Is it possible to get an error when accidentally assigned wrong type in python?
Question:
For example I have next code:
name = str('John Doe')
Let’s imagine after I assign to name = 1
, but code still valid.
Is it possible to get an error in this case in Python or within some special tool?
Answers:
Python is dynamically typed, so you can assign pretty much anything to anything. This would work:
name = 1
name = "Bill"
You can add in type checking with mypy
I’m not sure if you are trying to raise an error, or just wondering if an error might arise if you change the value.
Raise an error
you could check the type using isinstance(obj, class)
and raise TypeError(msg)
.
Is it possible to get an error?
Not directly, but you could as a consequence get an error if you use string operations/methods on an integer.
Example:
>>> name = "john doe"
>>> name = 1
>>> name.split(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'split'
For example I have next code:
name = str('John Doe')
Let’s imagine after I assign to name = 1
, but code still valid.
Is it possible to get an error in this case in Python or within some special tool?
Python is dynamically typed, so you can assign pretty much anything to anything. This would work:
name = 1
name = "Bill"
You can add in type checking with mypy
I’m not sure if you are trying to raise an error, or just wondering if an error might arise if you change the value.
Raise an error
you could check the type using isinstance(obj, class)
and raise TypeError(msg)
.
Is it possible to get an error?
Not directly, but you could as a consequence get an error if you use string operations/methods on an integer.
Example:
>>> name = "john doe"
>>> name = 1
>>> name.split(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'split'