Lists with multiple types inside

sebastian

New member
I have a program that contains a list of tokens. The items in that list could be:
An int
A float
A string
or, another list with the same possible types (recursively).
I could not find a way to put this so that 11l could understand it; it also doesn't seem to like the "list" type in type hints. It also rejected Union once, not quite sure what that was about.
 

alextretyak

Administrator
Staff member
You can write something like this:
Python:
from enum import IntEnum
from typing import List

class Item:
    class Type(IntEnum):
        INT    = 0
        FLOAT  = 1
        STRING = 2
        LIST   = 3
    ty : Type
    i : int
    f : float
    s : str
    subitems : List['Item']

    def __init__(self, ty):
        self.subitems = []
        self.ty = ty

def print_items(items) -> None:
    for item in items:
        if item.ty == Item.Type.INT:
            print('int(' + str(item.i) + ')')
        elif item.ty == Item.Type.FLOAT:
            print('float(' + str(item.f) + ')')
        elif item.ty == Item.Type.STRING:
            print('str(' + str(item.s) + ')')
        else:
            assert(item.ty == Item.Type.LIST)
            print('[')
            print_items(item.subitems)
            print(']')

root = Item(Item.Type.LIST)
si1 = Item(Item.Type.INT)
si1.i = 1
root.subitems.append(si1)
si2 = Item(Item.Type.FLOAT)
si2.f = 2.5
root.subitems.append(si2)
si3 = Item(Item.Type.LIST)
si1.i = 3
si3.subitems.append(si1)
root.subitems.append(si3)

print_items(root.subitems)
Code:
T Item
   T.enum Type
      INT
      FLOAT
      STRING
      LIST
   Type ty
   Int i
   Float f
   String s
   [Item] subitems

   F (ty)
      .ty = ty

F print_items(items) -> N
   L(item) items
      I item.ty == INT
         print(‘int(’item.i‘)’)
      E I item.ty == FLOAT
         print(‘float(’item.f‘)’)
      E I item.ty == STRING
         print(‘str(’item.s‘)’)
      E
         assert(item.ty == LIST)
         print(‘[’)
         print_items(item.subitems)
         print(‘]’)

V root = Item(Item.Type.LIST)
V si1 = Item(Item.Type.INT)
si1.i = 1
root.subitems.append(si1)
V si2 = Item(Item.Type.FLOAT)
si2.f = 2.5
root.subitems.append(si2)
V si3 = Item(Item.Type.LIST)
si1.i = 3
si3.subitems.append(si1)
root.subitems.append(si3)

print_items(root.subitems)
 
Last edited:

sebastian

New member
It's a good idea, but I can see a lot of extra hassle trying to get items in & out. I was considering making everything a string, and have the parser directly put in the sublists (don't parse them). And then when it comes to reading the parsed tokens, then I could just call the parser on the unparsed sublists (and then I hope you can see where it goes). It might be a bit less efficient, but far more readable. Not to discredit your solution - it's a great idea - but I think it just isn't the best idea for my situation.
 
Top