Skip to content
Advertisement

Tag: python-import

How to use a module as part of a package and as a directly executable script?

Lets say i have a package folder called my_package. This directory contains a file called __init__.py and a module file called my_module.py among further module files. The module my_module.py contains the function do_something_with_file(file_path). The function is used in other parts of the package but it would be practical if it could be called as a command line script that takes

Import function from submodule in __init__.py without exposing submodule

I’ working on a Python project with a directory structure similar to this: Where the module bar1 defines the function function1. I would like to have users of my code import function1 (and nothing else) directly from foo, i.e. via from foo import function1. Fair enough, that can be achieved with the following foo/__init__.py: The problem now is that someone

‘ModuleNotFoundError’ when trying to import module from imported package

This is my directory structure: man1.py contains the following import statement, which I do not want to change: man1test.py contains the following import statements: I need the second import in man1test.py because man1test.py needs access to a function in man1.py. My rationale behind the first import (Soft) was to facilitate the aforementioned import statement in man1.py. Contrary to my expectation,

Python circular imports with inheritance

I have a parent and child class, where a parent’s method returns an instance of the child. Both classes are in separate files classA.py and classB.py. In order to avoid circular imports when I import classA I added the classB import to the end of classA.py (as shown below). Everything worked well and I was able to properly use classA

Relative imports in Python 3

I want to import a function from another file in the same directory. Usually, one of the following works: …but the other one gives me one of these errors: Why is this? Answer unfortunately, this module needs to be inside the package, and it also needs to be runnable as a script, sometimes. Any idea how I could achieve that?

Advertisement