What is a module variable vs. a global variable?

前端 未结 1 912
无人共我
无人共我 2021-02-04 14:18

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         


        
相关标签:
1条回答
  • 2021-02-04 14:21

    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:

    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.

    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!

    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.

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

    0 讨论(0)
提交回复
热议问题