Categories
Python Answers

How to fix Python NameError: name is not defined?

Spread the love

Sometimes, we want to fix Python NameError: name is not defined.

In this article, we’ll look at how to fix Python NameError: name is not defined.

How to fix Python NameError: name is not defined?

To fix Python NameError: name is not defined, we can use a forward reference to annotate the type.

For instance, we write

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

to create the __init__ method with the left and right parameter set to the 'Tree' type.

This tells Python that left and right are Tree class instances without the class being defined yet.

Conclusion

To fix Python NameError: name is not defined, we can use a forward reference to annotate the type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *