The | union operator expresses that a value may have several types; str | None explicitly permits a missing value.
What It Does and Why It Matters
The | union operator expresses that a value may have several types; str | None explicitly permits a missing value. A type checker can narrow the union after an is None check.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
def greeting_label(customer_name: str | None) -> str:
if customer_name is None:
return 'Guest'
return customer_name.strip()
print(greeting_label(None))
print(greeting_label('Morgan'))
How the Code Works
- The definition of greeting_label creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
Guest
Morgan
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Create a function that returns a fallback label when an optional name is absent.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Accessing string methods before excluding None from an optional value.
- Checking only the easiest input and missing a relevant error or boundary case.
Key Takeaways
- The | union operator expresses that a value may have several types; str | None explicitly permits a missing value.
- Create a function that returns a fallback label when an optional name is absent.