How to declare a function argument that can accept any type in Python

3 Answers

0 votes
def AcceptAnyType(x):
    print(f"The type of x is: {type(x)}")
    if type(x) == int:
        print("x is an integer.")
    elif type(x) == float:
        print("x is a float.")
    elif type(x) == bool:
        print("x is a bool.")    
    elif type(x) == str:
        print("x is a string.")
    else:
        print("x is of another type.")


AcceptAnyType(9001)
AcceptAnyType(3.14)
AcceptAnyType('a')
AcceptAnyType("XYZ")
AcceptAnyType(True)


  
'''
run:
  
The type of x is: <class 'int'>
x is an integer.
The type of x is: <class 'float'>
x is a float.
The type of x is: <class 'str'>
x is a string.
The type of x is: <class 'str'>
x is a string.
The type of x is: <class 'bool'>
x is a bool.

'''

 



answered Aug 1, 2025 by avibootz
0 votes
def AcceptAnyType(x):
    if isinstance(x, int):
        print("x is an integer.")
    elif isinstance(x, float):
        print("x is a float.")
    elif isinstance(x, bool):
        print("x is a bool.")
    elif isinstance(x, str):
        print("x is a string.")
    else:
        print(f"x is of type: {type(x)}")


AcceptAnyType(9001)
AcceptAnyType(3.14)
AcceptAnyType('a')
AcceptAnyType("XYZ")
AcceptAnyType(True)


  
'''
run:
  
x is an integer.
x is a float.
x is a string.
x is a string.
x is an integer.

'''

 



answered Aug 1, 2025 by avibootz
0 votes
from typing import Any

def AcceptAnyType(x: Any):
    if isinstance(x, list):
        print("x is a list.")
    elif isinstance(x, dict):
        print("x is a dictionary.")
    else:
        print(f"x is of type: {type(x)}")


AcceptAnyType({1: "C", 2: "Java", 3: "Python",})
AcceptAnyType([1, 2, 3])
AcceptAnyType(9001)
AcceptAnyType(3.14)
AcceptAnyType('a')
AcceptAnyType("XYZ")
AcceptAnyType(True)


  
'''
run:
  
x is a dictionary.
x is a list.
x is of type: <class 'int'>
x is of type: <class 'float'>
x is of type: <class 'str'>
x is of type: <class 'str'>
x is of type: <class 'bool'>

'''

 



answered Aug 1, 2025 by avibootz
...