- Available License keywords: https://autopilot-docs.readthedocs.io/en/latest/license_list.html
- List of python exceptions
- Write Python - Run Everywhere - Beeware
-
Python execution model
- code-blocks, scopes, execution frames and exceptions
- Mock standalone function when unittesting
- Unittest alternatives: https://pypi.org/project/chai/
- Copying files
- Doctest primer
- Logging module resources:
- setup.cfg
- arrow - one class to manage dates
- requirements.txt vs install_requires
- pyenv - Alternate between different python versions
-
Conflict resolution with argparse: https://docs.python.org/2.4/lib/optparse-conflicts-between-options.html
parser = OptionParser(conflict_handler="resolve") parser.add_option("-n", "--dry-run", ..., help="do no harm") parser.add_option("-n", "--noisy", ..., help="be noisy")
- python performance hints
- concerns when packaging c extensions in python packages
- dynamic-programming-in-python
-
memory-tempfile
-
When to use
/tmp
and when to use/dev/shm
: https://superuser.com/a/45509/369517 - More information: https://superuser.com/a/1030777/369517
-
When to use
-
Convert time since epoch to datetime:
-
datetime.datetime.fromtimestamp(1284286794)
-
-
Python staticmethod vs classmethod:
- https://stackoverflow.com/a/1669524/2843583
-
staticmethods are basically freestanding functions grouped under the
class
scope; classmethods are still methods of a class.
- FactoryBoy: Better fixtures for your Django tests
-
Is
Python
an interpreted or a compiled language?-
Python is a language specification. One of it's implementations
CPython
, compiles the source code into bytecode, which then is run (interpreted) inside the Python VM. - Link: https://stackoverflow.com/a/2998228/2843583
-
Python is a language specification. One of it's implementations
-
Python is caching the first 257 integers in memory:
# Same identity all the time In [49]: id(256) Out[49]: 9796768 # Generated on the fly In [50]: id(257) Out[50]: 139740392044752
-
bdist
: build distribution -
sdist
: source distribution -> tar.gz -
pip
: pip installs packages
-
https://github.com/thclark/rstcloth
- Commit hooks for running autoformatting
- Based on a cookiecutter template
>>> cli_timestamp_to_ns("123") # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): python_utils.custom_exceptions.InvalidCLITimestampError: Invalid timestamp provided: 123
-
Run a single test method (or a single test class or ...):
python3 -m unittest package.path.to.class.or.method
-
See loaded modules in python:
set(sys.modules) & set(globals())
-
Pip downloads every single version of a package:
-
Use
--use-deprecated=legacy-resolver
instead - https://github.com/pypa/pip/issues/8713
-
Use
Print numpy array without truncation:
np.set_printoptions(threshold=sys.maxsize)
Quaternions:
- Form: w, x, y, z
-
Preferred extension:
pkl
/pickle
- https://stackoverflow.com/questions/40433474/preferred-or-most-common-file-extension-for-pickle-files/40433504 -
Use the
dump
,load
methods - open file inline for auto-close
- Python3 pathlib library: https://realpython.com/python-pathlib/
There's a gazzilion of 2D statistics/plotting libraries in python. Just select a single damn one and stick to it - None of it supports 3D visualisation
- bokeh: https://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html
- gpgpy
- plotly
- seaborn
- altair
- pygal
Only thing that's available (~end 2019) is matplotlib. Just use it...
- https://medium.com/@sebastiannorena/3d-plotting-in-python-b0dc1c2e5e38
- https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
- https://plot.ly/python/3d-surface-plots/
- Matplotlib rcParams available parameters: https://matplotlib.org/3.1.0/tutorials/introductory/customizing.html
parser = argparse.ArgumentParser(description="Help line 1\n" + "Help line 2", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
Example usage: https://www.data-structures-in-practice.com/hash-tables/
Use the dis
standard library module: https://docs.python.org/3/library/dis.html
Use it e.g., on a function:
import dis f = lambda x: x + 2 dis.dis(f) 1 0 LOAD_FAST 0 (x) 2 LOAD_CONST 1 (2) 4 BINARY_ADD 6 RETURN_VALUE
Normally you'd do this as part of your bashrc/fish.config file. But if you haven't, here's the commands to do it in the current shell instance
fish ) set -x PATH \"${PYENV_ROOT}/bin\" \$PATH status --is-interactive; and . (pyenv init -|psub) status --is-interactive; and . (pyenv virtualenv-init -|psub) ;; * ) PYENV_ROOT="$HOME/.pyenv" export PATH="${PYENV_ROOT}/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)"
-
Compile python versions from source:
-
You'll need to install OpenSSL first:
apt-get install libssl-dev libffi-dev
-
You'll need to install OpenSSL first:
-
Format all
.py
files withblack
autoformatter:-
fd -e py | xargs -I{} black --line-length 95 -t py36 {}
-
-
Render a html python string in the browser:
# I assume that the text was acquired using the requests library import webbrowser with open("a.html", "w") as f: f.write(resp.text) webbrowser.open("a.html")
from sympy import var, cos, plot x = var('x') p = plot(cos(x), line_color='r') p = plot(cos(2*x), line_color='g') p = plot(cos(4*x), line_color='b') pl.extend(plot(cos(2*x), line_color='g')) pl.show()
numpy.set_printoptions(linewidth=160)
(Pdb++) p T array([[ 1.00000000e+00, 1.00284240e-18, -2.28654607e-18, 0.00000000e+00], [ 1.13765545e-18, 1.00000000e+00, 1.29264105e-19, 0.00000000e+00], [-1.39240192e-17, 1.34405256e-19, 1.00000000e+00, 3.46944695e-18], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) (Pdb++) numpy.set_printoptions(linewidth=160) (Pdb++) p T array([[ 1.00000000e+00, 1.00284240e-18, -2.28654607e-18, 0.00000000e+00], [ 1.13765545e-18, 1.00000000e+00, 1.29264105e-19, 0.00000000e+00], [-1.39240192e-17, 1.34405256e-19, 1.00000000e+00, 3.46944695e-18], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) (Pdb++)
https://github.com/albertlauncher/python/pull/96/files
bus = dbus.SessionBus() notify = dbus.Interface(bus.get_object(dbusItem, dbusPath), dbusInterface) notify.Notify(__prettyname__, 0, iconPath, title, text, '', '', 0)
spec = importlib.util.spec_from_file_location("bing", "plugins/image_search/bing.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) cl = foo.MyClass()
- Rename just a single column in pandas: df.rename(columns = {'old_name':'new_name'}, inplace = True)
- Drop column by index i: df.drop(df.columns[i], axis=1)
- Just plain nice: df['Change (%)'] = df['Change (%)'].str.strip('%').astype(float)
-
https://github.com/myint/scspell
-
See
colcon-zsh
(or any other colcon plugin) as an example
-
See
Every module and object in python has a __dict__
attribute (you can think of
all the modules as dictionaries that contain their variables, and functions)
-
Except int - doesn't have
__dict__
Use self.__class__.__bases__
Link: https://stackoverflow.com/a/10092179/2843583
- Using Pip
- Debugging: Keyring Issue
- Debugging: unpackb-msgpack Error
- Simulate pushd using @contextmanager
- Poetry Package Manager
- Handling Integer Objects
- Debugging Tools
- VLC Python API - Read metadata from network stream
- Iterators vs Generators
- Concerns Packaging C Extensions in Python Packages
- Python Object Unique Name
- Check if PID exists
- Thought on Python coding standards
- Concurrency and AsyncIO
- functools
- decorators
- decorator once per minute
- psrecord
- Call subprocess and print its output as it comes / live
- Avoid if-initialisation cases
- unittest runner script
- Find System Installed Version That Matches
- Logging
- Code Coverage
- Decorator with Arguments
- ipython Interpeter
- Choosing TOML Over Other Formats
- Importing in Python
- Readline: Enable TAB Completion
- Click - List all visible, registered subcommands
- pdb / ipdb
- Upload to PyPI
- Decorators for Class and Object Attributes
- Mocking in Python
- mypy - annotate self class itself
- Find N-th Occurrence
- Pytest Testing Suite
- Mypy Cheatsheet
- Invoke a click subcommand - Have all subcommands share a list of arguments
- Regexp: Match URLs
- Packaging Options
- numba
- Bumping the version of your Python Project
- Implementations of the Python Specification
- pyproject.toml
- simple decorator
- pyc-files