Skip to content

Instantly share code, notes, and snippets.

@sebastianschramm
Created August 31, 2022 16:45
Show Gist options
  • Save sebastianschramm/0b59a02f3bca0fbfb18c9fffcc737af0 to your computer and use it in GitHub Desktop.
Save sebastianschramm/0b59a02f3bca0fbfb18c9fffcc737af0 to your computer and use it in GitHub Desktop.
How to use the union operator instead of Union for typing
from typing import Union
def is_valid_type(object):
return isinstance(object, Union[str, None])
def is_valid_type_new(object):
return isinstance(object, str | None)
if __name__ == "__main__":
for entry in ["foo", None, 10]:
old_style = is_valid_type(entry)
new_style = is_valid_type_new(entry)
print(f"For '{entry}' we get old_style={old_style} and new_style={new_style}")
"""
For 'foo' we get old_style=True and new_style=True
For 'None' we get old_style=True and new_style=True
For '10' we get old_style=False and new_style=False
"""
@sebastianschramm
Copy link
Author

dependencies: python3.10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment