I need to perform an import of a function on my python project.
I know there're dozens of similar questions on SO, however, unfortunately, I couldn't find the right solution for me because the answers are either too question specific, or way too general, or they're just ugly hacks (like operating with absolute paths).
Here's how my folder structure looks like:
PythonClient:.
│ .gitignore
│ des.py
│ des_test.py
│ des_var2.py
│ gui.py
│ index.py
│ __init__.py
│
├───diffie_hellman
│ │ diffie_hellman.py
│ │ diffie_hellman_test.py
│ │ __init__.py
│ │
│ └───__pycache__
│ diffie_hellman.cpython-35.pyc
│
├───hashes
│ │ collision.py
│ │ hash_function.py
│ │ __init__.py
│ │
│ └───__pycache__
│ hash_function.cpython-35.pyc
│ __init__.cpython-35.pyc
│
└───__pycache__
des.cpython-35.pyc
des_var2.cpython-35.pyc
I need to import the ./hashes/hash_function.py
from ./diffie_hellman/diffie_hellman.py
.
The ./hashes/hash_function.py
file contains the only function named hash_function
.
I've tried quite a number of ways to perform the import but just couldn't do it. I always get either
SystemError: Parent module '' not loaded, cannot perform relative import
when I use .
in my import statement (i.e. from .hashes.hash_function
)
or I get this:
ImportError: No module named 'hashes'
Every __init__.py
file is empty.
Here's the list of my attempts:
from hashes import hash_function
from hashes.hash_function import hash_function
from .hashes.hash_function import hash_function
from ..hashes.hash_function import hash_function
import hashes
import hash_function
from .. import hash_function
from . import hash_function
from PythonClient.hashes.hash_function import hash_function
Could you please help me to resolve my problem and to understand how to work with such imports?
PS: The solution couldn't be found here stackoverflow.com/questions/14132789/
I know you have already accepted an answer, but if you wanted a less "permanent" solution (that is to say, if you didn't want to install your code), another option would be to simply add the parent of your PythonClient directory to your path. This can be done permanently (which varies depending upon operating system) or temporarily in code:
import os
import sys
p = os.path.abspath('../..')
if p not in sys.path:
sys.path.append(p)
from PythonClient.hashes.hash_function import hash_function
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With