Home > Software engineering >  How to assign a type to a parameter in python?
How to assign a type to a parameter in python?

Time:02-23

I have a class named triangulo, and a class named coord. So, in a way to create a new instance of triangle, I pass three vertex like

t= triangle( V1, V2, V3)

So, for documentation, I want to write the class triangle in this way

class triangulo( object ):
   def __init__(self, a:coord, b:coord, c:coord)->None:
       """Constructor
       """
       self.A= a
       self.B= b
       self.C= c

class coord( object ):    
    def __init__( self, x, y ): 
        self.x= x
        self.y= y

But when I try to import this library I get this error

NameError: name 'coord' is not defined

So the question is: How can I make python accept vertex as a type of data?

CodePudding user response:

You need to declare the class before using it! so putting coord class on the top of triangulo will solve the problem

CodePudding user response:

You can either wrap the name of the class in quotes

def __init__(self, a: 'coord', b: 'coord', c: 'coord') -> None:
  ...

or you can use a __future__ import to do so automatically

from __future__ import annotations

...

def __init__(self, a: coord, b: coord, c: coord) -> None:
  ...

from __future__ import annotations effectively wraps all type signatures in quotation marks to prevent this exact problem. As long as you're not reflexively viewing type annotations at runtime (with something like MyClass.__annotations__), you won't even notice, and your type checker will work better.

CodePudding user response:

Note that the type hint can be a class or a type (in your case vertex is a class):

from whatever import vertex

class triangle():
    def __init__(self, v1:vertex, v2:vertex, v3:vertex)->None:
        ...

More details at https://www.python.org/dev/peps/pep-0483/

  • Related