Fwd: A typing question

Peter Otten __peter__ at web.de
Sun Oct 30 15:43:23 EDT 2022


On 30/10/2022 14:37, Peter J. Holzer wrote:
> On 2022-10-30 09:23:27 -0400, Thomas Passin wrote:
>> On 10/30/2022 6:26 AM, Peter J. Holzer wrote:
>>> On 2022-10-29 23:59:44 +0100, Paulo da Silva wrote:
>>>> The funny thing is that if I replace foos by Foos it works because it gets
>>>> known by the initial initialization :-) !
>>>>
>>>> ________________________
>>>> from typing import List, Optional
>>>>
>>>> class GLOBALS:
>>>>       Foos: Optional[Foos]=None
>>> [...]
>>>> class Foos:
>>>
>>> That seems like a bug to me. What is the «Foos» in «Optional[Foos]»
>>> referring to?
>>>
>>> If it's the class attribute «Foos» then that's not a type and even if
>>> its type is inferred that's not the same as «Optional[it's type]», or is
>>> it?
>>>
>>> If it's referring to the global symbol «Foos» (i.e. the class defined
>>> later) that hasn't been defined yet, so it shouldn't work (or
>>> alternatively, if forward references are allowed it should always work).
>>
>> Quoting a forward-referenced type is the way to use one.  Unquoted types
>> need to have been declared already.
>
> Yes. I was referring to the code as written. Why does that work? I don't
> think it should.

For me it makes sense. I think mypy should refrain from trying to figure
out order of execution. If the above is disallowed, how about

if random.randrange(2):
     class A: pass

class B(A): pass

?

One interesting consequence of that policy -- take the whole scope
instead of the most recent appearance of a name is that

class A: pass
class A: pass

won't compile.

While I didn't expect that I think I like it ;)



More information about the Python-list mailing list