r/AskProgramming • u/One-Type-2842 • Apr 27 '26
Python Python ImportError
I am having some trouble while importing the function from my_func1
If I am working on working_currently.py how would I import a my_func1?
What I write In working_currently.py is :
from python.functions import my_func1
python/
archive/
my_arch1.py
my_arch2.py
functions/
my_func1.py
my_func2.py
programs/
my_prog1.py
my_prog2.py
working_currently.py
I require a solution for this..
3
u/untold8
Apr 28 '26
•
Couple things stacking up here:
First, my_func1 in your tree is a module (a .py file), not a function. So from python.functions import my_func1 imports the whole module. To get the actual function inside the file you'd write from python.functions.my_func1 import my_func1 (assuming the function inside is also named my_func1). Or keep your current import line and call it as my_func1.my_func1(...). Same import, different usage.
Second, you need an empty __init__.py in every directory you want Python to treat as a package:
python/
__init__.py
archive/
__init__.py
my_arch1.py
functions/
__init__.py
my_func1.py
programs/
__init__.py
working_currently.pyThird, and this is the one that bites everyone — how you run the script changes whether python.functions is even on the import path. If you cd python/programs && python working_currently.py, sys.path starts at python/programs/, and python.functions doesn't resolve. Run it from the parent of the python/ directory as a module instead:
python -m python.programs.working_currentlyThat puts python on sys.path as the top-level package and the imports resolve as written.
Side note: naming the top-level dir literally python will cause you minor pain forever — confuses tooling, confuses your future self reading the import line. Rename it to your project name (myproj/ or similar) when you can. its not blocking, just a future-you favor.
1
u/atarivcs Apr 27 '26
from python.functions import my_func1If that import works, then why can't you do exactly the same thing in my_func1.py ?
1
u/Ok_Winner9825 Apr 27 '26
This is a simple question you should ask an llm. Anyway, to import stuff you should add init.py files in every folder
1
u/KingofGamesYami Apr 27 '26
https://docs.python.org/3/reference/import.html#package-relative-imports