Sometimes when debugging we like to print/log out all the
inputs and outputs of a method: name, args, kwargs, dict etc.
We would have some IDE debug features for this purpose but sometimes we need
manual debugging.
And while manual debugging I don’t want to write logger.debug(<messsage>)
to every one of two lines of a module.
The solution : Python Decorators
First configure a logger. In this post I will implement a default basic
configuration. For a detailed configuration go to the post logging configuration post
.
Then crate a module for debuggers in utils package, utils/debuggers.py
like below:
#!/usr/bin/env python3# -*- coding: utf-8 -*-# utils/debuggers.pyimportfunctoolsimportloggingimporttimelogging.basicConfig(level=logging.DEBUG,format="[%(asctime)s] [%(levelname)s] %(name)s: %(message)s",datefmt="%Y-%m-%d %H:%M:%S %z",)logger=logging.getLogger(__name__)deftimerun(func):""" Calculate the execution time of a method and return it back"""@functools.wraps(func)defwrapper(*args,**kwargs):start=time.time()result=func(*args,**kwargs)duration=time.time()-startlogger.debug(f"Duration of {func.__name__} function was {duration}")returnresultreturnwrapper
Output:
2019-07-21 18:43:25,636 [DEBUG] debuggers: Duration of my_func was 0.00023937225341796875
No, please don’t debug your program with print.
Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages for Python programs.
The module provides some ways for applications to configure different log handlers and a way of routing log messages to these handlers. This allows for a highly flexible configuration that can deal with a lot of different use cases.
The logging functions are named after the level or severity of the events they are used to track.
We sometimes —always?, want to know how efficient our code is. So here comes the magical Big O notation:
Big O notation is used in computer science to describe the performance or complexity of an algorithm. Actually Big O notation is special symbol that tells you how fast an algorithm is. Of course you’ll use predefined algorithms often — and when you do, it’s vital to understand how fast or slow they are.
This brief tutorial shows how to install and configure Python 3.8 on Ubuntu.
There are 2 methods to install python on Ubuntu. I prefer first method and strongly recommend that but it depends on developer’s taste.
Method 1: Install It From Source Code I prefer this method since I’d rather always go to source, whether it is documentation for an API or installing something.
Out of the box default python version for Ubuntu 18.