What is a Python Virtual Environment?
A virtual environment is simply a tool that separates the dependencies of different projects by creating a separate isolated environment for each project.
Why we need to use Virtual Environment?
Did you know Linux and macOS come preinstalled with a version of Python that the operating system uses for internal tasks?
Yes, you know that If you install packages to your operating system’s global Python, these packages will mix with the system-relevant packages. This mix-up could have unexpected side effects on tasks crucial to your operating system’s normal behavior.
And, did you know One of your projects might require a different version of an external library than another one?
Again yes, you know that If you have only one place to install packages, then you can’t work with two different versions of the same library.
These are the most common reasons for the recommendation to use a Python Virtual Environment.
What is the interesting direnv?
In the classic way of using Virtual Environment, after you creat it you should activate, do your work then deactivate it. I know myself and im looking for the solution that more easy than the other solutions.what about you?
Exactly yes, so lets go to use direnv with following the steps bellow:
- Use your system package manager to install direnv, for example on macOS you can install it with brew : open your terminal and type
brew install direnv.
- In your terminal type
open .zshrcand paste this command
eval "$(direnv hook zsh)"on it.
- Go to the directory that your project placed on with
cd example directory
echo “layout python3” > .envrc
- If this error "direnv: error .envrc is blocked. Run direnv allow to approve its content " occures, type
Now we have a Virtual Environment that when you leave the directory, automatically deactivated and when you come back, automatically activated.isnt it amazing? So you can enjoy it.