0

I can do this to define a Matrix type for instance:

from typing import List

Matrix = List[List[float]]

How can I do the same with custom types? For instance I tried this but it doesn't seem effective:

class MyClass: 

@staticmethod
def __getitem__(self, item: Type):
    """
    You can type like this:
    var: MyClass[BaseCausalityFeature] = something
    """
    return MyClass

Moreover, what I've just coded doesn't work when I try to use it, it says Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances.

I'd love to be able to specify custom nested types to my custom objects with typings, like CPP templates to make my code more readable in presence of complex type hierarchies and composition.

I'm using Python 3.6.9.

Guillaume Chevalier
  • 9,613
  • 8
  • 51
  • 79
  • 2
    https://docs.python.org/3/library/typing.html#user-defined-generic-types – user2357112 Jul 02 '20 at 04:11
  • Thanks. I could accept an answer provided a concrete example here with the class above. – Guillaume Chevalier Jul 02 '20 at 05:32
  • Hey there I found a similiar question for that, I think it seems quite simple: [link](https://stackoverflow.com/questions/6187932/how-to-write-a-static-python-getitem-method) – Max R Jul 02 '20 at 05:44
  • @MaxR This is interesting at least for having the syntax of the type to compile, but it doesn't seem to allow for different metaclasses to be taken into account with the typing system. The comment by user2357112 seems like a good way to do it, although it seems complicated and I'm not 100% sure it'll fully work until I try and test it. – Guillaume Chevalier Jul 05 '20 at 14:42

0 Answers0