DEV Community

Emmanuel K
Emmanuel K

Posted on

1

Local Python Module imports when using virtualenv

Importing modules in python3 can be unnecessarily confusing, especially when using virtualenv

Suppose you have this file structure:

.env
test.py
cool_modules
    |--__init__.py
    |--cool_module1.py
    |--cool_module2.py
Enter fullscreen mode Exit fullscreen mode

To prevent import errors while using virtualenv .env:

cool_module1.py:

class CoolModule1():
    ...
Enter fullscreen mode Exit fullscreen mode

cool_module2.py:

class CoolModule2():
    ...
Enter fullscreen mode Exit fullscreen mode

Here's the critical part.
init.py:

# The part to note here is you have to use `parent_folder.child_file`
from cool_modules.cool_module1 import CoolModule1
from cool_modules.cool_module2 import CoolModule2
Enter fullscreen mode Exit fullscreen mode

test.py:

from cool_modules import CoolModule1, CoolModule2
Enter fullscreen mode Exit fullscreen mode

That's it!

If this helped you out, follow me on Twitter: emmanuel_n_k

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post