Resolving intra-project imports in Python — A simple guide — PyCharm

project 

├─── folder1
│ │ __init__.py
│ │ file1.py

├─── folder2
│ │ __init__.py
│ │ file2.py

└─── tests
│ test_file.py

N.B. This project structure is fine for anyone who has no plans to distribute their code. If, however, you plan to distribute your code to others, e.g. through PyPI, you should consider using a src project structure instead. Follow this link (coming soon) for a step-by-step guide to project file import setup using a src project structure.

Import Statements

# project/folder1/file1.pydef add(num1, num2):
return num1 + num2
# project/folder2/file2.pyfrom folder1 import file1print('1 + 2 =', file1.add(1, 2))

Setting up imports for PyCharm Run Configurations

Setting up imports for the Terminal

project

├─── folder1
│ │ __init__.py
│ │ file1.py

├─── folder2
│ │ __init__.py
│ │ file2.py

├─── tests
│ │ test_file.py

└─── venv
(venv) C:\...\project> 
project
setup.py

├─── folder1
│ │ __init__.py
│ │ file1.py

├─── folder2
│ │ __init__.py
│ │ file2.py

├─── tests
│ │ test_file.py

└─── venv
# /project/setup.pyfrom setuptools import setup

setup(
name='project',
version='',
packages=['folder1', 'folder2'],
url='',
license='',
author='',
author_email='',
description=''
)
(venv) C:\...\project> py -m pip install -e .
(venv) C:\...\project> py -m pip install -e .
Obtaining file:///C:/.../project
Installing collecting packages: project
Running setup.py develop for project
Successfully installed project
project
│ setup.py

├─── folder1
│ │ __init__.py
│ │ file1.py

├─── folder2
│ │ __init__.py
│ │ file2.py

├─── project.egg-info

├─── tests
│ │ test_file.py

└─── venv
def add(num1, num2):
return num1 + num2
from folder1 import file1print('1 + 2 =', file1.add(1, 2))
(venv) C:\...\project> py folder2\file2.py
1 + 2 = 3
# output trimmed for brevityC:\...\project> pytestcollected 1 item.tests\test_file.py1 passed in 0.02s

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store