Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Python Best Practices Annotations
BackEnd DevelopmentCoding Foundations

Python Best Practices Annotations

Python Annotations

Anastasiia Tsurkan

by Anastasiia Tsurkan

Backend Developer

Nov, 2023
6 min read

facebooklinkedintwitter
copy
Python Best Practices Annotations

Let's consider annotations. Think of them as your code's sidekicks, making sure everyone's on the same page. Today, we're unleashing the power of type annotations – those little hints turn your code into a language everyone can understand. Ready to transform your code into a crystal-clear masterpiece? Let's roll!

Naming Conventions

web server layers

Main points:

  • The keywords are reserved words that cannot be used as variable names, function names, or any other identifiers. So, don’t use reserved words. (For examples: True, False, None, return, sum, type, str, int, list, dict, def, if, else, lambda, and others)
  • Variable and function should be named in snake_case style (example: initial_amount = 5, some_function_name())
  • Class used to be named in PascalCase: each word starts with a capital letter, don’t use underscore (class MyClass, class User, class AdminManager)
  • Constants are usually named using uppercase words with underscores(TEMPERATURE = 36.6, MAX_FILE_SIZE = 1024)
  • Don’t forget to give meaningful names. Because variable names have to show which information is saved, the function shows what it has to do.

When writing Python code, employing an effective naming approach can save time. Whether for variables, functions, classes, packages, or other elements, opting for a consistent naming convention can expedite project timelines and enhance the collaborative process among team members.

Run Code from Your Browser - No Installation Required

Run Code from Your Browser - No Installation Required

What are Annotations?

Some important theory! Python is a dynamically typed language. It means you don’t need to define variable type within the value. Python is doing it for you. You can determine the type, but the script will skip it anyway:

copy

There is no error, Python dynamically determines the type of each variable. But Python is still a strongly typed language. If we add an int to str, we will receive:

So, why do we need type annotations?

The last example was easy to read, but what about functions? Sometimes it is too complicated to easily predict what data type might be input and what type is expected as output. Let`s see some examples:

a and b arguments can have any type (int, str, float, bool, list, custom Class) as well as returning type.

And if we are decided to write a calculator, but another person will not use it properly and will pass strings as arguments?

For the protection of the logic of our program is better to use type annotations and to be on one page with our colleagues or users.

Now we see that function add must receive int type and return int too.

Complex Annotations

Python improves all the time, and the meaningful part in renovation is laid to annotations. You see, it`s important! Starting from version 3.5, Python libraries extend with a library named typing. You can add it to your project by

Let’s see some examples:

copy

The function accepts a dictionary with keys of type string and values of type integer. Ultimately, it returns a list of string entities.

Additionally, we can specify multiple types within square brackets, such as List[str | int | float], including as many types as necessary.

If our function receives input but doesn't return anything, we should use -> None as the return type annotation

copy

Additionally, there are many other types of annotations used by Python developers, such as Any, Iterable, and Callable. It's best to learn these through practice.

Docstring

Docstring in Python is a documentation string that is used to describe the purpose and behavior of a function, module, or class. It is a string that is placed right after the function name or module or class, enclosed in triple quotes """...""" or ‘’’...‘’’ and can span multiple lines. First of all, let's read the docstring of some built-in function.

copy

Now, let's create our function with the docstring.

copy

Start Learning Coding today and boost your Career Potential

Start Learning Coding today and boost your Career Potential

Conclusion

By adhering to these best practices, Python developers can create code that not only works well but is also scalable, maintainable, and a pleasure to work with for themselves and others.

Was this article helpful?

Share:

facebooklinkedintwitter
copy

Was this article helpful?

Share:

facebooklinkedintwitter
copy

Content of this article

We're sorry to hear that something went wrong. What happened?
some-alt