[Python-ideas] pep-0484 - Forward references and Didactics - be orthogonal

Steven D'Aprano steve at pearwood.info
Tue Aug 25 18:56:59 CEST 2015


On Tue, Aug 25, 2015 at 01:35:24AM -0700, Andrew Barnert wrote:
> On Aug 24, 2015, at 19:52, Steven D'Aprano <steve at pearwood.info> wrote:
> > 
> > I agree that is desirable, but surely many languages have some sort of 
> > forward declaration syntax? I know that both the Pascal and C families 
> > of languages do.
> 
> What would a forward declaration mean in Python?

I thought it was obvious from context, not to mention from the example 
given by the OP. Its a reference to something that doesn't exist yet, 
namely the class still in the process of being created. E.g.:

class Tree:
    def merge(self, other:'Tree') -> 'Tree':
        ...

The string 'Tree' is a forward reference to the Tree class, as far as 
either the type-checker or a human reader is concerned. The annotations 
will, of course, be strings. But they will be understood as a reference 
to the Tree class. I mean reference in the sense of "to refer to", not 
in the technical sense of "pointer".

Aside: we could use a decorator which replaces all annotations of the 
form 'Tree' with the actual Tree class itself. In pseudo-code:

def decorate(cls):
    for each method in cls:
        for key, val in method.__annotations__:
            if val == cls.__name__:
                method.__annotations__[key] = cls

@decorate
class Tree: ...


This may be useful for runtime introspection, but it comes too late to 
be of any use to any type-checker that runs at compile-time or earlier.


> To be useful, it would have to mean something very different. For 
> example, it could bind the name to some magic marker that means "after 
> something else is bound to this name, go back and fix up everything 
> that made a reference to this magic marker to refer to the bound value 
> instead".

You're over complicating this. (Snarky comments regarding "a-strings" 
for annotations can go straight to /dev/null :-)

Both PEP 484 and mypy call "use the class name as a string as a stand in 
for the actual class" a "forward reference":

https://www.python.org/dev/peps/pep-0484/#forward-references

http://mypy.readthedocs.org/en/latest/kinds_of_types.html#class-name-forward-references

and the OP's example of annotations in the Tree class comes straight out 
of the PEP. I am sorry if I mislead you by being sloppy and calling them 
"forward declaration" sometimes.


-- 
Steve


More information about the Python-ideas mailing list