ricardomol
  • Ricardomol Notes
  • Frontend
    • Javascript Toolchain
    • Javascript
      • Quirks
      • Articles
        • Function caching
        • 12 JS Tricks
      • Closures
      • Assorted
      • ES6
      • this
      • OOP
      • Async Programming
      • Functional Programming
      • Typescript
    • React
      • Patterns
        • Render props
      • React Router
    • Webpack
    • CSS
      • Resources
  • Backend
    • Python
      • Shallow copy vs deep copy
      • Classes
      • Resources
      • Python C Extensions
      • Coroutines
      • Exceptions
      • Context managers
      • One-Liners
      • Open function
      • Object introspection
      • Targeting Python 2 + 3
      • For - else
      • Comprehensions
      • Lambdas
      • __slots__ magic
      • Collections
      • Enumerate
      • Mutation
      • Map, Filter and Reduce
      • Decorators
      • Sets
      • Fluent Python summary
      • Quizes / Tips
      • Generators
    • Django
      • Generic Relations
      • FBV's vs CBV's
      • ORM
      • DRF
    • RESTful Architecture
    • Resources
  • Databases
    • Joins
    • Normalization
    • PostgreSQL
  • DevOps
    • Docker
      • 0. Resources
      • 2. Services
      • 3. Swarms
      • 5. Stacks
      • 6. Deploy your app
    • CI
      • CI with Django
    • CD
    • PaaS
    • WSGI servers
    • Django
      • Django Deployment
    • Modern DevOps with Django
  • Git
    • Git
  • Comp Sci
    • Big O Notation
    • Patterns
    • Programming paradigms
  • Assorted
    • TCP vs UDP
    • Tests
    • MongoDB
    • Node
      • Resources
    • Go
    • HTTP vs HTTP2
    • GraphQL
    • Books
    • Vim
    • IPv4 vs IPv6
    • Regex
    • Redis
    • Celery
      • Brokers
    • Caching
  • SECURITY
    • Security
Powered by GitBook
On this page
  • Simple Web Server
  • Pretty Printing
  • Profiling a script
  • CSV to json
  • List Flattening
  • One-Line Constructors
  • More
  1. Backend
  2. Python

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:

cat file.json | python -m json.tool

Profiling a script

Helpful in pinpointing the bottlenecks in your scripts:

python -m cProfile my_script.py

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

CSV to json

Run this in the terminal:

python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"

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

List Flattening

Using itertools.chain.from_iterable from the itertoolspackage:

a_list = [[1, 2], [3, 4], [5, 6]]
print(list(itertools.chain.from_iterable(a_list)))
# Output: [1, 2, 3, 4, 5, 6]

# or
print(list(itertools.chain(*a_list)))
# Output: [1, 2, 3, 4, 5, 6]

One-Line Constructors

Avoid a lot of boilerplate assignments when initializing a class:

class A(object):
    def __init__(self, a, b, c, d, e, f):
        self.__dict__.update({k: v for k, v in locals().items() if k != 'self'})

More

PreviousContext managersNextOpen function

Last updated 6 years ago

Additional one-liners can be found on the .

Python website