Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Python Cheatsheet

General

import pdb;pdb.set_trace()  # noqa E702, E231
  • 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):
        pass

class B(A):
    def __init__(self,something):
        super().__init__(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>',
                      r'<additional_image_link><![CDATA[\1]]></additional_image_link>', 
                      product_data)
  • Quickly sorting hashmaps (useful for testing expectations):
my_hashmap.sort(key=lambda item: item["field"])
  • Debug http requests
# Debugging at httplib level

import requests
import logging
import http.client as http_client

http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
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
        decorated_function(arguments)
        # 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
  • dict comprehensions exist:
data_dict = { data.key: data.value for data in data_list }
  • 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 __init__.py:
# __init__.py:
from myapp.namespace.subnamespace import MyClass
from myapp.namespace.anothersubnamespace import MyOtherClass

# normal code:
from myapp import MyClass, MyOtherClass

Pypi

Mypy

Flake8

Boto

Testing

Pytest

pytest xxxxxx -s
  • Filter to specific test of specific battery:
pytest path/to/test/battery.py -k test_name

Mamba

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

Tools

Flask

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

eferro commented Jun 20, 2017

For date and time handling support you can try https://github.com/sdispater/pendulum

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