[Python] use __getattr__ within the same module or console

Discussão em 'Python' iniciado por Stack, Fevereiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have setup a custom __getattr__() method on a module which works perfectly when called from outside the module. However, it doesn't work from within the module itself (since that uses the globals() dict which doesn't redirect to __getattr__ on failure). How would I work around that?

    I was thinking about encapsulating the globals() into a custom dict where I can then modify the __getitem__ method, but that seems very dirty and error prone. Is there another way to do that?

    MWE:

    def __getattr__(name):
    f'custom {name}'

    print(a) # should print 'custom a', but raises NameError

    Continue reading...

Compartilhe esta Página