1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] In a class body, is it safe to use vars() to dynamically set an attribute?

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024 às 04:02.

  1. Stack

    Stack Membro Participativo

    In Python, I can use vars() to dynamically set class attributes

    class A:
    vars()['x'] = 1

    print(A.x) # Prints 1


    However, the documentation for vars() states


    Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

    This indicates updates to vars() shouldn't have any effect, but they clearly do based on the example above. The documentation for locals() similarly states


    Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

    This is slightly different from the var() documentation, as it states updates may not affect local variables, while the vars() documentation claims it doesn't affect local variables at all.

    Is it safe to keep relying on using vars() to set class attributes? Or am I relying on unspecified behavior by doing this?

    Continue reading...

Compartilhe esta Página