Modularity
Modularity
# math_operations.py # main.py
import math_operations
Consider the package named Here is how you can use this
mypackage with the following package:
directory structure:
# Alternatively, use shorter names with 'as'
import mypackage.math_operations as math_ops
mypackage/ import mypackage.geometry.area as geometry_area
├── __init__.py
├── area.py
└── volume.py
Where should I put my package?
In principle, it should be at the same location of the main code.
Nevertheless, you can change the PYTHONPATH to include the
location of your package.
Changing it locally
import sys
print(sys.path) # Shows the actual path
sys.path.append('/path/to/your/package') # Append the path of your package
import mypackage.module1
Where should I put my package?
Changing it globally
export PYTHONPATH="/path/to/your/package:$PYTHONPATH"
There is a third way of doing this, but we will cover it in detail in the
following section.
Environments
• Python virtual environments are an important concept in Python
programming that allow you to create isolated environments for
your projects.
• These environments ensure that dependencies for one project do
not interfere with other projects, and they help manage package
versions effectively.
• To create a virtual environment, you can use the venv module or
third-party tools like virtualenv or conda . We will use the first.
venv usage
1. Open a terminal and navigate to the directory where you want to
create your project's environment. Then write:
# On Windows
myenv\Scripts\activate
# On macOS and Linux:
source myenv/bin/activate
venv usage
3. Now you can install packages using conda or pip . Packages
installed in the virtual environment are isolated from the global
Python installation.
Sometimes pip or anaconda hang out. The solution is to use the -v (verbose) flag.
deactivate
Example
This is the unique library that our environment has. To check this,
write
pip freeze
and you will get the libraries (and their respective versions)
installed in your env.
Requirements
Suppose that you need a specific version (let's say 1.0 ) of a library
called library . Then you should write
setup(
name="my_package",
version="1.0.0",
packages=find_packages(),
description="A package for mathematical operations and geometry",
author="Your Name",
author_email="[email protected]",
url="https://github.com/yourusername/my_package",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.9"
],
python_requires=">=3.7",
install_requires=['wheel', 'bar', 'greek']
)
setup.py