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!

2
  • 4
    Why do you not want to use import? Commented Jan 13, 2016 at 7: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. Commented Jan 13, 2016 at 8:05

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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
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
This will not change the value in anywhere other than the file in which you type the import line. -1
It will not change the value in f1.
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.