0

When defining an user defined function with parameters, in general a dummy variable is declared. That variable in the function definition can receive values of any type (int, str, list, class instance, etc). But there are situations where we need only a specific data type to receive. Is there any way to restrict that variable to receive values of specific datatype? The following eg gives a clear view

a={1,2,3,4}
b={5,6,7,8}
c=(1,2,3,4)
def func(a,b):
   print("union = " ,a|b)
   print("intersection = " ,a&b)
   print("difference = " ,a-b)
   print("sym diff = " ,a^b)
func(a,b)
func(b,c)
func(a,4)

Here I need to restrict the variables a and b to receive only objects of class set. How can it be done???

  • 1
    Usually you just do the operation you need, but put a try/except block around it in case of failure. – Mark Ransom Jul 02 '20 at 16:42
  • Does this answer your question? [How do Python functions handle the types of the parameters that you pass in?](https://stackoverflow.com/questions/2489669/how-do-python-functions-handle-the-types-of-the-parameters-that-you-pass-in) – hlzl Jul 02 '20 at 16:52

3 Answers3

2

Python is dynamically typed, so the language itself doesn't provide any sort of check. You can pass an argument of any type when you call the function. The function is free to make runtime checks on the argument before trying to use it, but typically that isn't done. Python code assumes something called duck typing: a value of any type should be allowed as long as it behaves as expected.

You can provide a type hint, which serves as documentation as well as something a tool like mypy can use to determine if the restriction is met statically (that is, without having to execute the code).

def func(a1: set, b1: set) -> None:
   print("union = " ,a|b)
   print("intersection = " ,a&b)
   print("difference = " ,a-b)
   print("sym diff = " ,a^b)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    In case OP expects sets of ints, you could even annotate with`typing.Set[int]` (or `set[int]` in Python 3.9). – timgeb Jul 03 '20 at 06:31
1

Take a look at isinstance(). You could raise an exception if the type didn't match what you wanted, like so:

def func(a1, b1):
    if not isinstance(a1, set) or not isinstance(b1, set):
        raise TypeError("A value was not a set")
    print("union = " ,a|b)
    print("intersection = " ,a&b)
    print("difference = " ,a-b)
    print("sym diff = " ,a^b)

Dash
  • 1,191
  • 7
  • 19
  • This isn't that much different from the original; you can still call `func` with the wrong type of argument, but now you get a different runtime exception. – chepner Jul 02 '20 at 16:45
  • True, or you could skip that one. Although it's not very pythonic, and it would be easier to wrap in a try except block, like Mark said. It just depends on what the intended purpose is for not allowing other types. – Dash Jul 02 '20 at 16:47
1

You can use isinstance to explicitly check the type of your variables.

a={1,2,3,4}
b={5,6,7,8}
c=(1,2,3,4)
def func(a1,b1):
   if not(isinstance(a1, set) and isinstance(b1, set)):
      raise ValueError("a1 and b1 must be of type set.")
   print("union = " ,a|b)
   print("intersection = " ,a&b)
   print("difference = " ,a-b)
   print("sym diff = " ,a^b)
func(a,b)
func(b,c)
func(a,4)

You can also specify several types to allow.

Adam Oudad
  • 337
  • 1
  • 9