RussBaz / enforce

Python 3.5+ runtime type checking for integration testing and data validation
543 stars 21 forks source link

Forward References #45

Open georgwiese opened 6 years ago

georgwiese commented 6 years ago

Do you support forward references? I'm getting this behavior:

import enforce
import typing

MyType = typing.List[typing.Union[int, 'MyType']]

@enforce.runtime_validation()
def foo(x: MyType):
  pass

foo([1, 2])    # Good
foo([1, [2]])  # RuntimeTypeError

The error states: Argument 'x' was not of type typing.List<~T>[typing.Union[int, _ForwardRef('MyType')]]. Actual type was typing.List[int, typing.List].

Are forward references not supported, is this a bug, or am I doing something wrong? Thanks :)

RussBaz commented 6 years ago

Well, as it turns out, forward reference is not supported yet. Sorry. I will look into this as soon as I have a moment.

Enforce can accept strings as type hints but the types need to exist at the moment of decorating.

I think it is not very hard to fix, just gonna take some time. Forward reference need to invoke a validation tree generation when it is encountered for the first time and replace itself with it before proceeding. I think this is the fastest way to implement it at the moment.

Thanks for the report!

bannsec commented 6 years ago

Run into this a few times as well. Would love for forward refs to be implemented.

RussBaz commented 6 years ago

BTW, the dev branch now supports Forward References. If you have some time - please give it a try. Thanks.