DEV Community

spO0q ๐Ÿ’
spO0q ๐Ÿ’

Posted on • Edited on

Python pro tips

Learn useful tricks and concepts to write smarter scripts and prevent bad errors in Python.

Use get() with dictionaries

In Python, dictionaries are collections of data with key-value pairs.

A direct call of any value through its key is one of the most common mistakes in Python. It leads to bad behaviours.

If the key does not exist, the script exits. Endgame! Instead, use the get() method, it already checks if the key exists:

team = {
   "productor": "Lionsgate",
   "actor": "Keanu Reeves",
   "director": "Chad Stahelski" 
}

actress = team.get("bullets", 2000000)
Enter fullscreen mode Exit fullscreen mode

In the above example, I don't have to check if the key "bullets" exists, and the script does not stop. I can even specify a default value.

Sometimes, in tutorials, we write quick and dirty examples with direct calls, but beginners cannot know it's a bad practice.

== is not is

== does the same as in any other language. It checks if variables have equal values.

is checks if two operands refer to the same object. Every time you add a variable in your script, it gets a new "slot" in memory. You can check it with the id() method:

x = "unknown"
y = "elsewhere"
print(id(x))
print(id(y))
Enter fullscreen mode Exit fullscreen mode

You get:

140476677427376
140476698294128
Enter fullscreen mode Exit fullscreen mode

so :

if (x is y):
    print("wtf")
else:
    print("x is not y")
Enter fullscreen mode Exit fullscreen mode

displays:

 x is not y
Enter fullscreen mode Exit fullscreen mode

However, Python has internal optimisations:

x = 111
y = 111
print(id(x))
print(id(y))

if (x is y):
    print("wtf")
else:
    print("x is not y")
Enter fullscreen mode Exit fullscreen mode

will display something like that:

4457849408
4457849408
wtf
Enter fullscreen mode Exit fullscreen mode

That's normal. Python uses the same memory slot for integers less than 256.

Therefore, be extra careful with the is keyword.

Do not switch between tabs and spaces

This one is especially not allowed in Python3. If you have only one command line in your code block, using spaces instead of tabs won't produce any error.

Choose whatever style you want, but keep consistency. Otherwise, you will get errors sooner or later.

If it's not your code, please consider reformatting it. Most of the time, the IDE (integrated development environment) has options such as "convert tabs into spaces" for that.

Reserved keywords

All languages have reserved keywords. To get the full list just run the following in the Python interpreter:

help("keywords") 
Enter fullscreen mode Exit fullscreen mode

Your IDE is useful here too. Most of the time, if it supports Python (which is likely), reserved keywords have a specific colour.

Use try/except/else and finally

It's always a better idea to try code and catch errors instead of assuming everything will work as expected.

In Python, you can use exceptions like that:

answer = input()

try:
    answer = 111/int(answer)
except:
    print("Error, please check your input and use a positive number")
else:
    print("The answer is", answer)
finally:
    print("That's all folks!")
Enter fullscreen mode Exit fullscreen mode

The keyword "finally" always displays, even if you get exceptions.

Use shorter if statements

Instead of writing:

if myvar == 9 or myvar ==1 or myvar == 7
Enter fullscreen mode Exit fullscreen mode

you can do the following:

if myvar in [9,1,7]
Enter fullscreen mode Exit fullscreen mode

It's faster, and the code is more readable.

Follow guidelines and standards

Of course, you can write your stuff, but guidelines and code standards are the easiest ways, especially if you are a beginner.

In Python, you can use PEP 8 Style Guide. It's a set of rules with Dos and Don'ts.

For example, with PEP8 styles, you cannot use tabs to indent your code. Instead, you use four spaces per each indent.

Besides, it's excellent if you want to contribute.

Write Object Oriented code (OOP)

OOP is a paradigm. It goes beyond any programming/scripting language.

Writing class in Python might look like this:

class Calculation:
    """An example of Python class"""

    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        print(self.num1 + self.num2)


calc = Calculation(36, 37)
calc.add()
Enter fullscreen mode Exit fullscreen mode

Import libraries

Any module can access other modules with the import keyword.

Libraries are handy; for example, if you want to use Python for machine learning, you will probably use Numpy.

But, don't use import like the following:

from os import *

mkdir("existenz")
Enter fullscreen mode Exit fullscreen mode

Instead, do this:

# Standard library imports
import os

try:
    os.mkdir("existenz")
except:
    print("existenz exists")
else:
    print("existenz created")
finally:
    print("\\o/")
Enter fullscreen mode Exit fullscreen mode

The first will import all objects from the os package, which can lead to unexpected errors such as naming conflicts.

Besides, you can import third-party and local packages. For them, I recommend using aliases:

import foo as bar

print(bar)
Enter fullscreen mode Exit fullscreen mode

Note that it's possible to use relative paths to import libraries, but, IMHO, it's not a good practice. Pep8 discourages the use of relative paths in imports, and Python3 removed support for implicit relative imports.

Wrap up

I hope those tips and concepts will help you write better Python code. Indeed, it's not an exhausting list, do not hesitate to share your tricks in the comment section below ;)

Top comments (12)

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

Good stuff. An addition could be instead of just doing โ€ฆ = input(), we add a useful message e.g. โ€ฆ. = input("How many Ship do you need to learn C? ") ๐Ÿ˜Ž

Collapse
 
paddy3118 profile image
Paddy3118

You state "Write Object Oriented code".
You should learn it, and learn when to use it or not. Sometimes a function is all you need.

Collapse
 
spo0q profile image
spO0q ๐Ÿ’

totally agree with you on that point

Collapse
 
epogrebnyak profile image
Evgeny Pogrebnyak

as an idea for exercide - instead of a class with methods, write a dataclass and functions that operate on it, see what is cleaner and where would you prefer either

Collapse
 
muhimen123 profile image
Muhimen

Great article.

Collapse
 
epogrebnyak profile image
Info Comment hidden by post author - thread only accessible via permalink
Evgeny Pogrebnyak


import pandas as np

(seen on twitter)

Collapse
 
danielkun profile image
Daniel Albuschat

Thanks Julien! Maybe you can write your next post about recommended code layout and importing from local files? This is super weird with Python IMHO.

Collapse
 
spo0q profile image
spO0q ๐Ÿ’

good idea, noted!

Collapse
 
epogrebnyak profile image
Evgeny Pogrebnyak

Note that is None is idiomatic check for None, probably makes a good addition

Collapse
 
stefan_stojanovic profile image
Stefan Stojanovic

Cool stuff :)

Had no idea about the first point :D

Collapse
 
paddy3118 profile image
Paddy3118

You mention "Use shorter if statements". I get the sentiment but use a set literal rather than the list as it is better for such lookups, in general.

Collapse
 
epogrebnyak profile image
Evgeny Pogrebnyak • Edited

There is a view, often debated though, that the more if's you have is code, the less is the quality (eg flags in fucntions, avoidable branching, etc)

Some comments have been hidden by the post's author - find out more