Reputation: 1058
Is it possible in python to restrict parameter type in python. I tried using List module from typing, but it still allows user to pass class object or an int parameter without giving error.
from typing import List
class Job:
def __init__(self):
self.profit = 0
self.deadlines = 0
class JobsWithDeadlines:
def get_Job_Sequencing_with_deadlines(self, jobs: List[Job]):
print(type(jobs))
j = Job()
j.profit = 20
j.deadline = 2
obj = JobsWithDeadlines()
obj.get_Job_Sequencing_with_deadlines(1)
Upvotes: 0
Views: 1422
Reputation: 114440
The notation jobs:List[Job]
is called annotation. Annotations provide a way of writing hints for the user and for IDEs. Annotations are stored in the function object at runtime, but do not impose any sort of enforceable restriction on the actual code.
To enforce the restriction, you have to check it manually. For example, if subclasses are allowed:
def get_Job_Sequencing_with_deadlines(self, jobs):
if not isinstance(jobs, list):
raise TypeError('non-list input')
print(type(jobs))
If you don't want to allow subclasses, use if type(jobs) is not list:
instead.
Checking each item in a list is equally painful:
if not all(isinstance(job, Job) for job in jobs):
raise TypeError('non-Job input')
You almost never want to do explicit type checking in Python. The language is fundamentally designed with the idea of duck typing in mind. This means that objects that behave the way you want but aren't part of some hard coded class hierarchy should be allowed. Pragmatically this makes perfect sense. If it behaves like a list, do you care if it isn't?
Upvotes: 1
Reputation: 198436
While type annotations are a part of Python, type checking is not. The annotations serve to enable external static type checking. The most common static type checkers for Python are the PyCharm editor and mypy.
"static" means catching the errors before the program is run, just by analysing the source code. There is nothing that can prevent a wrong object being passed at runtime, except an explicit check.
Upvotes: 1