[Python] isinstance() returns false because import path is not equal to class type

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I want to check if a variable is a specific class:

    if isinstance(inv, src.components.inventory.Inventory):
    inv.items.remove(entity)


    But the check goes wrong because the class type is different from the import:

    print(f"type of inv: {type(inv)}")


    results in

    type of inv: <class 'components.inventory.Inventory'>


    I'm currently working through the Roguelike Tutorial , but for some reasons I've moved all code files to src/ and components to src/components/.

    How can I solve this problem? I could do a string comparison, but then I'm missing the type cast to be able to call remove.

    Edit: add code snippet and structure

    src/components/base_component.py:

    class BaseComponent:
    ...


    src/components/inventory.py:

    from src.components.base_component import BaseComponent

    class Inventory(BaseComponent):
    ...


    src/components/consumable.py:

    from src.components.inventory import Inventory

    class Consumable(BaseComponent):
    def consume(self) -> None:
    entity = self.parent
    inv = entity.parent
    if isinstance(inv, Inventory):
    inv.items.remove(entity)


    Edit2

    If you downvote the question, please write why, so that I know what information is missing and can add it.

    Continue reading...

Compartilhe esta Página