-1

The question is pretty simple: I need to move a piece of my code to the another file. In the main file, I'll do something like import not_main. Is is possible to run imported code as a part of the main file? Here's a simplified example:

__code
    \__main.py
    |__not_main.py

main.py content:

a = 5
import not_main

not_main.py content:

print a

When I'm running main.py, there is a error : NameError: name 'a' is not defined. How can I make it work? Thanks for any tips.

Sergey Potekhin
  • 621
  • 1
  • 11
  • 27
  • 2
    When you split your code into multiple files, you're supposed to perform the split along clean function boundaries and communicate between code in different files through function arguments and return values, *not* just literally cut and paste code sections out of one file into another and treat `import` as "run this other file's contents now". – user2357112 Mar 07 '17 at 23:19

1 Answers1

1

It's not possible to directly reference a variable in one module that's defined in another module unless you import that module first. Doesn't matter that it's the main module, this error would happen if you tried to do the same between any two modules. An imported module does not gain the scope of the module it's imported into.

There are possible workarounds, though I would caution using them if the code you're trying to separate out is fairly complex. But if you're intent on doing it, I'd suggest separating out any variables needed in both modules into a third module that only contains those variables. So the simple example you gave would turn into this:

cross_module_variables.py:

a = 5

main.py:

import not_main

not_main.py:

import cross_module_variables as cmv
print cmv.a

For more complex code you might need to assign the value of the variable in main after doing executing some code to produce the value. In that case you'll want to import cross_module_variables into the main module and assign a value to it. Course that variable has to be instantiated before it can be used in main so you'll have define the variable in cross_module_variable with some default value. So it would look something more like this:

cross_module_variables.py:

a = 0

main.py:

import cross_module_variables as cmv
cmv.a = 5
import not_main

not_main.py:

import cross_module_variables as cmv
print cmv.a

See this answer for more info on cross module variables.

With all that said, I would highly suggest you look at restructuring your code in some other sane way. It sounds like you're running all your code straight in modules instead of defining functions around discrete sections of code. You should look into ways of designing coherent functional programs.

Community
  • 1
  • 1
gph
  • 116
  • 3