Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Python

You're reading from   Mastering Python Master the art of writing beautiful and powerful Python by using all of the features that Python 3.5 offers

Arrow left icon
Product type Paperback
Published in Apr 2016
Publisher Packt
ISBN-13 9781785289729
Length 486 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Rick Hattem Rick Hattem
Author Profile Icon Rick Hattem
Rick Hattem
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Getting Started – One Environment per Project FREE CHAPTER 2. Pythonic Syntax, Common Pitfalls, and Style Guide 3. Containers and Collections – Storing Data the Right Way 4. Functional Programming – Readability Versus Brevity 5. Decorators – Enabling Code Reuse by Decorating 6. Generators and Coroutines – Infinity, One Step at a Time 7. Async IO – Multithreading without Threads 8. Metaclasses – Making Classes (Not Instances) Smarter 9. Documentation – How to Use Sphinx and reStructuredText 10. Testing and Logging – Preparing for Bugs 11. Debugging – Solving the Bugs 12. Performance – Tracking and Reducing Your Memory and CPU Usage 13. Multiprocessing – When a Single CPU Core Is Not Enough 14. Extensions in C/C++, System Calls, and C/C++ Libraries 15. Packaging – Creating Your Own Libraries or Applications Index

Creating a virtual Python environment using venv

Most Python programmers are already be familiar with venv or virtualenv, but even if you're not, it's never too late to start using it. The venv module is designed to isolate your Python environments so that you can install packages specific to your current project without polluting your global namespace. For example, having a filename such as sys.py in your current directory can seriously break your code if you expect to have the standard Python sys library—your local sys libraries will be imported before the global one, effectively hiding the system library. In addition, because the packages are installed locally, you don't need system (root/administrator) access to install them.

The result is that you can make sure you have exactly the same version of a package on both your local development machine and production machines without interfering with other packages. For example, there are many Django packages around that require specific versions of the Django project. Using venv, you can easily install Django 1.4 for project A and Django 1.8 for project B without them ever knowing that there are different versions installed in other environments. By default, the environments are even configured in such a way that the global packages are not visible. The benefit of this is that to get an exact list of all installed packages within the environment, simply a pip freeze will suffice. The downside is that some of the heavier packages (for example, numpy) will have to be installed in every separate environment. Needless to say, which choice is the best for your project depends on the project. For most projects, I would keep the default setting of not having the global packages, but when messing around with projects that have lots of C/C++ extensions, it would be convenient to simply enable the global site packages. The reason is simple; if you do not have a compiler available, installing the package locally can be difficult, while the global install has an executable for Windows or an installable package for Linux/Unix available.

Note

The venv module (https://docs.python.org/3/library/venv.html) can be seen as a slightly simplified version of the virtualenv tool (https://virtualenv.pypa.io/), which has been bundled with Python since version 3.3 (refer to PEP 0405 -- Python Virtual Environments: https://www.python.org/dev/peps/pep-0405/).

The virtualenv package can generally be used as a drop-in replacement for venv, which is especially relevant for older Python versions (below 3.3) that do not come bundled with venv.

Creating your first venv

Creating an environment is quite easy. The basic command comes down to pyvenv PATH_TO_THE_NEW_VIRTUAL_ENVIRONMENT, so let's give it a try. Note that this command works on Linux, Unix, and Mac; the Windows command will follow shortly:

# pyvenv test_venv
# . ./test_venv/bin/activate
(test_venv) #

Note

Some Ubuntu releases (notably 14.04 LTS) maim the Python installation by not including the full pyvenv package with ensurepip. The standard workaround is to call pyvenv --without-pip test_env, which requires a manual pip installation through the get_pip.py file available on the pip home page.

This creates an environment called test_venv, and the second line activates the environment.

On Windows, everything is slightly different but similar overall. By default, the pyvenv command won't be in your PATH, so running the command is slightly different. The three options are as follows:

  • Add the Python\Tools\Scripts\ directory to your PATH
  • Run the module:
    python -m venv test_venv
    
  • Run the script directly:
    python Python\Tools\Scripts\pyvenv.py test_venv
    

For convenience, I would recommend that you add the Scripts directory to your PATH anyhow, since many other applications/scripts (such as pip) will be installed there as well.

Here is the full example for Windows:

C:\envs>python -m venv test_venv
C:\envs>test_venv\Scripts\activate.bat
(test_venv) C:\envs>

Tip

When using Windows PowerShell, the environment can be activated by using test_venv\Scripts\Activate.ps1 instead. Note that you really do need backslashes here.

venv arguments

So far, we have just created a plain and regular venv, but there are a few, really useful flags for customizing your venv specifically to your needs.

First, let's look at the venv help:

Parameter

Description

--system-site-packages

It gives the virtual environment access to the system-site-packages directory

--symlinks

Try to use symlinks rather than copies when symlinks are not the default for the platform

--copies

Try to use copies rather than symlinks even when symlinks are the default for the platform

--clear

Delete the contents of the environment directory, if it exists, before environment creation

--upgrade

Upgrade the environment directory to use this version of Python, assuming that Python has been upgraded in-place

--without-pip

This skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default)

The most important argument to note is --system-site-packages, which enables the global site packages within the environment. This means that if you have a package installed in your global Python version, it will be available within your environment as well. However, if you try to update it to a different version, it will be installed locally. Whenever possible, I would recommend disabling the --system-site-packages flag because it gives you a simple environment without too many variables. A simple update of the system packages could break your virtual environment otherwise, but worse, there is no way to know which packages are needed locally and which ones are just installed for other purposes.

To enable this for an existing environment, you can simply run the environment creation command again, but this time adding the --system-site-packages flag to enable the global site packages.

To disable it again, you can simply run the environment creation command without the flag. This will keep the locally (within the environment) installed packages available but will remove the global packages from your Python scope.

Tip

When using virtualenvwrapper, this can also be done with the toggleglobalsitepackages command from within the activated environment.

The --symlinks and --copies arguments can generally be ignored, but it is important to know the difference. These arguments decide whether the files will be copied from the base python directory or whether they will be symlinked.

Note

Symlinks are a Linux/Unix/Mac thing; instead of copying a file it creates a symbolic link that tells the system where to find the actual file.

By default, venv will try to symlink the files, and if that fails, it will fall back to copying. Since Windows Vista and Python 3.2, this is also supported on Windows, so unless you're using a very old system, you will most likely be using symlinks in your environment. The benefit of symlinks is that it saves disk space and stays in sync with your Python installation. The downside is that if your system's Python version undergoes an upgrade, it can break the packages installed within your environment, but that can easily be fixed by reinstalling the packages using pip.

Finally, the --upgrade argument is useful if your system Python version has been upgraded in-place. The most common use case for this argument is for repairing broken environments after upgrading the system Python with a copied (as opposed to symlinked) environment.

Differences between virtualenv and venv

Since the venv module is essentially a simpler version of virtualenv, they are mostly the same, but some things are different. Also, since virtualenv is a package that is distributed separately from Python, it does have some advantages.

The following are the advantages of venv over virtualenv:

  • venv is distributed with Python 3.3 and above, so no separate install is needed
  • venv is simple and straightforward with no features besides the bare necessities

Advantages of virtualenv over venv:

  • virtualenv is distributed outside of Python, so it can be updated separately.
  • virtualenv works on old Python versions, but Python 2.6 or a higher version is recommended. However, Python 2.5 support is possible with older versions (1.9.x or lower).
  • It supports convenient wrappers, such as virtualenvwrapper (http://virtualenvwrapper.readthedocs.org/)

In short, if venv is enough for you, use it. If you are using an old Python version or want some extra convenience, such as virtualenvwrapper, use virtualenv instead. Both projects essentially do the same thing, and efforts have been made to easily switch between them. The biggest and most significant difference between the two is the wide variety of Python versions that virtualenv supports.

You have been reading a chapter from
Mastering Python
Published in: Apr 2016
Publisher: Packt
ISBN-13: 9781785289729
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image