简体   繁体   中英

Setting function parameter as global variable

I'm trying to simply make a parameter received by a function accesible for all other functions in a file, or be set as a global variable, and not have to pass it as an argument for all other functions. So far I've tried to set it as a global variable but apparently cannot have a parameter be also a global.

Here would be a simple example of what I would like:

def add(a,b, verbose):
    global verbose
    return a + b

result = add(2,3, False)
print(verbose)

In my case the called function is on another file, so cannot set verbose as a global beforehand. Any help would be appreciated!

If you want to assign to the global verbose variable inside your function, you can do this:

def add(a,b, verbose_value):
    global verbose
    verbose = verbose_value
    return a + b

result = add(2,3, False)
print(verbose)

First point, as a general rule, globals are evils - or, more exactly, mutating or worse rebinding globals from within a function should be avoided as much as possible.

Second point: in Python, 'global' really means 'module-level' - there's no 'process-level' globals (note that this is a designed choice, based on first point above)

Third point: for your general use case (application settings), the 'less evil' ways would be to have all your modules using a settings system so instead of "passing the param to a function that sets it as global so you don't need to pass it around", your modules just import the settings and read the param's value from there (cf django settings for an example).

The drawbacks are that 1/ only your own code can use those settings and 2/ it makes your code dependant on those settings (which can sometimes be a PITA).

And finally, given the "verbose" name, I assume you want to configure the verbosity level of your program's debugging / error outputs. The proper way to do that in a standard, portable and well decoupled way (which will fix both drawbacks above for this feature) is to use the stdlib's logging package . This package is designed to decouple logger's use (in the 'library' code, using logger.log(level, msg, ...) or one of it's shortcuts) from logging configuration (which is application/installation specific). It requires a bit of learning at first but from experience it's time well spent and actually very quickly saves time.

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