Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: what is the purpose of '|'

So basically, when i go to the builtins.py file, i find many functions like this:

def foo(o: object, arg: int | None = ...) -> int: ...

When i tried this out myself, it actually didn’t give out any errors, and still works like a normal function. I’m wondering why people use it and what the purpose of it is. When i make a function like the foo function (which is the first example given before this one):

def bar(arg: int, arg1: int | None = ...) -> int:
    try:
        return arg + arg1
    except:
        print('You cannot add a string and int together')

I don’t find any difference between def bar(arg: int, arg1: int): ... and def bar(arg: int, arg1: int | None = ...) -> int: ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a type hint. In this case, int | None is a Union type indicating that the arg parameter will either be an int or None.

You might also find some valuable background info here: PEP 483.

One benefit of these hints is that IDEs and linters can use them to help analyze your code and catch certain kinds of errors. Some more high-level info is available here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading