Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a cross-module variable?

The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?

The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.

like image 332
Dan Homerick Avatar asked Sep 26 '08 23:09

Dan Homerick


People also ask

How do I share a variable across a module in Python?

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name. Hope it works!!

How do you pass a variable from one module to another in Python?

So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object.

How do I use a global variable in another Python file?

To use global variables between files in Python, we can use the global keyword to define a global variable in a module file. Then we can import the module in another module and reference the global variable directly. We import the settings and subfile modules in main.py . Then we call settings.


1 Answers

If you need a global cross-module variable maybe just simple global module-level variable will suffice.

a.py:

var = 1 

b.py:

import a print a.var import c print a.var 

c.py:

import a a.var = 2 

Test:

$ python b.py # -> 1 2 

Real-world example: Django's global_settings.py (though in Django apps settings are used by importing the object django.conf.settings).

like image 168
jfs Avatar answered Oct 18 '22 06:10

jfs