简体   繁体   中英

How to reference not-yet-declared functions in a global variable in Python?

I need to have a global dict with string as keys and function references as values. I don't want to write something similar to a switch, because I need to be able to fetch the keys list from another script. I tried to write a script looking like that :

GLOBAL_VARIABLE = {'id_1' : func_1,
                   'id_2' : func_2,
                   'id_3' : func_3
                  }

def get_id_list():
    return GLOBAL_VARIABLE.keys()

def func_1(arg):
    <do some stuff>

def func_2(arg):
    <do some stuff>

def func_3(arg):
    <do some stuff>

But when I do this, Python throws me an error " NameError: name 'func_1' is not defined ". The only two solutions I could think of were:

  • Declare the global variable at the end of the file, but then it's really annoying if I have to edit it, I'd rather have this info as close as possible from the top of the file.

  • Declare a hackish function "get_global_variable" that (create and) return the exact same dict. It's working, but it's pretty ugly.

Is there a way to do some lazy declaration and/or what would be a more pythonic way to tackle this situation?

The Pythonic way is to declare the variable after the function, regardless of how it may appear. Don't worry, other people will understand perfectly well why this is done.

Or if you really, really need to have variables appear before functions in a module, move the functions into a separate module and then import them. No kill like overkill...

Define a decorator that adds the function references to the dictionary as you define the functions.

GLOBAL_VARIABLE = {}
def export(tag):
    def _(f):
        GLOBAL_VARIABLE[tag] = f
        return f
    return _

@export('id_1')
def func_1(arg):
    <do some stuff>

@export('id_2')
def func_2(arg):
    <do some stuff>

@export('id_3')
def func_3(arg):
    <do some stuff>

I hate this but it would "work".

Instead of literal variables, the name of each function is put in GLOBAL_VARIABLE .

>>> GLOBAL_VARIABLE = {
...     "id_1": "func_1",
...     "id_2": "func_2",
...     "id_3": "func_3",
... }

The functions are defined like before.

>>> def func_1():
...     return 1
...
>>> def func_2():
...     return 2
...
>>> def func_3():
...     return 3
...

After the function definitions, the function names in GLOBAL_VARIABLE are looked up to find the actual functions. These replace the names.

>>> GLOBAL_VARIABLE = {key: globals()[value] for (key, value) in GLOBAL_VARIABLE
.items()}

>>> GLOBAL_VARIABLE["id_1"]
<function func_1 at ...>
>>> GLOBAL_VARIABLE["id_2"]
<function func_2 at ...>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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