Namaste everyone. This time I came up with few sensitive suggestions which can effect our coding style. A good habit leads to a good output. If you are already working with the things I am going to mention, then you are on right track. Other wise you will sure gain something useful in few minutes.
Yeah, the first important thing we should know about is working with virtual environments in python. I observed that lot of people are installing packages for their default python Interpreter. Separating the interpreting environment always keeps things clean. We can work with different projects on same machine without conflicts using virtual environment. For installing virtualenv on Ubuntu -14.04 machine just do
$ sudo apt-get install python-pip $ pip install virtualenv
Suppose I am working on Flask project, I create a virtual environment for that and install all dependencies for Flask. A virtual environment is created with command “virtualenv env_name”
# This creates a virtual environment called flask_env $ virtualenv ~/flask_env
Now tell machine to drop default python interpreter and load this flask_env interpreter using
$ source ~/flask_env/bin/activate
Now you are in a separate world. Install packages using pip.
(flask_env)$ pip install flask requests
Now if you want to drop from virtual environment do, deactivate
# This command deactivates virtual environment's interpreter and loads default (flask_env)$ deactivate
Hint: Always use Virtualenv to separate project environments.
Have you ever faced problem of hitting up arrow key for several times to collect nth previous command in python shell. Also you need to rush to Python API for knowing about properties and methods available in a package or module. Then you should use IPython. It is an interactive shell with tons of options. You can see method names, properties of any module on the fly. It is a tool that every programmer should have. For installing IPython just use this command.
$ pip install ipython
there is another variation of IPython called Notebook where we can save our scripts as notebooks on web based interpreter. We can share them, use them.
You can launch IPython shell using ” ipython” command. To see the suggestion lookup for method names press TAB after entering the dot ( . )
Generally IPython is used for creating shorter scripts and testing language features . My favorite command is “%cpaste”. Using it I can copy code directly into terminal without losing the indentation. In conventional python shell pasting and formatting is painful. For more details visit this link https://github.com/ipython/ipython
3) Anaconda sublime plugin
If you are writing shorter scripts and testing them IPython is sufficient. But if you want a full fledged python editor with following features:
- Automatic code completion
- PEP-8 and PEP-257 checking and reporting
Then you should use Anaconda plugin with Sublime Text . Sublime Text 3 is a great editor for python development. It is fluid, takes less resources and can handle any kind of file without pain. Combining [ Anaconda plugin + Sublime Text 3 ] = Python IDE . You can see how to setup plugin using package control here.
One more common thing I observe in python beginners is not using any debugger while testing their code. Python is interpreted language. It executes line by line. But still in big projects with various function calls, we do not get the actual code flow. We all know classic debugger in python called Pdb. IPdb is a combination of IPython + Pdb (Interactive Python Debugger).
Using IPdb we can set break points anywhere in our code using one single statement.
Insert above statement into your python code. When program executes, control stops at the above line. From then you can go line by line and inspect variables etc to debug code. I am listing the primary keys used for debugging here.
- n – execute next line
- c – execute remaining program
- r – continue execution until current function returns
For more details about IPdb and debugging visit this link. http://georgejhunt.com/olpc/pydebug/pydebug/ipdb.html
I saw people putting print statements many times to debug the code and to write information on console. Logging information on console is a very bad practice. Python provides an excellent in-built library which is sadly neglected by most of the python developers. Logging your program activities is a very good habit to avoid failures. Here we can jump start how to log a python function activity in a file.
# loggex.py import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) fh = logging.FileHandler('add.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) def add(x,y): logger.info("Just now received parameters %d and %d" % (x, y)) addition = x + y logger.info("Returning the computed addition %d" % addition) return addition if __name__ == '__main__': add(13,31)
Here we are not doing anything fancy. We are just logging activity of an add function in a file called add.log. Here we created a python script loggex.py which does these things.
- Create a logger object with current file name as handle
- Set level to DEBUG. It can also be INFO or ERROR according to the context of log
- Create a file handler, which redirects logs to a physical file
- Create format handler and set it to file handler. This is nothing but defining custom message for time and date etc that appears in the log file.
- Add file handler to logger object we created
- Sprinkle INFO or DEBUG messages wherever you want to note down activity. They will be recorded in the file. You can review a log file in case of failure.
See how simple logging is. But very few developers shows interest in doing it while building software. Make logging in your program as a habit.
So these are five notable minimum things every python developer should use and care about to improve their productivity. If you have any queries just comment below. Thanks.