In my project I need to use user_id as field in many classes. So I try to concentrate the implementation by using a single descriptor instead of duplicating propertys everywhere.
But there is still a subtle problem, Pylance in VSCode won't show the docstring of descriptor just like how it works with property.
Here is the demo.
class _UserID(object):
"""
note for test (wont show)
"""
def __get__(self, obj, _) -> int:
"""
note for test (wont show)
"""
return obj._user_id
def __set__(self, obj, val: int) -> int:
obj._user_id = int(val) if val else 0
return val
class UserWithCustomDescriptor(object):
user_id = _UserID()
def __init__(self) -> None:
self._user_id = 0
class UserWithProperty(object):
def __init__(self) -> None:
self._user_id = 0
@property
def user_id(self) -> int:
"""
note for test
"""
return self._user_id
@user_id.setter
def user_id(self, val: int) -> None:
self._user_id = int(val) if val else 0
if __name__ == "__main__":
user_prop = UserWithProperty()
user_prop.user_id = 42
print(f"{user_prop.__class__.__name__} - {user_prop.user_id}")
user_desc = UserWithCustomDescriptor()
user_desc.user_id = 42
print(f"{user_desc.__class__.__name__} - {user_desc.user_id}")
If you hover your mouse over the user_prop.user_id, the docstring will be showed like this:
while the user_desc.user_id won't show the docstring:
I found a similar question here python-docstring-for-descriptors, but the answer below could not slove this problem.
And I also tried to find solution in python-doc#properties. It seems property will return an instance carrying docstring instead of a direct value. Maybe it's close to the final answer but I'm already stuck in this step for several hours.

