Is it possible to create a regex-constrained type hint?

前端 未结 2 1768
再見小時候
再見小時候 2020-12-17 03:07

I have a helper function that converts a %Y-%m-%d %H:%M:%S-formatted string to a datetime.datetime:

def ymdt_to_datetime(ymdt: str)         


        
相关标签:
2条回答
  • 2020-12-17 03:37

    Using type-hints does nothing in Python and acts as an indication of the type in static checkers. It is not meant to perform any actions, merely annotate a type.

    You can't do any validation, all you can do, with type-hints and a checker, is make sure the argument passed in is actually of type str.

    0 讨论(0)
  • 2020-12-17 03:50

    There currently is no way for types to statically verify that your string matches a precise format, unfortunately. This is partially because checking at compile time the exact values a given variable can hold is exceedingly difficult to implement (and in fact, is NP-hard in some cases), and partially because the problem becomes impossible in the face of things like user input. As a result, it's unlikely that this feature will be added to either mypy or the Python typing ecosystem in the near future, if at all.

    One potential workaround would be to leverage NewType, and carefully control when exactly you construct a string of that format. That is, you could do:

    from typing import NewType
    YmdString = NewType('YmdString', str)
    
    def datetime_to_ymd(d: datetime) -> YmdString:
        # Do conversion here
        return YmdStr(s)
    
    def verify_is_ymd(s: str) -> YmdString:
        # Runtime validation checks here
        return YmdString(s)
    

    If you use only functions like these to introduce values of type YmdString and do testing to confirm that your 'constructor functions' are working perfectly, you can more or less safely distinguish between strings and YmdString at compile time. You'd then want to design your program to minimize how frequently you call these functions to avoid incurring unnecessary overhead, but hopefully, that won't be too onerous to do.

    0 讨论(0)
提交回复
热议问题