Home > Software engineering >  Declaration of list of type python
Declaration of list of type python

Time:10-04

Let's suppose to have a class Bag that contains a list of item. What we know about item is just that it has a method called : printDescription().

Now I want to define a method printAllItemsDescription inside Bag, that invokes the method printDescription() on each item inside items list.

This should be the code (it's wrong but I think should looks like this) :

class Bag:
    items:list[item] = []
    .
    . 
    .
    def printAllItemsDescription(this):
        for item in this.items:
            item.printDescription()

My problem is that I don't know how to tell python that my items is a list of item. I know I can do something like item:Item but don't know how to do it with lists.

Then while iterating on items it will know that each item contains a method called printDescription(), but on this moment item is just a variable of undefined type.

P.S. : I tried also to do something like x:list[item] but I got this error :

Subscript for class "list" will generate runtime exception; enclose type annotation in quotes

CodePudding user response:

Python's type hinting is ever-evolving, and they've made some changes over time. Older versions of Python don't support subscripting list as in list[item]. Fortunately, we can get around all of this using a future import. The annotations import from __future__ works in all Python versions starting from 3.7 and effectively pretends that all type signatures are wrapped in quotes so they don't cause issues at runtime.

from __future__ import annotations

class Bag:
    items: list[Item]

    def __init__(self):
        self.items = []

    def printAllItemsDescription(self):
        for item in self.items:
            item.printDescription()

Also, I've made a few minor changes to fit with Python's style. Instance methods should generally have their first argument called self for consistency, and classes (like item) should be written starting with a capital letter, so if you have control over the class item, I would recommend changing it to class Item.

  • Related