"How to import function from `file.py` in `some_file.py`?"

How to import function from file.py in some_file.py?

Hey Heenakhan,

Using relative imports: Ensure app2 is treated as a package by adding an init.py file in the app2 folder. Then, use relative imports:

In some_file.py

from …app.folder.file import func_name Explanation: By adding init.py, you make the directories packages, allowing relative imports with dots representing parent directories.

Hello Heena,

Using sys.path manipulation: Add the application directory to the system path within your script before the import statement:

In some_file.py

import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), ‘…/…/…’)))

from app.folder.file import func_name

Explanation: This dynamically adds the application directory to sys.path, making the app module accessible for imports. The os.path.abspath and os.path.join ensure the correct path is added relative to the script’s location.

Hello Heenakhan,

Using sys.path manipulation: Add the application directory to the system path within your script before the import statement:

In some_file.py

import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), ‘…/…/…’)))

from app.folder.file import func_name

Explanation: This dynamically adds the application directory to sys.path, making the app module accessible for imports. The os.path.abspath and os.path.join ensure the correct path is added relative to the script’s location.