es.
class item:
def __init__(self, number:int):
self.number = number
a = item("ciao")
When I instantiate the object I would like to make sure that the name parameter is of type string and otherwise an exception is raised. "name: str" doesn't actually check that the parameter is of the specified type
CodePudding user response:
As per the documentation:
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
If you would like to enforce the type you can use isinstance()
function to do so.
class item:
def __init__(self, number: int):
if not isinstance(number, int):
raise TypeError('Value should be of type int')
self.number = number
CodePudding user response:
Annotations do not add more than information to the developer about the expected information. This is done through an informal contract because, as we know, simple annotations do not contain syntactic meaning but are accessible at runtime, so we can implement a generic decorator that is capable of checking types from the function annotations.
def ensure_annotations(function):
signature = inspect.signature(function)
parameters = signature.parameters
@wraps(function)
def wrapped(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for name, value in bound.arguments.items():
annotation = parameters[name].annotation
if annotation is inspect._empty:
continue
if not isinstance(value, annotation):
raise TypeError(
"{}: {} doesn't actually check that the parameter"
"is of the specified type.".format(name, annotation)
)
function(*args, **kwargs)
return wrapped
class item:
@ensure_annotations
def __init__(self, number: int):
self.number = number
CodePudding user response:
This might be what you want. You can use isinstance()
to check if it is a string. I am not used to exeptions, so I don't know if that is written right, but the logic is.
class item:
def __init__(self, name):
if isinstance(name, str):
self._name = name
else:
self._name = None
raise Exception
a = item('ciai')