Python Tips

This will be a dumping ground for Python tips that I would like to share with others.

  • Command-line parsing: Use the optparse library (pre-Python 2.7) or the argparse library (Pyton 2.7 and greater). I would stay away from getopt. It's too old and the code requird to use it is unreadable and requires more effort to use.
  • print statments: Don't use them. Use the logging module. Doesn't apply to Python 3.x where you can use the print function and easily replace it later with a call to a logging command. Even in Python 3.x though, I recommend not using print statements but setting up logging early on.
  • Always make your module importable: Enclose all the logic in functions and the main entry point inside a "def main():" function block. Use a block like this at the bottom of your file to call main():
    def main():
        doWork()
     
    if __name__ == "__main__":
        main()

    If your python script is called like this:
    python script.py
    then __name__ will be set to __main__. If you are importing your module, it won't. So if you import your module, no code will be executed, which is usually what you want.

  • Use tools like pylint, pyflakes, and pychecker: These tools are awesome as they will find simple syntax errors and make sure that you are using proper naming conventions, and adding documentation to your code.

Tags:

Add new comment