-1

One of the ways I recently started structuring my programming is by having one main file and multiple different appropriately named files that represent different parts of the project that I am working on.

All different Python Files in one folder.

To then use one file I would simply type:

import filename

This works all well and good, but I noticed that I can't use variables from within another file in that code.

My question is can I import variables, or pass variables from one file to another to make use of them later again?

pppery
  • 3,731
  • 22
  • 33
  • 46
  • To be clear; your asking how to access global variables that exist in one file from another file? – AlG Nov 20 '15 at 13:33

2 Answers2

2

Each file you import is considered to have its own namespace. You can reference anything in that namespace if you prefix it with the module name.

For example, f you have a file like this:

# filename.py
foobar = 42

You can access foobar with filename.foobar. For example:

import filename
print("foobar is %s" % filename.foobar)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Great! That works, but it doesn't really pass the variable from one location to the next. –  Nov 20 '15 at 13:51
  • @AlexPanagis: I'm not sure what you mean by "pass the variable". Certainly, you can pass the variable from one function to the next. It's a normal variable, you treat it like any other variable. – Bryan Oakley Nov 20 '15 at 14:46
-1

Another way is to use __builtin__ module so that your file main_file.py will contain:

print(thing)

while your whatever.py will contain:

import __builtin__
__builtin__.thing = 1
import main_file

More on that: here

Community
  • 1
  • 1
Paul
  • 37
  • 2