Python Subpackages not available for import - python

I'm working from the basis of this previously posted problem:
module importing itself
Essentially, that problem is solved, but in the "modulename.py" file, there is a class defined, with an init function, and a ui function. Inside the class, any line of the form:
import submodule
Will function just fine. However..
import submodule.subsubmodule
or
import subsubmodule
Will produce an ImportError.
All submodules and subsubmodules have an
__init__.py
file.

This often happens if you have multiple modules with the same name inside a package.
For example, consider:
mypkg/
__init__.py
toplevel.py
mypkg.py
If the toplevel.py file calls import mypkg.mypkg, it will actually be importing the mypkg.py file and not the package.
You can solve this by including from __future__ import absolute_import as the first line in toplevel.py, which will force it to import the top-level package.
Alternatively, you can use from . import mypkg in toplevel.py, which will explicitly import the mypkg.py file.

Related

python import file path relative inside a import module / use module without installing

How do I import a module and use it as if I installed it without actually installing it? More specifically, when I do imports on an installed module, all the imports are relative to the module. However when I just import it, all the imports are relative to the module it is called from.
As a specific example, in the below I would like run_import.py to print module not parent. But because it imports cfg from the parent not the module, it prints the wrong one. I would like to be able to run module1 on a standalone basis and have it isolated from any code that is calling it, much like you would in an installed package.
Directory structure is
module1/
__init__.py
cfg.py
tasks.py
run_module.py
utils.py
cfg.py
run_import.py
utils.py
Code
# cfg.py
level = 'parent'
# module1/cfg.py
level='module'
# module1/tasks.py
import cfg
def run_it():
print(cfg.level)
# module1/run_module.py
import tasks
tasks.run_it() # prints 'module'
# module1/utils.py
def util_fun():
print('util module')
# utils.py
def util_fun():
print('util parent')
# run_import.py
import module1.tasks as tasks
tasks.run_it() # prints 'parent', would like it to print 'module'
import utils
utils.util_fun() # prints util parent, should not print util module
This give me what I was looking for but has the unintended consequence that everything gets imported relative to that module
import sys
sys.path.insert(0, "module1")
tasks.run_it() # prints 'parent'
import utils
utils.util_fun() # prints util module, not util parent
Here are a couple of answers I have looked it, they didn't seem to solve it.
What's the purpose of the "__package__" attribute in Python? this sounds like what is needed but not sure how that can be set
Python3 importlib.util.spec_from_file_location with relative path? look potentially promising but i'm not sure how to use it, particularly not sure what the file path should be
How to use a packed python package without installing it
Import a module from a relative path
Can a python module be imported without installing
Import module using relative paths
When you execute run_import.py, the imports are searching in the root folder (module1/).
So you can try changing module1/tasks.py
from module1 import cfg
def run_it():
print(cfg.level)
Try this, adding the module to the path works if you would only like to change run_import.py
import sys
sys.path.insert(0, "module1")
from module1 import tasks
tasks.run_it()

python submodule can't find import

So I have a module called gann which itself has a number of modules, the problem is that if I run gannController.py directly it fails.
I have the following file structure(some files omitted):
----convert
__init__.py
convert.py
----AI
__init__.py
----gann
gannController.py
----model
__init__.py
modelController.py
----util
now I want to use the gannController.py in the convert.py file.
from AI.gann import gannController
in convert.py does import gannController, however it crashes on the first line which is
from model import modelController
which does work if I run gannController.py directly. As it gives the error:
ModuleNotFoundError: No module named model
So I guess that it's because a submodule uses a submodule of it's own that I cannot run this. Anybody know how to fix this? It's worth noting that I would prefer not to pollute my convert namespace with all of the stuff in model and that I have omitted a few other modules that have the same situation (inside util)
Change your import to be relative:
from .model import modelController

Python __init__ file can't import modules

I know this question has been asked before but I couldn't get to an answer.
My package folder looks like this, no sub folders, just a flat package folder with .py files in it.
+Package
∣
∣--__init__.py
∣--moduleA.py
∣--moduleB.py
If I run my test.py script from inside the package folder, the imports, classes and methods work fine:
import moduleA.py
import moduleB.py
# ...stuff
Now, if I try to run my package from outside importing import Package, outside being \site-packages I get
File "defaultPathTo\Python\Python38\lib\site-packages\Package\__init__.py", line 1, in <module>
import moduleA
ModuleNotFoundError: No module named 'moduleA'
This is my init file
import moduleA
import moduleB
I tried changing the content to from moduleA import *, from . import moduleA
from .moduleA import (whatever class) seems to work, but I don't want to change all my classes from moduleA.ClassA because it clashes with class names from the other modules.
I think I summed up all the information neede. Thanks for the help
Using from . import moduleA for all imports from within my package did the trick.
I may have done something wrong the first time I tried because I got no known parent folder

Python: Importing a file from a parent folder

...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo.
I have a python file that wishes to import a file (that is in its parent directory). Can you help me figure out how my child file can successfully import its a file in its parent directory. I am using python 2.7.
The structure is like so (each directory also has the __init__.py file in it):
StockTracker/
└─ Comp/
├─ a.py
└─ SubComp/
└─ b.py
Inside b.py, I would like to import a.py: So I have tried each of the following but I still get an error inside b.py saying "There is no such module a".
import a
import .a
import Comp.a
import StockTracker.Comp.a
import os
import sys
sys.path.append('.')
import a
sys.path.remove('.')
from .. import a
Should do it. This will only work on recent versions of Python--from 2.6, I believe [Edit: since 2.5].
Each level (Comp and Subcomp) must also be have an __init__.py file for this to work. You've said that they do.
When packages are structured into
subpackages (as with the sound package
in the example), you can use absolute
imports to refer to submodules of
siblings packages. For example, if the
module sound.filters.vocoder needs to
use the echo module in the
sound.effects package, it can use from
sound.effects import echo.
Starting with Python 2.5, in addition
to the implicit relative imports
described above, you can write
explicit relative imports with the
from module import name form of import
statement. These explicit relative
imports use leading dots to indicate
the current and parent packages
involved in the relative import. From
the surround module for example, you
might use:
from . import echo
from .. import formats
from ..filters import equalizer
Quote from here http://docs.python.org/tutorial/modules.html#intra-package-references
If the Comp directory is in your PYTHONPATH environment variable, plain old
import a
will work.
If you're using Linux or OS X, and launching your program from the bash shell, you can accomplish that by
export PYTHONPATH=$PYTHONPATH:/path/to/Comp
For Windows, take a look at these links:
http://docs.python.org/using/windows.html
http://www.itechtalk.com/thread3595.html
EDIT:
To modify the path programmatically, you were on the right track in your original question. You just need to add the parent directory instead of the current directory.
sys.path.append("..")
import a

Python: import the containing package

In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?
Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...
Is there a pythonic way to do this?
Also, starting in Python 2.5, relative imports are possible. e.g.:
from . import foo
Quoting from http://docs.python.org/tutorial/modules.html#intra-package-references:
Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:
from . import echo
from .. import formats
from ..filters import equalizer
This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well.
If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod.
I'm not totally sure what the situation is, but this may solve your "different name" problem:
import __init__ as top
top.some_function()
Or maybe?:
from __init__ import some_function
some_function()
In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory.

Categories

Resources