Does python have generic methods?

13,448

Solution 1

No. Python is not a statically typed language, so there is no need for them. Java generics only provide compile time type safety; they don't do anything at runtime. Python doesn't have any compile time type safety, so it wouldn't make sense to add generics to beef up the compile time type checks Python doesn't have.

A list, for example, is an untyped collection. There is no equivalent of distinguishing between List<Integer> and List<String> because a Python list can store any type of object.

Solution 2

Python is a dynamically typed language, so it doesn't need generics. It can do something like this

def addTen(inputData):
    if isinstance(inputData, int):
        return inputData + 10
    elif isinstance(inputData, str):
        return int(inputData) + 10
    else:
        return 10

You can pass any type of data to any function and that function can choose to process different types of data differently.

Share:
13,448
TheProgrammer
Author by

TheProgrammer

Updated on July 22, 2022

Comments

  • TheProgrammer
    TheProgrammer almost 2 years

    Does python have generic methods like Java? If so could you refer to a site that explains it.

  • Juxhin
    Juxhin about 8 years
    Update regarding this since it's a top post - python.org/dev/peps/pep-0484/#generics
  • tribbloid
    tribbloid almost 8 years
    Python is not statically typed but type hinting for member methods can be statically typed. So there is need for them.
  • nme
    nme almost 7 years
    At a time when you wrote this answer there was no typing module. However right now it is a part of standard library (since Python 3.5).