Python

Virtual Environments

1. Create a virtual environment for a project:

 $ cd my_project_folder
 $ virtualenv my_project
 

2. To begin using the virtual environment, it needs to be activated:

 
 $ source my_project/bin/activate

3. If you are done working in the virtual environment for the moment, you can deactivate it:

 $ deactivate

Packaging Code

Suggest workflow via Github Actions:

  • on Pypi, create a Token for the “organization” with “global” scope

  • on Github > Settings > Secrets > Add a secrets.

    • Warning: if you created the token at the organization level, you should create a secrets for the organization (not the repos)

  • Create a Github action template for “publishing”

  • Github uses twine to publish the package, everytime a release is created (does not work for draft releases)

  • Edit the .yml file with the credentials for connecting to Pypi

  • To debug, you can create the package locally and verify its integrity:

    • Install twine: pip install twine

    • Build the distribution: python setup.py sdist bdist_wheel

    • Check integrity: twine check dist/*

Tips and Tricks

Nice Packages

- pytest-sugar: Nice visualization for pytestEdit

Matplotlib

Display 2d array:

from matplotlib.pylab import *
matshow(data2d, fignum=1, cmap=cm.gray), plt.colorbar(), show()

Interactive mode (can display several figures without freezing the process)

import matplotlib.pyplot as plt
plt.ion()
plt.plot([1.6, 2.7])
plt.draw()
# Turn interactive mode off
plt.ioff()

Using oriented-object approach (force backend)

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.matshow(data2d, cmap='gray')
fig.savefig('myfig.png')