Relative imports in Python 3

前端 未结 16 1097
误落风尘
误落风尘 2020-11-21 06:42

I want to import a function from another file in the same directory.

Sometimes it works for me with from .mymodule import myfunction but sometimes I get

16条回答
  •  面向向阳花
    2020-11-21 07:19

    Hopefully, this will be of value to someone out there - I went through half a dozen stackoverflow posts trying to figure out relative imports similar to whats posted above here. I set up everything as suggested but I was still hitting ModuleNotFoundError: No module named 'my_module_name'

    Since I was just developing locally and playing around, I hadn't created/run a setup.py file. I also hadn't apparently set my PYTHONPATH.

    I realized that when I ran my code as I had been when the tests were in the same directory as the module, I couldn't find my module:

    $ python3 test/my_module/module_test.py                                                                                                               2.4.0
    Traceback (most recent call last):
      File "test/my_module/module_test.py", line 6, in 
        from my_module.module import *
    ModuleNotFoundError: No module named 'my_module'
    

    However, when I explicitly specified the path things started to work:

    $ PYTHONPATH=. python3 test/my_module/module_test.py                                                                                                  2.4.0
    ...........
    ----------------------------------------------------------------------
    Ran 11 tests in 0.001s
    
    OK
    

    So, in the event that anyone has tried a few suggestions, believes their code is structured correctly and still finds themselves in a similar situation as myself try either of the following if you don't export the current directory to your PYTHONPATH:

    1. Run your code and explicitly include the path like so: $ PYTHONPATH=. python3 test/my_module/module_test.py
    2. To avoid calling PYTHONPATH=., create a setup.py file with contents like the following and run python setup.py development to add packages to the path:
    # setup.py
    from setuptools import setup, find_packages
    
    setup(
        name='sample',
        packages=find_packages()
    )
    

提交回复
热议问题