RussBaz / enforce

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

Forward references on classes #72

Open obeleh opened 5 years ago

obeleh commented 5 years ago

I know this is similar to #45 but bare with me, it is different

I have this situation:

from enforce import runtime_validation

class A:

    @runtime_validation
    def clone(self) -> 'A':
        return A()

A().clone()

which results in:

NameError: name 'A' is not defined

I've noticed that Forward references are actually implemented but in this case the reference is followed at "compile time" of class A and at that point class A doesn't exist yet.

Basically you want to use a late bind like this:

from enforce import runtime_validation

def late_bind(method):
    checked_meth = None

    def wrap(*args, **kwargs):
        nonlocal checked_meth
        if checked_meth is None:
            checked_meth = runtime_validation(method)
        return checked_meth(*args, **kwargs)

    return wrap

class B:

    @late_bind
    def clone(self) -> 'B':
        return 'bla'

B().clone()