简体   繁体   English

Python:缓存一个本地 function 变量以供后续调用

[英]Python: cache a local function variable for subsequent calls

In C/C++, a function can declare a local variable as static .在 C/C++ 中, function 可以将局部变量声明为static When doing so, the value remains in memory and is available to subsequent calls to the function (this variable is no longer local, but that's besides the point).这样做时,该值将保留在 memory 中,并且可用于随后对 function 的调用(此变量不再是本地变量,但除此之外)。

Is there a way to do something similar in Python, without having to declare any global variable outside of the function?有没有办法在 Python 中做类似的事情,不必在 function 之外声明任何全局变量?

Use case: a function that (among other things) uses a regex to extract a value from an input string.用例:function(除其他外)使用正则表达式从输入字符串中提取值。 I want to pre-compile the pattern ( re.compile() ), without having to declare the variable outside of the function scope.我想预编译模式( re.compile() ),而不必在 function scope 之外声明变量。

I can inject a variable directly into globals() :我可以将变量直接注入globals()

globals()['my_pattern'] = re.compile(...)

But it doesn't look like a good idea.但这看起来不是一个好主意。

You could use a function attribute.您可以使用 function 属性。 In Python, functions are first-class objects, so you can abuse of this feature to simulate a static variable:在 Python 中,函数是一等对象,因此您可以滥用此功能来模拟 static 变量:

import re

def find_some_pattern(b):
    if getattr(find_some_pattern, 'a', None) is None:
        find_some_pattern.a = re.compile(r'^[A-Z]+\_(\d{1,2})$')
    m = find_some_pattern.a.match(b)
    if m is not None:
        return m.groups()[0]
    return 'NO MATCH'

Now, you ca try it:现在,你可以试试:

try:
    print(find_some_pattern.a)
except AttributeError:
    print('No attribute a yet!')

for s in ('AAAA_1', 'aaa_1', 'BBBB_3', 'BB_333'):
    print(find_some_pattern(s))

print(find_some_pattern.a)

This is the output:这是 output:

No attribute a yet!
initialize a!
1
NO MATCH
3
NO MATCH
re.compile('^[A-Z]+\\_(\\d{1,2})$')

It is not the best approach (wrappers or callables are way more elegant, and I suggest you use one of them), but I thought this clearly explains the meaning of:这不是最好的方法(包装器或可调用对象更优雅,我建议您使用其中之一),但我认为这清楚地解释了以下含义:

In Python, functions are first-class objects.在 Python 中,函数是一等对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM