Python Type Checking
Type checking is the process of verifying that a variable or an expression has a certain type. Python is a dynamically typed language, which means that the type checking is done at run-time, not at compile-time.
Python also supports duck typing, which means that an object’s behavior determines its type, rather than its class or inheritance. For example, if an object can be iterated over, it is considered iterable, regardless of its actual type.
Python also allows you to use type hints or annotations to indicate the expected types of variables, arguments and return values. Type hints are optional and do not affect the execution of your code. However, they can help you catch errors and improve readability.
You can use tools like mypy to perform static type checking on your Python code using type hints. Mypy can detect inconsistencies and violations of type contracts before running your code.
Checking the type of a variable is a task that you will perform again and again to gain knowledge. isinstance() function in python returns a boolean depending on whether the given object is an instance of the specified class. It takes two parameters object and the class itself. It can also be used for normal type checking.
class XYZ:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
empOne = XYZ("Zahid", 151214, 75000)
print(isinstance(empOne, XYZ))
data = [1,5,12,14,72]
print(isinstance(data,list))
print(isinstance(data, XYZ))
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment