[Python] How to order functions to avoid NameError "x is not defined"?

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    15 years ago the answer to this question was:


    The general rule in Python is that a function should be defined before its usage, which does not necessarily mean it needs to be higher in the code.


    This is the correct answer, it also explains why the if __name__=="__main__": solution works
    ​

    But it's not working for me. I have a class that initializes some class variables, one of which is calculated by a helper function that uses the value of another class variable.

    But this yields a NameError regardless of whether the class or the function is defined first.

    In both cases the first execution happens under __main__ after the entire rest of the file has been seen.

    def calc() -> str:
    return Foo.x + '42'

    class Foo:
    x = 'bar'
    y = calc()

    def __init__(self):
    self.a = 'lunch'

    if __name__ == '__main__':
    f = Foo()
    print(f.x, f.y, f.a)


    Error 1:

    File "C:\Users\David\PycharmProjects\jadn2\jadn\otest.py", line 4, in calc
    return Foo.x + '42'
    ^^^
    NameError: name 'Foo' is not defined


    Error 2:

    File "C:\Users\David\PycharmProjects\jadn2\jadn\otest.py", line 4, in Foo
    y = calc()
    ^^^^
    NameError: name 'calc' is not defined


    (I created a wrapper function bar() that calls calc() as in the original question, but as expected permuting the order makes no difference.)

    How can I get the circular definition to work, given that the order of execution is supposed to be what matters?

    Continue reading...

Compartilhe esta Página