Skip to content

Commit f8ed66a

Browse files
authored
avoid redundant attr name repition with __set_name__
also prevent accidental descriptor re-use
1 parent 1cc7fe7 commit f8ed66a

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

02-descriptors.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
class TypeChecker:
55
required_type = object
66

7-
def __init__(self, name):
7+
def __set_name__(self, owner, name):
8+
old_name = getattr(self, 'name', None)
9+
if old_name:
10+
raise ValueError(f'reused from {old_name}')
11+
812
self.name = f'_{name}'
913

1014
def __get__(self, instance, owner=None):
@@ -21,8 +25,8 @@ class IntType(TypeChecker):
2125

2226

2327
class Point:
24-
x = IntType('x')
25-
y = IntType('y')
28+
x = IntType()
29+
y = IntType()
2630

2731
def __init__(self, x, y):
2832
self.x = x
@@ -44,8 +48,8 @@ class PointType(TypeChecker):
4448

4549

4650
class Circle:
47-
center = PointType('center')
48-
radius = IntType('radius')
51+
center = PointType()
52+
radius = IntType()
4953

5054
def __init__(self, center, radius):
5155
self.center = center

0 commit comments

Comments
 (0)