0

I'd like to create a parameterized class in python and wondering if that is at all possible:

Here is a statically typed class:

class DAGNode(ABC):

    @abstractmethod
    def dependencies(self) -> list[int]:
        pass

I'd like to use a parameterized class like follows:

class DAGNode(ABC):

    ntype = int

    @abstractmethod
    def dependencies(self) -> list[ntype]:  # this will not work in python, what can we do?
        pass

Or another way that is how scala would handle it:

class DAGNode(ABC)[ntype]:  # also not possible in python

    @abstractmethod
    def dependencies(self) -> list[ntype]:
        pass

Is there any construct for python remotely similar?

Note: I was not aware of generics support in python - as shown in the linked question. It's really not known much: I've been around large python shops at large companies and a number of startups, used many dozens of python libraries large and small, and a dozen university courses using the language and it never surfaced. Probably it is used in core libraries that I do not tend to read.

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • So, are you asking about writing correct *type hints*? In which case, you need to use a type variable and make your class [generic](https://docs.python.org/3/library/typing.html#user-defined-generic-types). It works the same as generics in Scala (note, a parameterized type refers to a particular instantiation of a generic class) But of course, that isn't necessary for the code to run, Python is a dynamically typed language. – juanpa.arrivillaga Nov 27 '22 at 06:04
  • I was not aware of `Generics` support in python: it's exactly what I am looking for. – WestCoastProjects Nov 27 '22 at 06:22

0 Answers0