Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

394
Views
How should I use the Optional type hint?

I'm trying to understand how to use the Optional type hint. From PEP-484, I know I can use Optional for def test(a: int = None) either as def test(a: Union[int, None]) or def test(a: Optional[int]).

But how about following examples?

def test(a : dict = None):
    #print(a) ==> {'a': 1234}
    #or
    #print(a) ==> None

def test(a : list = None):
    #print(a) ==> [1,2,3,4, 'a', 'b']
    #or
    #print(a) ==> None

If Optional[type] seems to mean the same thing as Union[type, None], why should I use Optional[] at all?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Directly from mypy typing module docs.

  • “Optional[str] is just a shorthand or alias for Union[str, None]. It exists mostly as a convenience to help function signatures look a little cleaner.”
over 4 years ago · Santiago Trujillo Report

0

While the accepted answer is the correct answer, one additional thing to note is that, in the context of kwargs, both Optional[...] and Union[..., None] are redundant and unnecessary. If you're immediately setting your kwarg to None, then both mypy and IDEs assume the obvious and automatically treat the arg as Optional[...].

IDE:

enter image description here

mypy:

mypy automatic Optional

For variables and method/function return values, Optional[...] is still necessary, however, as mypy cannot know, in those cases, to automatically assume anything.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!