Many programming languages have a rich set of libraries and frameworks. Python is no exception. To speed up the development process and effective reuse, projects typically make use of a handful of libraries.
Python libraries are stored in a public repository called PyPI (stands for Python Package Index). A Utility called pip is used to install new libraries and frameworks into the target machine. Packages can be installed using below command:
$ pip install <package_name>
With the above command, a newly requested library is downloaded from the public repository and globally installed in the system directory of the Python installation directory. This means a newly installed library will be available to all of the Python applications of the installed machine.
Imagine this scenario - If I have three Python projects that require three different versions of a Python framework called Flask and if I install a newer version of Flask on top of the older version globally using the pip command, I might accidentally overwrite the older version of the Flask framework. My application that requires the older version of the library might not function properly.
Here is an illustration of 3 Python applications within the developer’s machine with the requirement of different versions of same framework:
Python’s virtual environment addresses this issue. With the Python virtual environment, specific versions of libraries are installed and maintained within the project. This helps in effective version conflict management among applications. Now same machine could successfully run applications with different versions of libraries.
How to set up virtual environment?
Run below command in the project folder to create a virtual environment in Python 3:
$ python3 -m venv venv
The above command invokes Python 3's venv command to create a virtual environment in a folder called venv. After successful execution above command project folder would a new subfolder called venv.
Virtual environment could be activated in the project by running below command in the terminal window:
$ source venv/bin/activate
Run below command to activate virtual environment in Windows:
With the activation of virtual environment, pip install command installs different versions of libraries within the newly created
venv folder within the project resulting in effective conflict management of different versions of library among projects.
Oldest comments (0)