|
6 | 6 |
|
7 | 7 | import pickle
|
8 | 8 | import inspect
|
| 9 | +import builtins |
9 | 10 | import unittest
|
10 | 11 | from unittest.mock import Mock
|
11 | 12 | from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional
|
@@ -192,6 +193,55 @@ class C:
|
192 | 193 | first = next(iter(sig.parameters))
|
193 | 194 | self.assertEqual('self', first)
|
194 | 195 |
|
| 196 | + def test_field_named_object(self): |
| 197 | + @dataclass |
| 198 | + class C: |
| 199 | + object: str |
| 200 | + c = C('foo') |
| 201 | + self.assertEqual(c.object, 'foo') |
| 202 | + |
| 203 | + def test_field_named_object_frozen(self): |
| 204 | + @dataclass(frozen=True) |
| 205 | + class C: |
| 206 | + object: str |
| 207 | + c = C('foo') |
| 208 | + self.assertEqual(c.object, 'foo') |
| 209 | + |
| 210 | + def test_field_named_like_builtin(self): |
| 211 | + # Attribute names can shadow built-in names |
| 212 | + # since code generation is used. |
| 213 | + # Ensure that this is not happening. |
| 214 | + exclusions = {'None', 'True', 'False'} |
| 215 | + builtins_names = sorted( |
| 216 | + b for b in builtins.__dict__.keys() |
| 217 | + if not b.startswith('__') and b not in exclusions |
| 218 | + ) |
| 219 | + attributes = [(name, str) for name in builtins_names] |
| 220 | + C = make_dataclass('C', attributes) |
| 221 | + |
| 222 | + c = C(*[name for name in builtins_names]) |
| 223 | + |
| 224 | + for name in builtins_names: |
| 225 | + self.assertEqual(getattr(c, name), name) |
| 226 | + |
| 227 | + def test_field_named_like_builtin_frozen(self): |
| 228 | + # Attribute names can shadow built-in names |
| 229 | + # since code generation is used. |
| 230 | + # Ensure that this is not happening |
| 231 | + # for frozen data classes. |
| 232 | + exclusions = {'None', 'True', 'False'} |
| 233 | + builtins_names = sorted( |
| 234 | + b for b in builtins.__dict__.keys() |
| 235 | + if not b.startswith('__') and b not in exclusions |
| 236 | + ) |
| 237 | + attributes = [(name, str) for name in builtins_names] |
| 238 | + C = make_dataclass('C', attributes, frozen=True) |
| 239 | + |
| 240 | + c = C(*[name for name in builtins_names]) |
| 241 | + |
| 242 | + for name in builtins_names: |
| 243 | + self.assertEqual(getattr(c, name), name) |
| 244 | + |
195 | 245 | def test_0_field_compare(self):
|
196 | 246 | # Ensure that order=False is the default.
|
197 | 247 | @dataclass
|
|
0 commit comments