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???

2

3 Answers 3

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

In case OP expects sets of ints, you could even annotate withtyping.Set[int] (or set[int] in Python 3.9).
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) 

2 Comments

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.
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.