I’ve been programming in Python for years, and I’m still constantly amazed at how clean and DRY Python code can be. I learned a lot of tips and tricks, mostly from reading source code for open source projects like Django, Flask, Requests, etc.

Here I’ve picked out a few that are sometimes overlooked, but can be very helpful in your daily work.

1. Dictionaries and set derivations


Most Python developers know to use list comprehensions. You’re not familiar with that? A list derivation is a short way to create a list:

>>> some_list = [1, 2, 3, 4, 5]
>>> another_list = [ x + 1 for x in some_list ]
>>> another_list
[2, 3, 4, 5, 6]
Copy the code

Starting with Python 3.1 (and reversely porting to Python 2.7), we can create collections and dictionaries in the same way:

>>> # Set Comprehensions
>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]
>>> even_set = { x for x in some_list if x % 2 == 0 }
>>> even_set
set([8, 2, 4])

>>> # Dict Comprehensions
>>> d = { x: x % 2 == 0 for x in range(1, 11) }
>>> d
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}
Copy the code

In the first example, we used some_list to create a set of non-repeating elements, but only even ones. The second dictionary example shows the creation of a dictionary with keys 1 through 10 inclusive and Boolean values that indicate whether the key is an even number.

Another thing to note is the syntax of collections. We can create a collection as simple as this:

>>> my_set = {1, 2, 1, 2, 3, 4}
>>> my_set
set([1, 2, 3, 4])
Copy the code

Instead of using the built-in set method

2. Use the counter object to count


Obvious, but easy to forget. Counting is a common programming task, and for the most part it’s not that difficult. But the counting could be simpler.

Python’s Collections library contains a dict subclass for counting tasks:

>>> from collections import Counter
>>> c = Counter('hello world')
>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})
>>> c.most_common(2)
[('l', 3), ('o', 2)]
Copy the code

3. Print JSON nicely


JSON is a great sequence format that is widely used today in apis and Web services, but it’s hard to see with the naked eye large amounts of data, which are long and on one line.

You can use indent to better print JSON data, which is useful when dealing with a REPL or log:

>>> import json
>>> print(json.dumps(data))  # No indention
{"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]}
>>> print(json.dumps(data, indent=2))  # With indention
{
  "status": "OK",
  "count": 2,
  "results": [
    {
      "age": 27,
      "name": "Oz",
      "lactose_intolerant": true
    },
    {
      "age": 29,
      "name": "Joe",
      "lactose_intolerant": false
    }
  ]
}
Copy the code

Also, take a look at the built-in module pPrint, which helps you output other things nicely.

4. Quickly build a Web service


Sometimes we need a simple and fast way to set up RPC services. All we need is for program B to call the methods of program A(possibly on another machine).

We don’t need to know anything about this technique, but we just need something so simple that we can handle this using a protocol called XML-RPC (the corresponding Python library that implements SimpleXMLRPCServer).

Here is a simple and crude file reading server…

from SimpleXMLRPCServer import SimpleXMLRPCServer

def file_reader(file_name):
    with open(file_name, 'r') as f:
        return f.read()

server = SimpleXMLRPCServer(('localhost', 8000))
server.register_introspection_functions()

server.register_function(file_reader)

server.serve_forever()
Copy the code

The client that responds to it:

import xmlrpclib
proxy = xmlrpclib.ServerProxy('http://localhost:8000/')
proxy.file_reader('/tmp/secret.txt')
Copy the code

Now we have a remote file reader with no external dependencies except for a bit of code. (Of course, it’s not safe, so just use it at home.)

5. Python’s open source community


I’ve been talking about Python’s standard libraries, which are included in your Python whenever you install Python. For most other tasks, there are plenty of community-maintained third-party libraries to meet our needs.

Here’s one way I picked Python libraries:

  • Contains an explicit protocol for us to use

  • Active development and maintenance

  • It can be installed using PIP and can be easily redeployed

  • Have a set of tests with proper coverage

If you find a Python library that fits your needs, don’t be shy; most open source projects welcome our contributions and assistance, even if you’re not a Python veteran. A helping hand is always welcome!

6. Supplementary techniques


  • Quickly set up an HTTP server in a directory:

    python -m SimpleHTTPServer

    In Python 3 ::

    python -m http.server

  • Beautifully printed JSON on the command line:

    echo '{"json":"obj"}' | python -mjson.tool

    Also, if you install the Pyanswers module, you can highlight the JSON:

    echo '{"json":"obj"}' | python -mjson.tool | pygmentize -l json

  • Note that {} is an empty dictionary, not an empty set

The original link – ozkatz. Making. IO/improving – y…