On 6/24/19 12:48 PM, Arup Rakshit wrote:
> I am little experimenting with Python type annotation today. I wrote a simple 
> class as below:
> 
>>>> from datetime import date
>>>> class Person:
> ...     dob: date
> ...     def __init__(self, dob):
> ...             self.dob = dob
> ... 
>>>> Person(11)
> <__main__.Person object at 0x10e078128>
>>>> p = Person(11)
>>>> p.dob
> 11
> 
> Although I marked dob as date type, why am I able to assign it an int? So my 
> question how does type annotation helps, when should we use them and what 
> advantages it brings?

it's a mechansim to support static checking in various forms - tools,
IDES, etc.  It also serves to document your intent without having to
write as much in the docstring.

Python remains a "consenting adults" language, that is if you really
want to do something, you can, so the type hints are not enforced at
runtime.  Since it's not always the case that doing something possible
is a good idea, the type hints are there to make it easier to detect issues.


Your annotation looks funky, by the way, I'd expect to see it written as:

> ...     def __init__(self, dob: date):
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to