ericvsmith / dataclasses

Apache License 2.0
584 stars 53 forks source link

Why type checks not giving an error? #167

Closed phibersoft closed 3 years ago

phibersoft commented 3 years ago

Story

I'm pretty new to Python. I switched from typescript to python. As a habit for years, I was able to find the package I was looking for, namely "dataclasses".

What I don't understand is why it doesn't give an error.

Example

In Typescript

class Person {
   name: string;
   constructor(name: string){
       this.name = name;
   }
}

const a = new Person("Phiber");
a.name = 13 // TypeError: integer is not valid to type "string"

In Python

@dataclass
class Person:
   name: str

a = Person(name = "Phiber")
a.name = 13 # No Error?
ericvsmith commented 3 years ago

This repo is only for the non-unsupported backport of dataclassses to Python 3.6.

For questions about dataclasses, I suggest asking on Stack Overflow, or the python-list mailing list.

But the answer to your question is that it wasn't a design goal. See PEP 557 for details. there are a number of add-on packages for dataclasses that will do that validation for you.

jstasiak commented 3 years ago

I feel that this is about compile-type (or transpile-time, alternatively lint-time) checking though, in which case you'll want a tool like Mypy @phibersoft

% cat asd.py 
from dataclasses import dataclass

@dataclass
class Person:
   name: str

a = Person(name = "Phiber")
a.name = 13 # No Error?

% mypy asd.py
asd.py:8: error: Incompatible types in assignment (expression has type "int", variable has type "str")
Found 1 error in 1 file (checked 1 source file)
phibersoft commented 3 years ago

Sorry for my ignorance, I took your time.

@jstasiak Thank you for the "mypy" tactic, it worked for me a lot.