How to import Common.py using relative path in Python?

How do I use Python import relative path to import Common.py from both Server.py and Client.py? My project structure is as follows:

Proj/
    Client/
        Client.py
    Server/
        Server.py
    Common/
        __init__.py
        Common.py

Using sys.path.append (Hacky Way) In some situations, especially if you’re not installing your package or if you are working with specific frameworks like Django, you might still use a workaround to import Common.py dynamically. You can add the Common folder to your sys.path, which tells Python where to look for modules. Here’s how you can do it:

import sys, os sys.path.append(os.path.join(os.path.dirname(file), ‘…’, ‘Common’)) import Common

The os.path.dirname(file) function gives you the directory of the current script, and then you navigate to the Common/ folder to import Common.py.

Great suggestions from both @ishrth_fathima If you’re looking for more control over how you import modules, particularly with dynamic paths or more complex setups, you might want to explore the importlib module. It’s a powerful tool that gives you complete flexibility. Here’s how you can use it for a python import relative path from within your project:

import importlib.util
import os

module_name = 'Common'
module_path = os.path.join(os.path.dirname(__file__), '..', 'Common', 'Common.py')

spec = importlib.util.spec_from_file_location(module_name, module_path)
common_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(common_module)

This method works great when you need to import dynamically from a relative path and gives you fine-tuned control over the import process. It’s especially useful when you’re working with unconventional or constantly changing directory structures. Plus, it helps you avoid issues that might arise with sys.path.append in the long run