0

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!

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
Curiosity
  • 139
  • 2
  • 10
  • 4
    Why do you not want to use `import`? – BrenBarn Jan 13 '16 at 07:40
  • Instead of exposing a variable, consider having setter and getter functions instead. Take a look at the `property()` built-in function which gives the user the illusion of accessing a variable. – cdarke Jan 13 '16 at 08:05

3 Answers3

2

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

Community
  • 1
  • 1
Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
1

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.

Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
  • thanks, but i get an error "AttributeError: 'module' object has no attribute 'var'" .Since there are many variables, it would be useful if there is a better way to call "var" instead of "f1.var". Thanks again – Curiosity Jan 13 '16 at 07:31
  • you could reassign it with `var = f1.var`. But then you'll able to use it in current file but if you modify it variable changed only in that file not in the file `f1` – Anton Protopopov Jan 13 '16 at 07:35
  • This will not change the value in anywhere other than the file in which you type the import line. -1 – Burhan Khalid Jan 13 '16 at 07:51
  • It will not change the value in `f1`. – Burhan Khalid Jan 13 '16 at 08:06
0

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"

Dick Kniep
  • 518
  • 4
  • 11