ยปCore Development>Code coverage>Lib/types.py

Python code coverage for Lib/types.py

#countcontent
1n/a"""
2n/aDefine names for built-in types that aren't directly accessible as a builtin.
3n/a"""
4n/aimport sys
5n/a
6n/a# Iterators in Python aren't a matter of type but of protocol. A large
7n/a# and changing number of builtin types implement *some* flavor of
8n/a# iterator. Don't check the type! Use hasattr to check for both
9n/a# "__iter__" and "__next__" attributes instead.
10n/a
11n/adef _f(): pass
12n/aFunctionType = type(_f)
13n/aLambdaType = type(lambda: None) # Same as FunctionType
14n/aCodeType = type(_f.__code__)
15n/aMappingProxyType = type(type.__dict__)
16n/aSimpleNamespace = type(sys.implementation)
17n/a
18n/adef _g():
19n/a yield 1
20n/aGeneratorType = type(_g())
21n/a
22n/aasync def _c(): pass
23n/a_c = _c()
24n/aCoroutineType = type(_c)
25n/a_c.close() # Prevent ResourceWarning
26n/a
27n/aasync def _ag():
28n/a yield
29n/a_ag = _ag()
30n/aAsyncGeneratorType = type(_ag)
31n/a
32n/aclass _C:
33n/a def _m(self): pass
34n/aMethodType = type(_C()._m)
35n/a
36n/aBuiltinFunctionType = type(len)
37n/aBuiltinMethodType = type([].append) # Same as BuiltinFunctionType
38n/a
39n/aSlotWrapperType = type(object.__init__)
40n/aMethodWrapperType = type(object().__str__)
41n/aMethodDescriptorType = type(str.join)
42n/a
43n/aModuleType = type(sys)
44n/a
45n/atry:
46n/a raise TypeError
47n/aexcept TypeError:
48n/a tb = sys.exc_info()[2]
49n/a TracebackType = type(tb)
50n/a FrameType = type(tb.tb_frame)
51n/a tb = None; del tb
52n/a
53n/a# For Jython, the following two types are identical
54n/aGetSetDescriptorType = type(FunctionType.__code__)
55n/aMemberDescriptorType = type(FunctionType.__globals__)
56n/a
57n/adel sys, _f, _g, _C, _c, # Not for export
58n/a
59n/a
60n/a# Provide a PEP 3115 compliant mechanism for class creation
61n/adef new_class(name, bases=(), kwds=None, exec_body=None):
62n/a """Create a class object dynamically using the appropriate metaclass."""
63n/a meta, ns, kwds = prepare_class(name, bases, kwds)
64n/a if exec_body is not None:
65n/a exec_body(ns)
66n/a return meta(name, bases, ns, **kwds)
67n/a
68n/adef prepare_class(name, bases=(), kwds=None):
69n/a """Call the __prepare__ method of the appropriate metaclass.
70n/a
71n/a Returns (metaclass, namespace, kwds) as a 3-tuple
72n/a
73n/a *metaclass* is the appropriate metaclass
74n/a *namespace* is the prepared class namespace
75n/a *kwds* is an updated copy of the passed in kwds argument with any
76n/a 'metaclass' entry removed. If no kwds argument is passed in, this will
77n/a be an empty dict.
78n/a """
79n/a if kwds is None:
80n/a kwds = {}
81n/a else:
82n/a kwds = dict(kwds) # Don't alter the provided mapping
83n/a if 'metaclass' in kwds:
84n/a meta = kwds.pop('metaclass')
85n/a else:
86n/a if bases:
87n/a meta = type(bases[0])
88n/a else:
89n/a meta = type
90n/a if isinstance(meta, type):
91n/a # when meta is a type, we first determine the most-derived metaclass
92n/a # instead of invoking the initial candidate directly
93n/a meta = _calculate_meta(meta, bases)
94n/a if hasattr(meta, '__prepare__'):
95n/a ns = meta.__prepare__(name, bases, **kwds)
96n/a else:
97n/a ns = {}
98n/a return meta, ns, kwds
99n/a
100n/adef _calculate_meta(meta, bases):
101n/a """Calculate the most derived metaclass."""
102n/a winner = meta
103n/a for base in bases:
104n/a base_meta = type(base)
105n/a if issubclass(winner, base_meta):
106n/a continue
107n/a if issubclass(base_meta, winner):
108n/a winner = base_meta
109n/a continue
110n/a # else:
111n/a raise TypeError("metaclass conflict: "
112n/a "the metaclass of a derived class "
113n/a "must be a (non-strict) subclass "
114n/a "of the metaclasses of all its bases")
115n/a return winner
116n/a
117n/aclass DynamicClassAttribute:
118n/a """Route attribute access on a class to __getattr__.
119n/a
120n/a This is a descriptor, used to define attributes that act differently when
121n/a accessed through an instance and through a class. Instance access remains
122n/a normal, but access to an attribute through a class will be routed to the
123n/a class's __getattr__ method; this is done by raising AttributeError.
124n/a
125n/a This allows one to have properties active on an instance, and have virtual
126n/a attributes on the class with the same name (see Enum for an example).
127n/a
128n/a """
129n/a def __init__(self, fget=None, fset=None, fdel=None, doc=None):
130n/a self.fget = fget
131n/a self.fset = fset
132n/a self.fdel = fdel
133n/a # next two lines make DynamicClassAttribute act the same as property
134n/a self.__doc__ = doc or fget.__doc__
135n/a self.overwrite_doc = doc is None
136n/a # support for abstract methods
137n/a self.__isabstractmethod__ = bool(getattr(fget, '__isabstractmethod__', False))
138n/a
139n/a def __get__(self, instance, ownerclass=None):
140n/a if instance is None:
141n/a if self.__isabstractmethod__:
142n/a return self
143n/a raise AttributeError()
144n/a elif self.fget is None:
145n/a raise AttributeError("unreadable attribute")
146n/a return self.fget(instance)
147n/a
148n/a def __set__(self, instance, value):
149n/a if self.fset is None:
150n/a raise AttributeError("can't set attribute")
151n/a self.fset(instance, value)
152n/a
153n/a def __delete__(self, instance):
154n/a if self.fdel is None:
155n/a raise AttributeError("can't delete attribute")
156n/a self.fdel(instance)
157n/a
158n/a def getter(self, fget):
159n/a fdoc = fget.__doc__ if self.overwrite_doc else None
160n/a result = type(self)(fget, self.fset, self.fdel, fdoc or self.__doc__)
161n/a result.overwrite_doc = self.overwrite_doc
162n/a return result
163n/a
164n/a def setter(self, fset):
165n/a result = type(self)(self.fget, fset, self.fdel, self.__doc__)
166n/a result.overwrite_doc = self.overwrite_doc
167n/a return result
168n/a
169n/a def deleter(self, fdel):
170n/a result = type(self)(self.fget, self.fset, fdel, self.__doc__)
171n/a result.overwrite_doc = self.overwrite_doc
172n/a return result
173n/a
174n/a
175n/aimport functools as _functools
176n/aimport collections.abc as _collections_abc
177n/a
178n/aclass _GeneratorWrapper:
179n/a # TODO: Implement this in C.
180n/a def __init__(self, gen):
181n/a self.__wrapped = gen
182n/a self.__isgen = gen.__class__ is GeneratorType
183n/a self.__name__ = getattr(gen, '__name__', None)
184n/a self.__qualname__ = getattr(gen, '__qualname__', None)
185n/a def send(self, val):
186n/a return self.__wrapped.send(val)
187n/a def throw(self, tp, *rest):
188n/a return self.__wrapped.throw(tp, *rest)
189n/a def close(self):
190n/a return self.__wrapped.close()
191n/a @property
192n/a def gi_code(self):
193n/a return self.__wrapped.gi_code
194n/a @property
195n/a def gi_frame(self):
196n/a return self.__wrapped.gi_frame
197n/a @property
198n/a def gi_running(self):
199n/a return self.__wrapped.gi_running
200n/a @property
201n/a def gi_yieldfrom(self):
202n/a return self.__wrapped.gi_yieldfrom
203n/a cr_code = gi_code
204n/a cr_frame = gi_frame
205n/a cr_running = gi_running
206n/a cr_await = gi_yieldfrom
207n/a def __next__(self):
208n/a return next(self.__wrapped)
209n/a def __iter__(self):
210n/a if self.__isgen:
211n/a return self.__wrapped
212n/a return self
213n/a __await__ = __iter__
214n/a
215n/adef coroutine(func):
216n/a """Convert regular generator function to a coroutine."""
217n/a
218n/a if not callable(func):
219n/a raise TypeError('types.coroutine() expects a callable')
220n/a
221n/a if (func.__class__ is FunctionType and
222n/a getattr(func, '__code__', None).__class__ is CodeType):
223n/a
224n/a co_flags = func.__code__.co_flags
225n/a
226n/a # Check if 'func' is a coroutine function.
227n/a # (0x180 == CO_COROUTINE | CO_ITERABLE_COROUTINE)
228n/a if co_flags & 0x180:
229n/a return func
230n/a
231n/a # Check if 'func' is a generator function.
232n/a # (0x20 == CO_GENERATOR)
233n/a if co_flags & 0x20:
234n/a # TODO: Implement this in C.
235n/a co = func.__code__
236n/a func.__code__ = CodeType(
237n/a co.co_argcount, co.co_kwonlyargcount, co.co_nlocals,
238n/a co.co_stacksize,
239n/a co.co_flags | 0x100, # 0x100 == CO_ITERABLE_COROUTINE
240n/a co.co_code,
241n/a co.co_consts, co.co_names, co.co_varnames, co.co_filename,
242n/a co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars,
243n/a co.co_cellvars)
244n/a return func
245n/a
246n/a # The following code is primarily to support functions that
247n/a # return generator-like objects (for instance generators
248n/a # compiled with Cython).
249n/a
250n/a @_functools.wraps(func)
251n/a def wrapped(*args, **kwargs):
252n/a coro = func(*args, **kwargs)
253n/a if (coro.__class__ is CoroutineType or
254n/a coro.__class__ is GeneratorType and coro.gi_code.co_flags & 0x100):
255n/a # 'coro' is a native coroutine object or an iterable coroutine
256n/a return coro
257n/a if (isinstance(coro, _collections_abc.Generator) and
258n/a not isinstance(coro, _collections_abc.Coroutine)):
259n/a # 'coro' is either a pure Python generator iterator, or it
260n/a # implements collections.abc.Generator (and does not implement
261n/a # collections.abc.Coroutine).
262n/a return _GeneratorWrapper(coro)
263n/a # 'coro' is either an instance of collections.abc.Coroutine or
264n/a # some other object -- pass it through.
265n/a return coro
266n/a
267n/a return wrapped
268n/a
269n/a
270n/a__all__ = [n for n in globals() if n[:1] != '_']