How to import a function from parent folder in python?

后端 未结 2 373
离开以前
离开以前 2021-01-21 03:17

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 so

相关标签:
2条回答
  • 2021-01-21 03:40

    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!

    0 讨论(0)
  • 2021-01-21 03:47

    The fact that you have an __init__.py tells me that PythonClient is itself a library. Do from PythonClient.hashes.hash_function import hash_function. I always like fully qualified paths.

    You need to install your library too before you can import from it. That requires a setup.py file in your home directory. After that, you should pip install your library for testing, e.g., `pip install -e .

    0 讨论(0)
提交回复
热议问题