Netzeband <an...@netzeband.eu> added the comment:

Thanks for your response. I was also thinking much about it and was not able to 
find a nice idea how to get this working. 

The problem is, that we loose the local-namespace information as soon as we 
leave the context of the function, where the class was defined in. This 
information is not stored in the function object of the method, we want to get 
the type hints from. The only open question, I have in this context is: 

Why can python resolve the reference to class A (also a inner class, but no 
forward declaration)? Is there any chance to use the same mechanism also for 
forward declared references?

Beside from this question, I will give you my thoughts, how I think this issue 
could be addressed:

 - What we need is the local namespace information from the function, where the 
inner class was defined in. This is not stored from python in the function 
object of this class (but __global__ is stored). 
 - Maybe any upcoming python version could store this information in __local__ 
? So maybe we could clone this ticket to the python core in order to address 
this?

 - As long as python is not storing this information, a workaround could be 
used: We could define a function decorator, which adds the attribute __local__ 
to a function object. I think about this syntax:

class InnerClass():
    @store_namespace(locals())
    def method() -> 'InnerClass':
        ...

- The get_type_hints function is then checking for the __local__ attribute and 
if it exits it is passed to the function, which resolves the forward 
declaration.

This workaround is not beautiful, since it requires manual work for those 
methods (adding the function decorator to those methods). Furthermore - without 
knowing the internals of the get_type_hints function - this workaround is not 
straight forward and easy to understand. So it needs to be carefully documented 
and even then I expect confusing questions on StackOverflow or other 
communities. 

However, it is a quite rare case that someone really needs to use inner 
classes. Normally one could simply put the class in the global namespace. But 
when this happens and there is really a need for it, than this workaround would 
make it possible. Furthermore, checking a __local__ attribute of the function 
object would be a nice preparation for a feature request to the python core, 
which should store the reference to the local namespace for every function 
object, without using any decorators.

What do you think?

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue37835>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to