Check if a field is typing.Optional

前端 未结 5 668
死守一世寂寞
死守一世寂寞 2021-01-18 05:44

What is the best way to check if a field from a class is typing.Optional?

Example code:

from typing import Optional
import re
from dataclasses import         


        
5条回答
  •  青春惊慌失措
    2021-01-18 06:23

    For reference, Python 3.8 (first released October 2019) added get_origin and get_args functions to the typing module.

    Examples from the docs:

    assert get_origin(Dict[str, int]) is dict
    assert get_args(Dict[int, str]) == (int, str)
    
    assert get_origin(Union[int, str]) is Union
    assert get_args(Union[int, str]) == (int, str)
    

    This will allow:

    def is_optional(field):
        return typing.get_origin(field) is Union and \
               type(None) in typing.get_args(field)
    

    For older Pythons, here is some compatibility code:

    # Python >= 3.8
    try:
        from typing import Literal, get_args, get_origin
    # Compatibility
    except ImportError:
        get_args = lambda t: getattr(t, '__args__', ()) \
                             if t is not Generic else Generic
        get_origin = lambda t: getattr(t, '__origin__', None)
    

提交回复
热议问题