Python: Sharing global variables between modules and classes therein

后端 未结 5 1350
不知归路
不知归路 2020-11-28 06:00

I know that it\'s possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example,

5条回答
  •  死守一世寂寞
    2020-11-28 06:58

    As Ned Batchelder mentioned, only the values are shared and not the actual object. If you want to share an object by reference, then you are probably looking Thread-Local Data.

    Eg:

    import threading
    
    g = threading.local()
    g.population = '7 Billion'
    

    Now, whenever you want to access or change the variable g.population, you will get an updated value of it, provided it is the same thread you are trying to access it from.

    Read more in the Python documentation:https://docs.python.org/3/library/threading.html#thread-local-data

提交回复
热议问题