Check if a field is typing.Optional

前端 未结 5 671
死守一世寂寞
死守一世寂寞 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:18

    I wrote a library called typedload which can be used to do this.

    The main purpose of the library is conversion to/from json and namedtuple/dataclass/attrs, but since it needed to do those checks, it exposes the functions.

    Note that different versions of python change how the internal typing API works, so checks will not work on every python version.

    My library addresses it internally, hiding the details to the user.

    Using it, the code is like this

    from typing import *
    a = Optional[int]
    
    from typedload import typechecks
    typechecks.is_union(a) and type(None) in typechecks.uniontypes(a)
    

    https://github.com/ltworf/typedload

    Of course, if you don't need to support multiple python versions, you might not care to depend on a library just for this, but future releases might break the check. They have changed API even between minor releases.

提交回复
热议问题