ImportError: cannot import name from __init__.py - python-3.x

I have a project structure as the following
src/
scripts/
script1
mylib
__init__.py
a_module.py
These are the contents of __init__.py
__version__ = '0.0.1'
But if I try to do this on script1:
from mylib import __version__ as _ver
It fails with this:
Traceback (most recent call last):
File "./script1", line 2, in <module>
from mylib import __version__ as _ver
ImportError: cannot import name '__version__'
Changing the var name doesn't help at all, i.e. this fails, too:
from mylib import a_ver as _ver
Every other variable in any other module gets imported correctly, e.g.
from mylib.a_module import a_var
Why? And how can I work around this?

You can use:
import mylib
_ver = mylib.__version__
del mylib

Related

import inside a python package - ModuleNotFoundError

I'm trying to build a package where specific modules call other modules. Example of the structure of the package:
provapackage/
├── main.py
└── pippo
├── derivative_functions.py
├── functions_pippo.py
└── __init__.py
content of the functions_pippo module:
def add(x,y):
return x+y
content of the derivative_functions module:
from functions_pippo import add
def add_lst(l):
n=0
for i in l:
n = add(n,i)
return n
content of the main.py file:
from pippo.derivative_functions import add_lst
lst = [1,2,3,4]
print(add_lst(lst))
when I run main.py I get this error:
Traceback (most recent call last):
File "/home/g/Documents/provapackage/main.py", line 1, in <module>
from pippo.derivative_functions import add_list
File "/home/g/Documents/provapackage/pippo/derivative_functions.py", line 1, in <module>
from functions_pippo import add
ModuleNotFoundError: No module named 'functions_pippo'
It seems like python cannot find the functions_pippo module even if it's in the same folder. But when I run derivative_functions.py I don't gat any error message. Is it an import problem?
See this answer here
from .functions_pippo import add
not
from functions_pippo import add

"ModuleNotFoundError" when importing my own classes

I have 2 files, both are in the same folder.
The file that I am trying to import is "HelloWorldClass.py"
(Code to HelloWorldClass.py)
class HelloWorld():
def __init__(self):
print("Hello World")
and the file that I am calling "HelloWorldClass" from is "ClassTest.py"
(Code to ClassTest.py)
from Classes import HelloWorldClass
HelloWorld()
and for some reason, I am getting this error...
Traceback (most recent call last):
File "D:/Coding file/Owl Hoot/Classes/ClassTest.py", line 3, in <module>
from Classes import HelloWorldClass
ModuleNotFoundError: No module named 'Classes'
>>>
Both files are in the Classes file. I don't see what I am doing wrong, can anyone help?
If both are in the same directory you can import like that:
from HelloWorldClass import HelloWorld

How to properly import subpackages in python?

I have an import error I don't understand. I made a minimal example below, a small namespace package called p_parent which contains no __init__.py file but contains another sub-package called c_child
here is the full arborescence:
p_parent
├── c_child
│   ├── c_main.py
│   └── __init__.py
└── p_main.py
c_main.py and p_main.py contains almost nothing. p_parent/c_child/__init__.py contains only an import.
Here is the shell script which rebuilds this:
mkdir p_parent
mkdir p_parent/c_child
echo '#!/usr/bin/env python3\n\nc_value = 4\n' > p_parent/c_child/c_main.py
echo '#!/usr/bin/env python3\n\np_value = 4\n' > p_parent/p_main.py
echo '#!/usr/bin/env python3\n\nimport p_parent.c_child.c_main as c\n' > p_parent/c_child/__init__.py
When the content of the __init__.py file is import p_parent.c_child.c_main as c I get an error I don't understand when I try to import the submodule:
>>> import p_parent.c_child
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/C/autools/release/2019.09/scade/package/p_parent/c_child/__init__.py", line 3, in <module>
import p_parent.c_child.c_main as c
AttributeError: module 'p_parent' has no attribute 'c_child'
But, what tells me I missed something really important, is that when the content of the __init__.py file is only import p_parent.c_child.c_main everything works as expected (except I have loooong names)
>>> import p_parent.c_child
>>> p_parent.c_child.c_main
<module 'p_parent.c_child.c_main' from '/<snip>/p_parent/c_child/c_main.py'>
>>> p_parent.c_child.c_main.c_value
4
with from p_parent.c_child.c_main * it work somehow, but I would prefere to avoid it:
>>> import p_parent.c_child
>>> p_parent.c_child.c_value
4
What is the logic here ? Why the error is so unintuitive ?
python3.6 is used

Cyclic import in Python3

I have the following directory structure:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py and player.py have import dependency on each other (cyclic imports).
game.py has the following definition.
from logic.player import RandomPlayer, InteractivePlayer
T = 8
class Game:
def __init__(self, p1, p2)
...
# some other things
if __name__ == '__main__':
p1 = RandomPlayer()
p2 = InteractivePlayer()
g = Game(p1, p2)
...
player.py is as follows:
from logic.game import T
class Player:
def __init__(self):
...
class RandomPlayer(Player):
def __init__(self):
...
class InteractivePlayer(Player):
def __init__(self):
...
I am trying to run the game from logic/ directory but I get the following error.
$ python3 game.py
Traceback (most recent call last):
File "game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
I then tried running game.py from the directory higher up (my-game/).
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
What am I doing wrong? How can I make these cyclic imports work?
I have also tried using this import in player.py
from .game import T
and using
from .player import RandomPlayer, InteractivePlayer
in game.py.
In this case, I get a different error. For example, when running from my-game/,
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package
I get a similar error when running from logic/ directory.
I looked at this post but didn't understand where I was going wrong.
You are made a circulair import in your code try to remove it from your import
Vist this link you can find some other info about circular import :Remove python circular import

Python flask blueprint ImportError: cannot import name 'bp'

I am trying to get my login page working with blueprints. Before I separated my python package into separate packages, the app was successfully running with just app.py. However, now I am trying to make it more modular, I am having trouble running the app and it does not let me import the blueprint I created.
My file structure is like this:
myapp/
run.py
myapp/
__init.py__
app.py
models.py
...
Here is my run.py:
from myapp import app
app.run(host= '0.0.0.0', debug=True)
I am initializing my blueprint in app.py like this:
....
from flask import Blueprint
bp = Blueprint('bp', __name__)
#bp.route('/')
#bp.route('/home')
....
I am calling it from __init.py__ like this:
app = Flask(__name__)
....
app.config...
app.config...
app.config...
....
from . import bp # line 35
app.register_blueprint(bp)
However, no matter what I change the import to, it keeps complaining that it cannot import
# python3 run.py
Traceback (most recent call last):
File "run.py", line 1, in <module>
from usb import app
File "/my/path/to/myapp/myapp/__init__.py", line 35, in <module>
from . import bp
ImportError: cannot import name 'bp'
I even tried changing from . import bp to from myapp.app import bp, and then it throws a different error AttributeError: module 'myapp.app' has no attribute 'register_blueprint'
Here is the full error:
Traceback (most recent call last):
File "run.py", line 1, in <module>
from myapp import app
File "/my/path/to/myapp/myapp/__init__.py", line 33, in <module>
app.register_blueprint(bp)
AttributeError: module 'myapp.app' has no attribute 'register_blueprint'
Does anyone know what I am doing wrong here?
As far as i understand, you need to replace from from . import bp to
from myapp.app import bp.
This happens because of __init__.py, which makes package from 'myapp' dir, and python wait import path with package name.
Here is a little exmaple:
Project Structure:
myapp\
myapp\
__init__.py
app.py
run.py
run.py listing:
from myapp import app
app.run(host='0.0.0.0', debug=True)
myapp\__init__.py listing:
from flask import Flask
from myapp.app import bp
app = Flask(__name__)
app.register_blueprint(bp)
myapp\app.py listing:
from flask import Blueprint
#bp.route('/')
#bp.route('/home')
def home():
return '<html><body><h1>Hello, World!</h1></body></html>'
This error occurs because you are calling the bp instance without first loading it. When the python interpreter tries to load the route, for example:
# app/catalog/routes.py
from app.catalog import bp
#bp.route('/')
def hello():
return "hello world"
and verifies that the bp instance has not yet been loaded, it returns the error, describing that it has not found the bp module.
so to resolve this, in the blueprint configuration file, it will be mandatory to call the route after registering the blueprint. example:
# app/catalog/__init__.py
from flask import Blueprint
bp = Blueprint('main', __name__, template_folder='templates')
from app.catalog import routes

Resources