"Expected type 'Type', got 'Type[Type]' instead"

Question:

My class has a project where we have to build a database. I keep running into this error where python asks expected a type of the same kind that I gave it (see image
)

It says Expected type 'TableEntry', got 'Type[TableEntry]' instead

TableEntry is a dataclass instance (as per my assignment). I am only calling it for it’s creation newTable = Table(id, TableEntry)
Where Table is another dataclass with an id and data with type TableEntry*.

*I am required to complete the assignment using this format, and am only asking about the syntax, not how to format it

Asked By: daxti

||

Answers:

When you see an error like this:

Expected type ‘TableEntry’, got ‘Type[TableEntry]’ instead

it generally means that in the body of your code you said TableEntry (the name of the type) rather than TableEntry() (an expression that constructs an actual object of that type).

Answered By: Samwise

If your formatter understands sphinx type docstrings (pep257), then if you have code like this:

newTable = Table(TableEntry)

Then you’ll need docstrings like

class TableEntry:
    def __init__(self):
        pass

class Table:
    def __init__(self, table_entry):
        """Descrption.
        
        :param table_entry:
        :type table_entry: type[TableEntry]
        """
        pass     
Answered By: Roman

The problem occurs because you are passing in a Type (TableEntry) when an Instance (TableEntry()) of the class is expected. Notice the trailing parenthesis in the latter one.

I’ve reproduced the error with a basic demo:

from dataclasses import dataclass


@dataclass
class TableEntry:
    name: str
    value: int


@dataclass
class Table:
    id: int
    TableEntry: TableEntry


id = 3
newTable = Table(id, TableEntry)

Here, you were passing the Type TableEntry; not an instance of TableEntry.

To solve the issue:

1- You can either create the TableEntry instance in place:

newTable = Table(id, TableEntry('daxti', 23))

or

2- You can create an instance and then pass it into the Table object:

newTableEntry = TableEntry("daxti", 23)
newTable = Table(id, newTableEntry)
Answered By: Susamate
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.