Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, importing from same module: ImportError: cannot import name 'blah', __name__ == '__main__'

Tags:

python

Very easy issue to replicate. My current setup is:

package/
    __init__.py
    run.py

In my __init.py__ I have:

blah = 4

And in my run.py I have:

from package import blah


if __name__ == '__main__':
    print(blah)

I simply run it with python run.py. But I am getting ImportError: cannot import name 'blah'.

How come I am not being able to import a variable from my package? I know how to workaround it, I am rather interested in knowing the reason for the error.

like image 812
renatodamas Avatar asked Nov 02 '25 17:11

renatodamas


1 Answers

You are clearly trying to execute this as a package, but you are running "run.py" as if it were a standard python script. run.py does not have a concept of module in the sense of how you are trying to run it. You need to re-architect your design here. in the package module run.py would be a module (these are your naming conventions here). So module is the package, and run.py is a module. You then need a __main__.py to execute this as a package and you need to change your run.py:

run.py:

#!/usr/bin/env python3

from module1 import blah

def run():
    print(blah)

__main__.py:

#!/usr/bin/env python3
from module1 import run

def main():
    run.run() # run is the module name, and run is also the function name so we execute with run.run

main()

__init__.py:

blah = 4

directory structure:

module1/ - __init__.py - __main__.py - run.py

to execute (outside of module1):

[dkennetz@nodem103  fun]$ python3.5 -m module1
4

If you do not want to make this a package, you should simply create a directory called package and inside you can make run.py and variables.py.

variables.py:

blah=4
blahblah=8
blahblahblah=12

run.py:

from variables import blah
print(blah)

prints 4

if you changed run.py to:

from variables import blah, blahblah

print(blah)
print(blahblah)

[dkennetz@nodem103  package]$ python3.5 run.py
4
8

Or you can import all variables by changing run.py to:

from variables import *
print(blah)
print(blahblah)
print(blahblahblah) # if this was added to variables.py as 12

It returns:

[dkennetz@nodem103  package]$ python3.5 run.py
4
8
12
like image 198
d_kennetz Avatar answered Nov 05 '25 09:11

d_kennetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!