Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a module variable vs. a global variable?

From a comment: "global in Python basically means at the module-level". However running this code in a file named my_module.py:

import my_module as m

foo = 1
m.bar = m.foo + 1

if __name__ == "__main__":
    print('foo:', foo)
    print('m.foo:', m.foo)
    print('m.bar:', m.bar, '\n')

    for attrib in ('foo', 'bar'):
        print("'{0}' in m.__dict__: {1}, '{0}' in globals(): {2}".format(
            attrib,
            attrib in m.__dict__,
            attrib in globals()))

Output:

foo: 1
m.foo: 1
m.bar: 2 

'foo' in m.__dict__: True, 'foo' in globals(): True
'bar' in m.__dict__: True, 'bar' in globals(): False

What exactly are the module and global namespaces?

Why is there a __dict__ attribute in module namespace but not in global namespace?

Why is m.bar part of __dict__ and not part of globals()?

like image 828
mins Avatar asked Sep 03 '17 12:09

mins


People also ask

What is the difference between a variable and a global variable?

Practical Data Science using PythonA global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

What is module global variable?

A global variable is a variable which is accessible in multiple scopes. In Python, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.

What are variables in module?

Variables in ModuleThe module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

What are the two types of global variables?

A global variable can be classified as either session or database based on the scope of the value: The value of a session global variable is uniquely associated with each session that uses this particular global variable. Session global variables are either built-in global variables or user-defined global variables.


1 Answers

There are basically 3 different kinds of scope in Python:

  • module scope (saves attributes in the modules __dict__)
  • class/instance scope (saves attributes in the class or instance __dict__)
  • function scope

(maybe I forgot something there ...)

These work almost the same, except that class scopes can dynamically use __getattr__ or __getattribute__ to simulate the presence of a variable that does not in fact exist. And functions are different because you can pass variables to (making them part of their scope) and return them from functions.

However when you're talking about global (and local scope) you have to think of it in terms of visibility. There is no total global scope (except maybe for Pythons built-ins like int, zip, etc.) there is just a global module scope. That represents everything you can access in your module.

So at the beginning of your file this "roughly" represents the module scopes:

enter image description here

Then you import my_module as m that means that m now is a reference to my_module and this reference is in the global scope of your current file. That means 'm' in globals() will be True.

enter image description here

You also define foo=1 that makes foo part of your global scope and 'foo' in globals() will be True. However this foo is a total different entity from m.foo!

enter image description here

Then you do m.bar = m.foo + 1 that access the global variable m and changes its attribute bar based on ms attribute foo. That doesn't make ms foo and bar part of the current global scope. They are still in the global scope of my_module but you can access my_modules global scope through your global variable m.

enter image description here

I abbreviated the module names here with A and B but I hope it's still understandable.

like image 86
MSeifert Avatar answered Oct 16 '22 20:10

MSeifert