georgez
georgez

Reputation: 735

Easier way to assign a value to multiple global variables in a function

I declared a few global variables in a python file and would like to reset their values to None in a function. Is there a better/hack/pythonic way to declare all variables as global and assign them a value in one line?

doctype, content_type, framework, cms, server = (None,)*5

def reset():
        doctype, content_type, framework, cms, server = (None,)*5

Upvotes: 1

Views: 1767

Answers (3)

ndpu
ndpu

Reputation: 22571

I would use one global mutable object in this case, dict for example:

conf = dict.fromkeys(['doctype', 'content_type', 'framework', 'cms', 'server'])

def reset():
    for k in conf:
        conf[k] = None

or class. This way you can incapsulate reset in class itself:

class Config():
    doctype = None
    content_type = None
    framework = None
    cms = None
    server = None

    @classmethod
    def reset(cls):   
        for attr in [i for i in cls.__dict__.keys()
                     if i[:1] != '_' and not hasattr(getattr(cls, i), '__call__')]:
            setattr(cls, attr, None)

Upvotes: 0

warvariuc
warvariuc

Reputation: 59674

Use globals to get a reference to the dict of global variables:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
>>> globals().update({'a': 2})
>>> a
2
>>> 

In your case:

globals().update({
    'doctype': None,
    'content_type': None,
    ...
})

Use a dict comprehension to do this in one line:

Or this:

for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
     globals()[var_name] = None

Or this:

module = sys.modules[__name__]
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
     setattr(var_name, None)

Upvotes: 1

zhangxaochen
zhangxaochen

Reputation: 34047

Chain =, since you're assining immutable None to them:

doctype = content_type = framework = cms = server = None

If you wanna use the reset function, you have to declare them as global inside it:

def reset():
    global doctype, content_type, framework, cms, server
    doctype = content_type = framework = cms = server = None

Upvotes: 2

Related Questions