2

I'm working with generics in python, and want to know if I can achieve generics in python as other languages. The syntax needs not to be same as other languages but if I can do something like


template<typename T>
class List {
public:
    T array[10];
};

int main() {
    List<int> list;
}

I tried the below code but I'm not sure how can I achieve the same as C++ or Java. Like, I shouldn't be allowed to add objects of any other type once I define the data type on initialization.


from typing import TypeVar, Generic, List

T = TypeVar('T')


class CircularQueue(Generic[T]):

    def __init__(self):
        self._front = 0
        self._rear = 0
        self._array = list()

    def mod(self, x): return (x+1) % (len(self._array)+1)

    @property
    def is_full(self):
        return self.mod(self._rear) == self.mod(self._front) + 1

    def insert(self, element: T):
        if not self.is_full:
            self._rear += 1
            self._array.append(element)


if __name__ == "__main__":
    # I want to Initialize the queue as cQueue = CircularQueue<int>()
    # Something that other compiled languauges offer
    # Is it possible to do so?
    # Or any other method so that I can restrict the type of objects.
    cQueue = CircularQueue()
    cQueue.insert(10)

    # Here I want to raise an error if I insert any other type of Object
    cQueue.insert('A')    


  • I think numpy might do things like this, you could check out how it works – Barmar Jul 11 '19 at 20:12
  • 2
    But in general, languages like Python are not designed around declaring strict types. – Barmar Jul 11 '19 at 20:12
  • Nice question, but I don't think it's possible in Python, due to it's typing system. [This somewhat related question](https://stackoverflow.com/questions/11328920/is-python-strongly-typed) might help you better understand typing in Python. – gmauch Jul 11 '19 at 20:14
  • 1
    Python pretty much uses "duck typing", which means in practice, it's mostly generic by default. – jjramsey Jul 11 '19 at 20:15

1 Answers1

3

Python does not have the notion of generics but one could say that every function is generic because parameters are not actually typed. This is a duck typing approach where anything that walks like a duck and quacks like a duck it treated as a duck. So, typically, "generic" functions would only check if the parameters or objects have the minimal set of required attributes and process the data accordingly.

Alain T.
  • 40,517
  • 4
  • 31
  • 51