Karthikeyan Singaravelan <tir.kar...@gmail.com> added the comment:

Below is a even more simpler reproducer without dataclasses. 'name' is not 
listed as a class attribute in dir(Person) since it's not defined with a value 
but 'age' is with zero. Python seems to not to list something not defined with 
a value in declaration as a class attribute in dir().  Hence 'name' is not 
copied when Person is used as spec. spec only does attribute access validation. 
autospeccing [0] can be used for signature validation. The fields for 
dataclasses are defined in __dataclass_fields__ but I am not sure of special 
casing copying __dataclass_fields__ fields along with dir for dataclasses when 
normal Python doesn't list them as class attributes. If needed I would like 
dir(dataclass) to be changed to include __dataclass_fields__. I would propose 
closing as not a bug.

# ../backups/dataclass_dir.py

from unittest.mock import Mock

class Person:
    name: str
    age: int = 0

    def foo(self):
        pass

person_mock = Mock(spec=Person)
print(dir(Person))
print(dir(person_mock))
person_mock.foo
print("age" in dir(person_mock))
print("name" in dir(person_mock))

$ cpython git:(master) ./python.exe ../backups/dataclass_dir.py
['__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'foo']

['__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 
'assert_any_call', 'assert_called', 'assert_called_once', 
'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 
'assert_not_called', 'attach_mock', 'call_args', 'call_args_list', 
'call_count', 'called', 'configure_mock', 'foo', 'method_calls', 
'mock_add_spec', 'mock_calls', 'reset_mock', 'return_value', 'side_effect']
True
False


[0] https://docs.python.org/3/library/unittest.mock.html#autospeccing

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36580>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to