[Python-ideas] Delay evaluation of annotations

Oleg Broytman phd at phdru.name
Tue Sep 27 08:14:58 EDT 2016


On Tue, Sep 27, 2016 at 11:54:40AM +0000, Neil Girdhar <mistersheik at gmail.com> wrote:
> I don't understand why that would work and this clearly doesn't?
> 
> Mutual2 = "Mutual2" # Pre-declare Mutual2
> 
> class Mutual1:
>     def spam(self, x=Mutual2):
                       ^^^^^^^ - calculated at compile time,
                                 not at run time
>         print(type(x))
> 
> class Mutual2:
>     def spam(self):
>         pass
> 
> Mutual1().spam()
> 
> prints class "str" rather than "type".

   Try this:

class Mutual1:
    def spam(self, x=None):
        if x is None:
            x = Mutual2
        print(type(x))

class Mutual2:
    def spam(self):
        pass

Mutual1().spam()

Oleg.
-- 
     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.


More information about the Python-ideas mailing list