Skip to content

Instantly share code, notes, and snippets.

@rachmadaniHaryono
Created May 20, 2017 07:14
Show Gist options
  • Save rachmadaniHaryono/cf78341ca9157d06c9a0fe87b9df541e to your computer and use it in GitHub Desktop.
Save rachmadaniHaryono/cf78341ca9157d06c9a0fe87b9df541e to your computer and use it in GitHub Desktop.
summary from reddit thread about python repetitive code

What are the most repetitive pieces of code that you keep having to write?

summary from reddit thread.

https://www.reddit.com/r/Python/comments/6bjgkt/what_are_the_most_repetitive_pieces_of_code_that/

Class attributes

... class Coordinate(object):
... 
...     def __init__(a, b, c):
...         self.a = a
...         self.b = b
...         self.c = c

attrs

https://attrs.readthedocs.io/en/stable/examples.html

>>> @attr.s
... class Coordinate(object):
...     x = attr.ib()
...     y = attr.ib()
...     z = attr.ib()

collections.namedtuple

NOTE: immutable.

... from collections import namedtuple
... Coordinate = namedtuple('Coordinate', ['x', 'y', 'z'])
... A = Coordinate(1, 2, 3)
... A.x
>>> 1
... A.y (2)
>>> 2
... A.z
>>> 3

__dict__ (not recommended)

... class Coordinate(object):
... 
...     def __init__(a, b, c):
...         self.__dict__.update({k: v for k, v in locals().iteritems() if k != 'self'})

or

... class Coordinate(object):
... 
...     def __init__(self, **kwargs):
...         self.__dict__.update(kwargs)

django

blank=True, null=True

functools.partial

from functools import partial
from sqlalchemy.orm import Column

PKColumn = partial(Column, primary_key=True, autoincrement=True, nullable=False)

data science on jupyter notebook

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from sklearn import preprocessing, linear_model

import sys
import os
from datetime import datetime, timedelta

baseline.ipynb

https://gist.github.com/Jessime/69df607e4ad5f1229528af2edebe6e70

ipython_config.py

# List of files to run at IPython startup.
c.InteractiveShellApp.exec_lines = [
'%load_ext autoreload',
'%autoreload 2',

# Arrays, dataframes, and trig functions
'import numpy as np',
'from numpy import array, linspace, arange, zeros, ones, \
    eye, sin, cos, tan, arcsin, arccos, arctan, arctan2, log, sqrt',
'np.set_printoptions(suppress=True, precision=4)',
'import pandas as pd',
'from pandas import DataFrame, Series',

# Dates and times
'import saturn',

# Functional programming
'from functools import partial',
'from cytoolz import *',

# Plotting
'import matplotlib',
'from matplotlib import pyplot as plt',
'import fplot',

# Mathematical constants. Import before e, so e is 2.72, not elementary charge.
'from scipy.constants import *',
'ħ = hbar',  # hbar is imported from scipy.constants
'ε_0 = epsilon_0', # from scipy.constants
'Å = angstrom', # from scipy.constants
'import math',
'import cmath',
'from math import e, pi',
'tau = 2 * pi',
'π, τ = pi, tau',
'i = complex(0, 1)',


# Sympy
'import sympy',
'from sympy import diff, integrate, exp, oo, sin as ssin, cos as scos, \
    tan as stan, asin as sasin, acos as sacos, atan as satan, Matrix, simplify, \
    lambdify, Integral, Derivative, factor, expand, limit, var, Eq, N, \
    solveset, linsolve, roots, dsolve, symbols, log as slog, sqrt as ssqrt, \
    cbrt, pi as spi, Rational, linsolve, I',
'from sympy.plotting import plot',
"x, y, z, t = sympy.symbols('x y z t')",
'sympy.init_printing()',
]

Jupyter notebook snippets

http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/snippets/README.html

Setting up arguments

def arguments():
    parser = argparse.ArgumentParser()
    # various arguments
    return parser.parse_args()

click

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

docopt

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)```

Reading file

with open(path) as f:
    contents = f.read()

pathlib

contents = pathlib.Path(path).read_text()

pyfilesystem

contents = gettext(path, encoding=None, errors=None, newline=u'')

Logging

log.info('var=%s', `var`)

structlog

>>> from structlog import get_logger
>>> log = get_logger()
>>> log.info("key_value_logging", out_of_the_box=True, effort=0)
2016-04-20 16:20.13 key_value_logging              effort=0 out_of_the_box=True

Parameterized decorators

from functools import wraps

def decorator(argument):
    def real_decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            retval = function(*args, **kwargs)
            more_funny_stuff()
            return retval
        return wrapper
    return real_decorator

wrapt

import wrapt

@wrapt.decorator
def pass_through(wrapped, instance, args, kwargs):
    return wrapped(*args, **kwargs)

@pass_through
def function():
    pass

version, which accept arguments

import wrapt

def with_arguments(myarg1, myarg2):
    @wrapt.decorator
    def wrapper(wrapped, instance, args, kwargs):
        return wrapped(*args, **kwargs)
    return wrapper

@with_arguments(1, 2)
def function():
    pass

os.walk

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    for file in files:
        print(len(path) * '---', file)

pyfilesystem

>>> from fs import open_fs
>>> from fs.walk import Walker
>>> home_fs = open_fs('~/projects')
>>> walker = Walker(filter=['*.py'])
>>> for path in walker.files(home_fs):
...     print(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment