One-Liners

Simple Web Server

To quickly share a file over a network. Go to the directory which you want to serve over the network:

# Python 2
python -m SimpleHTTPServer

# Python 3
python -m http.server

Pretty Printing

You can print a list and dictionary in a beautiful format in the Python repl:

from pprint import pprint

my_dict = {'name': 'Yasoob', 'age': 'undefined', 'personality': 'awesome'}
print(dir(my_dict))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

pprint(dir(my_dict))
# ['__add__',
#  '__class__',
#  '__contains__',
#  '__delattr__',
#  '__delitem__',
#  '__dir__',
#  '__doc__',
#  '__eq__',
#  '__format__',
#  '__ge__',
#  '__getattribute__',
#  '__getitem__',
#  '__gt__',
#  '__hash__',
#  '__iadd__',
#  '__imul__',
#  '__init__',
#  '__init_subclass__',
#  '__iter__',
#  '__le__',
#  '__len__',
#  '__lt__',
#  '__mul__',
#  '__ne__',
#  '__new__',
#  '__reduce__',
#  '__reduce_ex__',
#  '__repr__',
#  '__reversed__',
#  '__rmul__',
#  '__setattr__',
#  '__setitem__',
#  '__sizeof__',
#  '__str__',
#  '__subclasshook__',
#  'append',
#  'clear',
#  'copy',
#  'count',
#  'extend',
#  'index',
#  'insert',
#  'pop',
#  'remove',
#  'reverse',
#  'sort']

This is more effective on nested dict s. Moreover, if you want to pretty print json quickly from a file then you can simply do:

Profiling a script

Helpful in pinpointing the bottlenecks in your scripts:

Note: cProfile is a faster implementation of profile as it is written in c

CSV to json

Run this in the terminal:

Make sure that you replace csv_file.csv to the relevant file name.

List Flattening

Using itertools.chain.from_iterable from the itertoolspackage:

One-Line Constructors

Avoid a lot of boilerplate assignments when initializing a class:

More

Additional one-liners can be found on the Python website.

Last updated