Andrei
Andrei

Reputation: 46

Type errors in function call expressions

I have dataclass and function with parameter type of that class.

from dataclass import dataclass 

@dataclass
class A:
  val_1: str = ""
  val_2: str = ""

def func(arg: A):
  print(arg.val_1, arg.val_2)

When I try to call method like this func(arg=A) I get warning "Expected type 'A', got 'Type[A]' instead". What is literally means?

Upvotes: 0

Views: 182

Answers (1)

deceze
deceze

Reputation: 522109

The type hint arg: A means that the argument should be an instance of A, because that's the typical use case. The class A itself is denoted as Type[A], explicitly referring to the type itself (or any subclass thereof), which is a less common use case and hence has the more complex syntax.

When you call func(A), you're passing A, the class itself, which does not match the type hint. You must pass an instance: func(A()).

Upvotes: 1

Related Questions