Improve Your Python Practices: Debugging, Testing, and Maintenance

Being a web developer comes with a number of unique challenges. Choosing the right language to build websites and applications which is a lot harder than you may think. For years, developers and programmers have used Python to bring their creations to life.

In fact, over 8 million developers report using Python on a regular basis. The main concern you should have as an avid user of Python is writing code that is both bug-free. Accomplishing this goal is easy with Python logging and abiding by best practices.

The following are just some of the things you can do to improve the quality of your Python code.

Become Familiar With PyPI

Writing every piece of code to construct a website or web-based application from the ground up can be both time-consuming and frustrating. For years, programmers have used the power of the Python Package Index (PyPI) to make building new websites and apps easy. Basically, PyPI is a collective repository of thousands of various Python projects.

With this repository, you can pick out bits of code to help you in the construction of a web app or site. By using the existing modules found in this repository, you can reduce the amount of time spent on a development project. Not only will you be able to look at over 100,000 existing modules, but you can also add your own as well. Getting involved in the extensive Python online community is a great way to get better at your job and meet lots of like-minded individuals.

Focus on Structuring Your Repository Correctly

One of the first things most programmers will do when starting a new project is to set up an extensive code repository and a system to control the various versions of their project. When trying to set up this repository, you need to focus on adding a few key components like

  • The README Document- One of the most important parts of any repository is the README document. In essence, this document will describe the project in hand, outline the functionality of the code and provide a purpose. Not only will this document help you out, but it can also help other developers tasked with maintaining your code later on.

  • Requirements.txt- When trying to provide other developers with information regarding the dependencies your program has, using a requirements.txt file is imperative. Without this information, developers and programmers will have a hard time maintaining your Python code in the future.

  • Module Code- Putting all of your code into an easily identifiable subdirectory is also important. By doing this, you can easily reference this file when trying to make changes or diagnose bugs.Adequately Testing Your Code At Each Step of the Development Process

    Adequately Testing Your Code At Each Step of the Development Process

    One of the biggest mistakes new programmers make is writing an entire program and then testing it. Doing this will usually lead to a number of headaches, which is why adopting a continuous testing mindset is vital. By testing the code at every step of the development process, you can catch problems before they cause too much damage.

    It is usually a good idea to let another knowledgeable programmer look at the code you have developed. Generally, this will provide you with an outside perspective that can be helpful when trying to discover issues. Constantly reviewing your error logs is also imperative when attempting to produce websites and apps that are functional and reliable.

    Practice Makes Perfect

    If you are new to the world of Python programming, then you need to work on honing your skills. The best way to do this is by using this code frequently on a variety of different projects. As time goes by, your understanding of this programming language will increase. 

    This guest post is written by Ashley Lipman.

The simplest explanation of Decorators in Python

Before starting about decorators, first, understand that functions in python have below three properties.

1. Functions are objects. Which means we can assign the function to a variable.
2. A function can be defined inside another function
3. A function can return another function

See example below:

Assigning a function to another variable

# Assigning function to another variable
# a function which adds * around text
def beautify(txt="python"):
    print("*" + txt + "*")

# Assign above function to another variable
star = beautify

# call star

# output
>>> *python*

Defining a function inside another function

def beautify():
    # define an inner function
    def inside_beauty(txt="python"):
        print("*" + txt + "*")

    # call inner function

# call outer function

# output
>>> *python*

Returning function from another function

def beautify():
    # define an inner function
    def inner_beauty(txt="python"):
        print("*" + txt + "*")

    # return this inner function
    return inner_beauty

# collect return type of beautify in a variable
f = beautify()


# output
>>> <function inner_beauty at 0x7fe5c176b7d0>
# call f f() # output >>> *python*

Now when we know that we can assign a function to a variable, can define a function inside another function and can return a function from another function, we can jump to next strep. We can pass a function as a parameter to another function.

def beautify(func):
    print("going to call a function passed as parameter to this function")
    print("function which was passed as parameter has been called")
def add_stars(txt="python"): print("*" + txt + "*") beautify(add_stars) # output >>> going to call a function passed as parameter to this function *python* function which was passed as parameter has been called

Now coming to what a decorator is: Decorator is a wrapper function that executes some code before and after the function being decorated, just like the example above.

Another Example:
Let's say you want to separate the output of a function by surrounding it with horizontal dividers.

Original Function:

def say_something():
    print("I am the original function.")

Decorator function:

def separate_content(function_to_decorate):
    # a wrapper function
    def wrapper_func():

    return wrapper_func

Now if you call the original function, the output will be I am the original function.

You can decorate the original function by passing it to the decorator function as below.

say_something = separate_content(say_something)

# output
I am the original function.

Shortcut to decorate a function is:

def say_something():
    print("I am the original function.")

which when called will give the same out as above.

Now you can just use @separate_content above any function definition and the behavior of that method will be changed without changing the content of that method

5 lesser used Django template tags

We already know how to use for, if-else, filter and url template tags in Django. We can also create custom template tags in Django if any requirement is not getting fulfilled with existing tags. 

Here we are introducing you with 5 Django template tags which are lesser-known and used by beginner Django developers.

1. lorem

This template tag is used to insert random lorem ipsum Latin text in the template. This is useful when you want to show the sample data instead of blank space.

This tag accepts 3 optional parameters: count, method, and random.

The count is the number of words or paragraphs to produce. The method can have values w for words, p for HTML paragraphs and b for plain-text paragraphs. When the third parameter, random, is used, the text is generated randomly instead of using lorem ipsum text.

Refer to this Django template fiddle for example and demo.

2. templatetag

Double curly braces are used to display variables in Django templates. What if you want to display just curly braces in template. For this to achieve we can use templatetag template tag.

3. cycle

This tag accepts the variable number of arguments and outputs the next argument each time this tag is called. Once all arguments have been called, loop restarts from the starting.

We can use variables or string or a mix of both as arguments for this tag.

Refer to this Django template fiddle for example and demo. 

<!-- mylist is {"mylist":["Line 1","Line 2","Line 3","Line 4","Line 5","Line 6"]} -->
{% for item in mylist %}
    <div style="color:{% cycle 'red' 'green' 'blue' 'yellow' %}">
{% endfor %}


cycle tag in django template tags

4. firstof

This template tag accepts the variable number of arguments and returns the first argument which is not False i.e. which is not zero, empty string or False

Refer to this Django template fiddle for example and demo. 

5. phone2numeric

Converts any phone number to the numeric equivalent even if the phone number is not valid.

It will not convert any integer or boolean values.

Refer to this Django template fiddle for example and demo. 

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© 2017-2019 Python Circle   Contact Us   Advertise with Us