DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

Cool Python elements that I recently discovered!

Working on some Python projects, we need sometimes to have more options to declare some methods or parameters.
Here are two elements that I found which are really useful!


Union

Sometimes to reuse a method we need to accept several kinds of parameters (a number as int or string for example).

One easy way to do it is to use an Union.

...
def function_a(param: Union[int, str]) -> None:
...
Enter fullscreen mode Exit fullscreen mode

Declared like this, you are now able to recieve both type to do your treatment.

Links


Optional

In some cases we need to have empty values and we want to do it properly.
A way to do it is with Optional.

Optional[str]

With this, no need to add a specific description in your documentation to say this value can be equal to None it will immediatly be explicit!

...
def concat(x: Optional[str], y: Optional[str]) -> Optional[str]:
...
Enter fullscreen mode Exit fullscreen mode

The rest of the code won't change, you will test if the value is equal to None or not to know if a value is available or not.

Links


I hope it will help you! 🍺

Top comments (0)