DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

3 2

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! 🍺

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay