Python
Pythonπ
| Category | Tools |
|---|---|
| Environment | venv module, (Ana)Conda, Micromamba |
| Package managers | pip, pipx |
| Package sources | PyPI |
| Linting & syntax | Black, pycodestyle |
| References | Standard Library, W3C Python Reference |
Installation and Versionsπ
- (virtual) environments
- Python module
venv - virtualenv
- (Ana)Conda
- Micromamba
micromambais a tiny version of themambapackage manager. It is a statically linked C++ executable with a separate command line interface. It does not need abaseenvironment and does not come with a default version of Python.
- Python module
- change system python version: Linux: default applications
- 2to3 converter: Automated Python 2 to 3 code translation
Functions/methodsπ
Docstringsπ
Convention for argument description:
1 2 3 4 5 | |
Decoratorsπ
Article intro @towardsdatascience
Annotate: Argument Metadataπ
Introduced with Python 3.9
Example
1 2 3 4 5 6 7 8 9 | |
Filesπ
The with statement
- simplifies exception handling by encapsulating common preparation and cleanup tasks
- no call of
close()needed - examples
1 2 | |
Data Typesπ
Dictionariesπ
W3schools Dictionaries Reference | RealPython on Dictionaries (iteration)
Merge two dictionaries stackoverflow
- Python >= 3.9.0:
z = x | y - Python >= 3.5:
z = {**x, **y} - Python <= 3.4:
1 2 3 4 | |
Picturesπ
Simple edits with pillow library
Libraries, packages and modulesπ
Importing Modulesπ
See documentation on the import system.
Package Sources and Managersπ
Package managers
- pip: pip is the package installer for Python. You can use it to install packages from the Python Package Index and other indexes
- pipx: Install and Run Python Applications in Isolated Environments
Package sources
- PyPI Python Package Index
awesome-python: curated list of awesome Python frameworks, libraries, software and resources Github
Why Python packaging sucks (minor rant)
- PyPI search sucks: query for
jupyter-labdoesn’t returnjupyterlab(why do I have to guess packager’s use of hyphens?!) - not obvious how to have pip upgrade installed packages (version not pinned by me, e.g. in
requirements.txt)
Technicalπ
argparse: parse command line arguments and create help page
Documentation | @golinuxcloud
Visualisation, GUI, visualsπ
- curses: “supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals”
- Python GUI with Qt
- PyAutoGUI: automate GUI interaction across OSs
- rich: rich text and beautiful formatting in the terminal.
Github
- rich: rich text and beautiful formatting in the terminal.
- Seaborn: statistical data visualistion (based on Matplotlib) | Homepage

- PyTorch3D: efficient, reusable components for 3D Computer Vision research with PyTorch
Python Enhancements, Coding, Optimisationπ
- functools: implements decorator
cachethat can significantly speed up things like recursive function calls - Colander: dictionary/JSON/YAML data validation
Example
Image Processing, Data Extraction and Processingπ
- camelot-py: table data extraction: library Camelot
- can be tweaked to influence extraction quality
- can extract multiple tables
- can read from URL
flavor: how PDF is parsed. Options arelatticeandstream- see Data Science Pandas etc for examples
- Mito: work with Pandas dataframes like (Excel) tables: select, format, formulas, filter, etc.
1 | 2 | 3 | Basic Visualisation- read tables: CSV, …
- simple analysis: describe
- fill holes:
fillna
- Pillow: Python Imaging Library fork. Example: see rembg
- rembg: remove image backgrounds
Example
1 2 3 4 5 6 7 8
# Remove Background of Images # pip install rembg # pip install pillowfrom rembg import remove as rem from PIL import Imagedef Remove_bg(img): output = "removed_bg.png" input = Image.open(img) output_img = rem(input) output_img.save(output)Remove_bg('input.png')
- language-tool-python: a grammar checker for Python
This is a Python wrapper for LanguageTool. LanguageTool is open-source grammar tool, also known as the spellchecker for OpenOffice. This library allows you to make to detect grammar errors and spelling mistakes through a Python script or through a command-line interface.
Example
1 2 3 4 5 6 7 8 9 10
# Proofread your Documents # pip install language-tool-pythonimport language_tool_python as ltp def Proofread(): checker = ltp.LanguageTool('en-US') text = 'A quick broun fox jumpps over a a little lazy dog.' correction = checker.correct(text) print("Your Original Text:", text) print("Corrected Text:", correction) Proofread()
Web Stuffπ
- Requests: HTML requests and parsing responses
- Smtplib: E-mail automation Resource 1 | Resource 2
http.servermodule: run a local HTTP server, accessible from other machines:
1 | |
Warning:
http.serveris not recommended for production. It only implements basic security checks.
- google-search: what the name implies
Example
1 2 3 4 5 6 7
# Search on Google # pip install google-searchfrom googlesearch.googlesearch import GoogleSearchdef Get_Google_Search(query): Google = GoogleSearch() r = Google.search(query, num_results=10) for data in r.results: print("Title: " + data.title) print("Content: " + data.getText())Get_Google_Search("python programming")
- scrapy: web scraping, website information extraction, sitecrawler, data mining, monitoring, automated testing
- public-apis: organised hundreds of free APIs that could be used for software and web development
Examples:- Fun Facts: randomly generates a fun fact every time we call it
- Colormind API: can be used to generate gorgeous colour codes that potentially can be used in our data visualisation
- Government APIs
Hardware, DIY, IoTπ
- home-assistant core: Open source home automation that puts local control and privacy first. Powered by a worldwide community of tinkerers and DIY enthusiasts. Perfect to run on a #tech/hw/RaspberryPi or a local server
Website | Github
Obscureπ
- real-time-voice-cloning
- face_recognition: The world’s simplest facial recognition api for Python and the command line Github
- Speech to text AI
Example
1 2 3 4 5 6 7 8 9 10 11
# Convert Speech to Text #pip install SpeechRecognitionimport speech_recognition as srdef SpeechToText():Ai = sr.Recognizer() with sr.Microphone() as source: listening = Ai.listen(source, phrase_time_limit = 6) try: command = Ai.recognize_google(listening).lower() print("You said: " + command) except sr.UnknownValueError: print("Sorry Can't understand, Try again") SpeechToText()
Advancedπ
Decoratorsπ
@lru_cache()built-in since Python 3.2
Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.
Simple lightweight unbounded function cache. Sometimes called βmemoizeβ.
Filetypesπ
YAMLπ
Testing, Lintersπ
Essential Python Tools: Linters and formatters
Linters
- pycodestyle (formerly pep8): Homepage, Documentation | Error Codes | Source @GitHub
- config:
setup.cfgsection[pycodestyle] - advanced usage: automated tests
- config:
- pylint: Documentation | Checker Features | Config Examples | Error Codes
- Config:
~/.pylintrc
- Config:
- autopep8: automatically apply (specific) PEP8 rules
Testing #dev/build/python
- virtualenvwrapper - a useful set of scripts for creating and deleting virtual environments
- pew - provides a set of commands to manage multiple virtual environments
- tox - a generic virtualenv management and test automation command line tool, driven by a
tox.iniconfiguration file - nox - a tool that automates testing in multiple Python environments, similar to tox, driven by a
noxfile.pyconfiguration file
Projectsπ
Project Managersπ
- Hatch
> Hatch is a modern, extensible Python project manager. See the Why Hatch? page for more information.
Virtual Environmentπ
- create:
python3 -m venv .venv - activate:
source .venv/bin/activate - deactivate:
deactivate - Install dependencies: e.g.
pip install -r requirements.txt - Save them:
pip freeze > requirements.txt
Can then be installed again
Testsπ
- by convention start filenames with prefix
test_, followed by name of script, same for test functions - can be run with
pytest(pip install pytest) - can be used from sub-directory if empty file
__init__.pyis created (used to mark directories as Python package directories
Documentationπ
- Sphinx: Python Documentation Generator
Sphinx makes it easy to create intelligent and beautiful documentation ^e526ca
- https://realpython.com/documenting-python-code
- Google Python Styleguide | Example Documentation Strings from Google
- mkdocstrings
Creating a Packageπ
Cookiecutter: there are several templates out there for Python packages to help one get started with authorship, licensing, etc.
Data Science: Pandas etcπ
Medium: # 5 Python Libraries That Will Help Automate Your Life
Python Automation Tutorial - Extracting Table from PDF
Using Camelot to extract data into Pandas dataframe from PDF with multiple tables
Jupyter: Notebook, Labπ
Tags: #dev/python/jupyter #dev/python/conda #dev/python/anaconda #dev/python/miniconda
- https://jupyter.org/ | Jupyter Notebook documentation | Built-in magic commands
Remco’s notes @Wiki: conda env, kernel installation - Jupyter Book
Build beautiful, publication-quality books and documents from computational content.
Referencesπ
Essential Python Tools
awesome-python-applications: Free software that works great, and also happens to be open-source Python.
