import packages from project directory

Stack Overflow Asked by Will Waltrip on November 30, 2020

I have the below file structure:


within I am running the following import command:

from package_C.c_module import someFunc

I am continually getting a ModuleNotFoundError: No module named 'package_C'. I have tried a number of different things from using a pipenv shell within the project directory, adding a Pipfile to the project directory. Also creating a virtual environment.

Right now the file is empty as I am just starting the project, is the issue?

2 Answers

I'm guessing that the in the package_C folder is blank?

Just putting an in the a package folder does not automatically give you access to all modules within the package. You only get access to the modules that are imported in the file.

This is because when you import a package python runs all the modules in the file and adds them to the symbol table.

If you add import c_module in the file, you should be able to import any objects from c_module.

Answered by pykam on November 30, 2020

For IDE like pycharm will automatically add parents directory to path, thus when ran manually it won't find packages as it's not listed in parents directory.

See this example:

# file:

    from A import a
    print("IDE import")
except ImportError:
    from os import getcwd
    from sys import path

    path.append(getcwd() + "/..")
    from A import a
    print("without IDE")


Folder structure:
color is always beautiful

Output - in IDE:

IDE import
<module 'A.a' from 'Z:\github\StackOverFlow\A\'>

Output in terminal:

without IDE
<module 'A.a' from 'Z:\github\StackOverFlow\B/..\A\'>

And this also changes when directory is nested once more in project directory, in that case it will always import with path insertion used in except block.

Answered by jupiterbjy on November 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP