Open In App

10 Tips and Tricks to Write the Better Python Code

Improve
Improve
Like Article
Like
Save
Share
Report

Writing code is hard, and Python programmers often face a steep learning curve. One of the most common issues that can prevent you from writing readable code is bad practices in organizing your code. In this article, we’ll discuss some ways to help you avoid making those mistakes and get better at writing Python code.

10 Tips and Tricks to Write the Better Python Code

 

The best thing in writing better Python code is to make your code readable. Writing understandable code is essential for a variety of reasons.

  • It makes it easier for you to comprehend your code, making it simple for others to use
  • If changes need to be made to the same section of code in the future, it simplifies things for other developers and even for you (for example, if part of a class needs changing)

10 Tips and Tricks to Write the Better Python Code

1. Use Context Manager to Automate Resource Closure

When a context is exited in Python, context managers can automatically close resources like files, network, and database connections. By doing so, resource leaks can be prevented, and memory usage can be increased.

Thewith statement, which sets a context to handle the resource, makes it simple to use a context manager. Even if an exception is raised, the context manager always closes the resource when the context’s function has done running. This can make your code more effective and less error-prone by ensuring the resource is always closed correctly.

Here’s a straightforward example of how to read a file and make sure it’s closed correctly using a context manager:

Python3




with open('example.txt', 'r') as f:
    contents = f.read()
    print(contents)


In this example, we’ll open the file “example.txt” in read mode using the open function, then assign it to the variable “f.” The ‘with’ statement is then used to provide ‘‘f” context. We use f.read() to read the file’s contents and print them inside the ‘with’ block.

Python automatically invokes the context manager’s __exit__ method, which in this case is the close() method of the file object f, when a block is exited. By doing this, even if an exception arises while the file is being read, the file will be appropriately closed.

2. Writing Cleaner Conditional Statements

Although they might be challenging to write correctly, conditional statements are an excellent approach to making your code more readable. If/elif/else statements are frequently used in Python, but it’s often overused and hard to read. You might occasionally discover that you’re creating more code than necessary while using if/else expressions. Python’s ternary operators let you build conditional statements that are shorter and simpler to read.
 

Python3




age = 25
  
if age >= 18:
   can_vote = "Yes"
else:
   can_vote = "No"
  
print(f"Can vote: {can_vote}")


Output

Can vote: Yes

However, we can simplify this code block:

Python3




age = 25
can_vote = "Yes" if age >= 18 else "No"
print(f"Can vote: {can_vote}")


Output

Can vote: Yes

In this version of the code block, we use a ternary operator to set the value of can_vote based on the value of age. If the age is greater than or equal to 18, can_vote is set to “Yes”; otherwise, it is set to “No”. This code is more concise and easier to read than the previous example.

3. Simplifying Function Definitions with Decorators

Without changing the function’s source code, decorators let you add functionality to an existing one. In other terms, a decorator is a function that accepts another function as an argument and returns a new function with the added capability.

Here’s an example of how to define a decorator in Python:

Python3




def my_decorator(func):
    def wrapper():
        print("Errors before Editing.")
        func()
        print("Accuracy after Editing.")
    return wrapper
  
  
@my_decorator
def my_function():
    print("Hello, world!")
  
  
my_function()


Output

Errors before Editing.
Hello, world!
Accuracy after Editing.

So, by using a decorator, you can add common functionality that is utilized across several functions without repeating the same code in each function, simplifying the creation of those functions.

4. Keeping Track of Items With the Enumerate Function

A list’s items can be difficult to remember. This can be done using the Enumerate function, which enables you to cycle through a list’s items while keeping track of its index.

Let’s say we have the following list of fruits:

Python3




fruits = ['apple', 'banana', 'orange', 'grape']
  
for index, fruit in enumerate(fruits):
    print(index, fruit)


Output

0 apple
1 banana
2 orange
3 grape

5. Use Variables to Avoid Code Duplication

To avoid code duplication, you can use variables to store values. Instead of having two functions that do exactly the same thing and have identical code, you can create a variable in the first function and use it in a second function by accessing it through its name.

6. Looping Over Several Lists With the Zip Function

The zip function is useful for combining two lists into one and is easy to use. If you have two lists of items (for example, cities in France), you can create a third list by combining the first two:

Here is an example of how to use the zip function to combine two lists:  

Python3




list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined_list = list(zip(list1, list2))
print(combined_list)


Output

[(1, 'a'), (2, 'b'), (3, 'c')]

7. Use Meaningful Variable Names

Give your variable names some context. Avoid using acronyms or abbreviations. For instance, “the first value” and “the second value,” respectively, are more descriptive names for variables than “x” or “x2”.

Avoid using the same variable name across distinct variables in different functions or modules; for instance, it’s probably not a good idea to create a second function with the name “second value” if the first function returns two values. There’s a good risk that someone will soon forget that this second value exists!

8. Hiding Sensitive User Input With GetPass

It’s crucial to take security precautions while writing programs that ask users to input sensitive data, including passwords. The Python getpass module can be used as one method to accomplish this. The getpass module offers a method for hiding user input as they enter their password or other sensitive data. This is significant because it keeps the user’s typing from being seen by others.

Simply import the getpass function module to start using it. This will ask the user for input but not display it on the screen.

For example:

Python3




import getpass
  
password = getpass.getpass("Enter your password: ")
print("Your password is:", password)


The optional prompt parameter of the getpass() function can show the user a message before they enter their input. The user’s input won’t be seen on the screen as they write it.

It’s important to note that the getpass module offers no additional security safeguards like hashing or encryption. It only conceals user input as they type. Use additional security steps to safeguard sensitive information if you need to keep or transfer it.

9. Using the Help Function to Learn More About a Module

A list of all the functions in a Python module can be obtained using the help function. For example, if you want to know more about the range function:

Python3




help(range)


Output

...value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __reduce__(...)
 |      Helper for pickle.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      Return a reverse iterator.
 |  
 |  count(...)
 |      rangeobject.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      rangeobject.index(value) -> integer -- return index of value.
 |      Raise ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop

The range function’s parameters, return value, and other relevant details will be displayed. By giving the name of the module as an argument, the help function may also be used to obtain details regarding a particular module or package:

Python3




import math
help(math)


Output

...s to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /usr/local/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so

This will show details on the math module, including its available functions and constants.

10. Don’t Repeat Yourself (DRY)

DRY is a programming principle for “Don’t Repeat Yourself”. It’s a way of writing code that avoids repetition and keeps your code clean, readable, and easy to understand.

For example: If you have a function that takes two parameters, instead of writing the same function twice with different names (e.g., my_func() and my_func2()), it would be better to write one function whose name is both (e.g., my_func) — then you can call this version from anywhere in your code without having to specify which version you want each time!

Writing reusable code is important because it reduces the number of lines of code and makes it easier to understand what each piece does, even if you don’t understand the full picture yet. Some programmers call these “small modules”, but it’s more commonly called “modules“. 

Conclusion

These practices when followed help you to write better Python code. The better code you write in Python, the fewer chances of bugs occurring. Hence, follow these top 10 tips and tricks to write better Python code. Also, try learning Python in a proficient manner. When you learn Python so efficiently, you can get hired as a Python Developer in big companies and earn a handsome salary.



Last Updated : 23 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads