Debian Codegraph @

lib-python/3/types.py

raw symbols SCIP
1 """
2 Define names for built-in types that aren't directly accessible as a builtin.
3 """
4 import sys
5
6 # Iterators in Python aren't a matter of type but of protocol. A large
7 # and changing number of builtin types implement *some* flavor of
8 # iterator. Don't check the type! Use hasattr to check for both
9 # "__iter__" and "__next__" attributes instead.
10
11 def _f(): pass
12 FunctionType = type(_f)
13 LambdaType = type(lambda: None) # Same as FunctionType
14 CodeType = type(_f.__code__)
15 MappingProxyType = type(type.__dict__)
16 SimpleNamespace = type(sys.implementation)
17
18 def _cell_factory():
19 a = 1
20 def f():
21 nonlocal a
22 return f.__closure__[0]
23 CellType = type(_cell_factory())
24
25 def _g():
26 yield 1
27 GeneratorType = type(_g())
28
29 async def _c(): pass
30 _c = _c()
31 CoroutineType = type(_c)
32 _c.close() # Prevent ResourceWarning
33
34 async def _ag():
35 yield
36 _ag = _ag()
37 AsyncGeneratorType = type(_ag)
38
39 class _C:
40 def _m(self): pass
41 MethodType = type(_C()._m)
42
43 BuiltinFunctionType = type(len)
44 BuiltinMethodType = type([].append) # Same as BuiltinFunctionType
45
46 WrapperDescriptorType = type(object.__init__)
47 MethodWrapperType = type(object().__str__)
48 MethodDescriptorType = type(str.join)
49 ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
50
51 ModuleType = type(sys)
52
53 try:
54 raise TypeError
55 except TypeError as exc:
56 TracebackType = type(exc.__traceback__)
57 FrameType = type(exc.__traceback__.tb_frame)
58
59 # For Jython, the following two types are identical
60 GetSetDescriptorType = type(FunctionType.__code__)
61 GenericAlias = type(list[int])
62 if sys.implementation.name == 'pypy':
63 MemberDescriptorType = type(GenericAlias._origin)
64 else:
65 MemberDescriptorType = type(FunctionType.__globals__)
66
67 del sys, _f, _g, _C, _c, _ag # Not for export
68
69
70 # Provide a PEP 3115 compliant mechanism for class creation
71 def new_class(name, bases=(), kwds=None, exec_body=None):
72 """Create a class object dynamically using the appropriate metaclass."""
73 resolved_bases = resolve_bases(bases)
74 meta, ns, kwds = prepare_class(name, resolved_bases, kwds)
75 if exec_body is not None:
76 exec_body(ns)
77 if resolved_bases is not bases:
78 ns['__orig_bases__'] = bases
79 return meta(name, resolved_bases, ns, **kwds)
80
81 def resolve_bases(bases):
82 """Resolve MRO entries dynamically as specified by PEP 560."""
83 new_bases = list(bases)
84 updated = False
85 shift = 0
86 for i, base in enumerate(bases):
87 if isinstance(base, type):
88 continue
89 if not hasattr(base, "__mro_entries__"):
90 continue
91 new_base = base.__mro_entries__(bases)
92 updated = True
93 if not isinstance(new_base, tuple):
94 raise TypeError("__mro_entries__ must return a tuple")
95 else:
96 new_bases[i+shift:i+shift+1] = new_base
97 shift += len(new_base) - 1
98 if not updated:
99 return bases
100 return tuple(new_bases)
101
102 def prepare_class(name, bases=(), kwds=None):
103 """Call the __prepare__ method of the appropriate metaclass.
104
105 Returns (metaclass, namespace, kwds) as a 3-tuple
106
107 *metaclass* is the appropriate metaclass
108 *namespace* is the prepared class namespace
109 *kwds* is an updated copy of the passed in kwds argument with any
110 'metaclass' entry removed. If no kwds argument is passed in, this will
111 be an empty dict.
112 """
113 if kwds is None:
114 kwds = {}
115 else:
116 kwds = dict(kwds) # Don't alter the provided mapping
117 if 'metaclass' in kwds:
118 meta = kwds.pop('metaclass')
119 else:
120 if bases:
121 meta = type(bases[0])
122 else:
123 meta = type
124 if isinstance(meta, type):
125 # when meta is a type, we first determine the most-derived metaclass
126 # instead of invoking the initial candidate directly
127 meta = _calculate_meta(meta, bases)
128 if hasattr(meta, '__prepare__'):
129 ns = meta.__prepare__(name, bases, **kwds)
130 else:
131 ns = {}
132 return meta, ns, kwds
133
134 def _calculate_meta(meta, bases):
135 """Calculate the most derived metaclass."""
136 winner = meta
137 for base in bases:
138 base_meta = type(base)
139 if issubclass(winner, base_meta):
140 continue
141 if issubclass(base_meta, winner):
142 winner = base_meta
143 continue
144 # else:
145 raise TypeError("metaclass conflict: "
146 "the metaclass of a derived class "
147 "must be a (non-strict) subclass "
148 "of the metaclasses of all its bases")
149 return winner
150
151 class DynamicClassAttribute:
152 """Route attribute access on a class to __getattr__.
153
154 This is a descriptor, used to define attributes that act differently when
155 accessed through an instance and through a class. Instance access remains
156 normal, but access to an attribute through a class will be routed to the
157 class's __getattr__ method; this is done by raising AttributeError.
158
159 This allows one to have properties active on an instance, and have virtual
160 attributes on the class with the same name. (Enum used this between Python
161 versions 3.4 - 3.9 .)
162
163 Subclass from this to use a different method of accessing virtual attributes
164 and still be treated properly by the inspect module. (Enum uses this since
165 Python 3.10 .)
166
167 """
168 def __init__(self, fget=None, fset=None, fdel=None, doc=None):
169 self.fget = fget
170 self.fset = fset
171 self.fdel = fdel
172 # next two lines make DynamicClassAttribute act the same as property
173 self.__doc__ = doc or fget.__doc__
174 self.overwrite_doc = doc is None
175 # support for abstract methods
176 self.__isabstractmethod__ = bool(getattr(fget, '__isabstractmethod__', False))
177
178 def __get__(self, instance, ownerclass=None):
179 if instance is None:
180 if self.__isabstractmethod__:
181 return self
182 raise AttributeError()
183 elif self.fget is None:
184 raise AttributeError("unreadable attribute")
185 return self.fget(instance)
186
187 def __set__(self, instance, value):
188 if self.fset is None:
189 raise AttributeError("can't set attribute")
190 self.fset(instance, value)
191
192 def __delete__(self, instance):
193 if self.fdel is None:
194 raise AttributeError("can't delete attribute")
195 self.fdel(instance)
196
197 def getter(self, fget):
198 fdoc = fget.__doc__ if self.overwrite_doc else None
199 result = type(self)(fget, self.fset, self.fdel, fdoc or self.__doc__)
200 result.overwrite_doc = self.overwrite_doc
201 return result
202
203 def setter(self, fset):
204 result = type(self)(self.fget, fset, self.fdel, self.__doc__)
205 result.overwrite_doc = self.overwrite_doc
206 return result
207
208 def deleter(self, fdel):
209 result = type(self)(self.fget, self.fset, fdel, self.__doc__)
210 result.overwrite_doc = self.overwrite_doc
211 return result
212
213
214 class _GeneratorWrapper:
215 # TODO: Implement this in C.
216 def __init__(self, gen):
217 self.__wrapped = gen
218 self.__isgen = gen.__class__ is GeneratorType
219 self.__name__ = getattr(gen, '__name__', None)
220 self.__qualname__ = getattr(gen, '__qualname__', None)
221 def send(self, val):
222 return self.__wrapped.send(val)
223 def throw(self, tp, *rest):
224 return self.__wrapped.throw(tp, *rest)
225 def close(self):
226 return self.__wrapped.close()
227 @property
228 def gi_code(self):
229 return self.__wrapped.gi_code
230 @property
231 def gi_frame(self):
232 return self.__wrapped.gi_frame
233 @property
234 def gi_running(self):
235 return self.__wrapped.gi_running
236 @property
237 def gi_yieldfrom(self):
238 return self.__wrapped.gi_yieldfrom
239 cr_code = gi_code
240 cr_frame = gi_frame
241 cr_running = gi_running
242 cr_await = gi_yieldfrom
243 def __next__(self):
244 return next(self.__wrapped)
245 def __iter__(self):
246 if self.__isgen:
247 return self.__wrapped
248 return self
249 __await__ = __iter__
250
251 def coroutine(func):
252 """Convert regular generator function to a coroutine."""
253
254 if not callable(func):
255 raise TypeError('types.coroutine() expects a callable')
256
257 if (func.__class__ is FunctionType and
258 getattr(func, '__code__', None).__class__ is CodeType):
259
260 co_flags = func.__code__.co_flags
261
262 # Check if 'func' is a coroutine function.
263 # (0x180 == CO_COROUTINE | CO_ITERABLE_COROUTINE)
264 if co_flags & 0x180:
265 return func
266
267 # Check if 'func' is a generator function.
268 # (0x20 == CO_GENERATOR)
269 if co_flags & 0x20:
270 # TODO: Implement this in C.
271 co = func.__code__
272 # 0x100 == CO_ITERABLE_COROUTINE
273 func.__code__ = co.replace(co_flags=co.co_flags | 0x100)
274 return func
275
276 # The following code is primarily to support functions that
277 # return generator-like objects (for instance generators
278 # compiled with Cython).
279
280 # Delay functools and _collections_abc import for speeding up types import.
281 import functools
282 import _collections_abc
283 @functools.wraps(func)
284 def wrapped(*args, **kwargs):
285 coro = func(*args, **kwargs)
286 if (coro.__class__ is CoroutineType or
287 coro.__class__ is GeneratorType and coro.gi_code.co_flags & 0x100):
288 # 'coro' is a native coroutine object or an iterable coroutine
289 return coro
290 if (isinstance(coro, _collections_abc.Generator) and
291 not isinstance(coro, _collections_abc.Coroutine)):
292 # 'coro' is either a pure Python generator iterator, or it
293 # implements collections.abc.Generator (and does not implement
294 # collections.abc.Coroutine).
295 return _GeneratorWrapper(coro)
296 # 'coro' is either an instance of collections.abc.Coroutine or
297 # some other object -- pass it through.
298 return coro
299
300 return wrapped
301
302 UnionType = type(int | str)
303
304 EllipsisType = type(Ellipsis)
305 NoneType = type(None)
306 NotImplementedType = type(NotImplemented)
307
308 __all__ = [n for n in globals() if n[:1] != '_']