Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Type Hint for Parameters for Custom Classes? [duplicate]

Let's say that I have created a class defined below, and I have called methods on it:

class Student:

    def __init__(self, name):
        self.name = name
        self.friends = []

    def add_friend(self, new_friend: Student):
        self.friends.append(new_friend)

student1 = Student("Brian")
student2 = Student("Kate")
student1.add_friend(student2)

The method add_friend has a parameter called new_friend, which is a Student object. How do I use type hints to specify that? I assumed that you just have to simply enter the name of the class, like new_friend: Student but it does not work. When I run it, I get a NameError: name 'Student' is not defined. I also tried new_friend: __main__.Student, but it gives me the same error. What am I doing wrong?

like image 410
bran Avatar asked Jan 19 '26 17:01

bran


1 Answers

Per PEP-484, use the string name of the class for forward references:

class Student:

    def __init__(self, name):
        self.name = name
        self.friends = []

    def add_friend(self, new_friend: 'Student'):
        self.friends.append(new_friend)
like image 91
unutbu Avatar answered Jan 22 '26 06:01

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!