Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Python Cheatsheet


# Interactive one (shell-based debugging sessions)
import ipdb;ipdb.set_trace()  # noqa E702, E231
# When previous one fails (e.g. `make test` inside a Docker container)
import pdb;pdb.set_trace()  # noqa E702, E231
  • Using ipython with Python 3.6 alongside any other installed python version:
sudo python3.6 -m pip install ipython
sudo sed -i "s|/usr/bin/python|/usr/bin/python3.6|g" /usr/bin/ipython
  • Show instance methods (useful from pdb traces and the like):
import inspect
inspect.getmembers(myinstance, predicate=inspect.ismethod)
python -m http.server
class A(object):
    def __init__(self,something):

class B(A):
    def __init__(self,something):
        # B constructor logic
  • Quick & dirty way of checking variable classname:
type(variable).__name__ == "direct_classname"
  • Replaces using regular expressions:
product_data = re.sub(r'<additional_image_link>(.*?)</additional_image_link>',
  • Quickly sorting hashmaps (useful for testing expectations):
my_hashmap.sort(key=lambda item: item["field"])
  • Sort array of objects:
sorted_objects = sorted(objects, key=lambda item: item.ordering_field)
  • Debug http requests
# Debugging at httplib level

import requests
import logging
import http.client as http_client

http_client.HTTPConnection.debuglevel = 1
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.propagate = True

# And  then, all requests.get() etc. will output some debug info via logging
def my_decorator_name(decorated_function):
    def wrapper(arguments):
        # your code
        # more code
    return wrapper
  • Decorator functions with arguments:
class my_decorator_name(object):
    def __init__(self, <arguments>):
        self.arg1 = <arg1>
        # ...
    def __call__(self, decorated_function):
        def wrapper(*args, **kwds):
            # args[0] contains `self` (decorated object)
            event = args[0]
            # your code
            return decorated_function(*args, **kwds)
            # more code
        return wrapper
optional_index_starting_value = 0
for index, value in enumerate(items_list, optional_index_starting_value):
  • Ternary if equivalent:
value = 1 if condition_meets else 0
  • Python does heavy use of exceptions for flow control
  • python can use tuples to swap variables without intermediate/temporal value: (foo, var) = (bar, foo)
  • (first, second, *rest) = some_list # would be valid also: (*head, penultimate, last) = some_list
  • list comprehensions from dictionaries (python 3):
all([value*2 for key, value in my_dict.items()])
  • dict comprehensions exist:
data_dict = { key: int(value) for key, value in data_list.items() }
  • and set comprehensions:
data_set = { data.key for data in data_list }
  • use collections.namedtuple instead of dictionaries for single items (e.g. group of function arguments)
  • rule for __repr__: make it so eval(repr(instance)) == instance. e.g.:
def __repr__(self):
    return "MyClass({}, {})".format(self.constructor_param_1, self.constructor_param_2)
  • generator expressions generate each item on the fly (consuming less memory):
for key in (key for key in data_list):
  • packaging imports using
from myapp.namespace.subnamespace import MyClass
from myapp.namespace.anothersubnamespace import MyOtherClass

# normal code:
from myapp import MyClass, MyOtherClass
import functools

def myfunction(param1, param2) ...







pytest xxxxxx -s
  • Filter to specific test of specific battery:
pytest path/to/test/ -k test_name
 with pytest.raises(ValueError, match="xxxxx"):



watch -n 1 TESTING=true ENVIRONMENT=test PYTHONPATH=.:<SERVICENAME> mamba test/unit
  • Complex stubbing using lambdas:
with Stub() as http_service: url, json, headers: HttpStubResponse(response_text='...', status_code=202))



  • List all routes
print([str(rule) for rule in instance.url_map.iter_rules()])


  • finding django source files path:
python -c "import django;print(djago.__path__)"

Schema validation

eferro commented Jun 20, 2017

For date and time handling support you can try

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment