Curiosity
Curiosity

Reputation: 139

Easiest way to share variables among files in Python?

I have a project with many Python files. There are certain number of variables in some files which I like to use in other files. For example, if

var=10

is defined in f1.py, what are the ways I can call/use "var" in other files without using from f1 import var ?

I tried using global but it doesn't work across all the files. Thank you!

Upvotes: 0

Views: 336

Answers (3)

Dick Kniep
Dick Kniep

Reputation: 528

Most of the times I encounter this problem I use different methods:

  1. I put all constants that are to be used in all programs in a separate program that can be imported.
  2. I create a "shared variables object" for variables that are to be used in several modules. This object is passed to the constructor of a class. The variables can then be accessed (and modified) in the class that is using them.

So when the program starts this class is instantiated and after that passed to the different modules. This also makes it flexible in that when you add an extra field to the class, no parameters need to be changed.

class session_info:
    def __init__(self, shared_field1=None, shared_field2=None ....):
        self.shared_field1 = shared_field1
        self.shared_field2 = shared_field2

def function1(session):
    session.shared_field1 = 'stilton'

def function2(session):
    print('%s is very runny sir' % session.shared_field1)

session = session_info()    
function1(session)
function2(session)

Should print: "stilton is very runny sir"

Upvotes: 0

Rolf of Saxony
Rolf of Saxony

Reputation: 22453

Declare all of your global variables in one file i.e. my_settings.py and then import that in your other scripts.

See this question and it's accepted answer for details: Using global variables between files in Python

Upvotes: 2

Anton Protopopov
Anton Protopopov

Reputation: 31682

You could do it with namescope:

import f1
print(f1.var)
10

f1.var = 20

Then it should change var in all files which are using that variable with import.

Upvotes: 1

Related Questions