DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on โ€ข Edited on

๐Ÿค” Python Quiz: Need a hint? I mean, type hint.

Follow me to learn ๐Ÿ Python in 5-minute a day fun quizzes! Find previous quiz here.

We're back with another fun and enlightening Python challenge! This time, we're delving into the world of type hints as guided by PEP 484. Are you ready to test your Python prowess?

We've got two Python functions, both aiming to do the same thing but written differently.

Which one follows the best practices as per PEP 484?

Sample 1

def greet(name):
    return "Hello, " + name

print(greet(123))
Enter fullscreen mode Exit fullscreen mode

Sample 2

def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("Alice"))
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments โ€“ is it 0 for the first sample or 1 for the second? As usually, the correct answer with explanation will be in comment.

or Go to the next quiz

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
vladignatyev profile image
Vladimir Ignatev โ€ข

Correct answer

Sample 1 lacks type hints and allows any data type to be passed as an argument, which can lead to runtime errors. For example, passing an integer as in greet(123) would still work but doesn't align with the intended use of the function.

Sample 2 correctly uses type hints as per PEP 484. It specifies that the name parameter should be a string (str) and the return type of the function is also a string (str). This promotes code readability and helps in catching type-related errors during development.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

๐Ÿ‘ฅ Ideal for solo developers, teams, and cross-company projects

Learn more