types --- 動的な型生成と組み込み型に対する名前

ソースコード: Lib/types.py


このモジュールは新しい型の動的な生成を支援するユーティリティ関数を定義します。

さらに、標準の Python インタプリタによって使用されているものの、 intstr のように組み込みとして公開されていないようないくつかのオブジェクト型の名前を定義しています。

最後に、組み込みになるほど基本的でないような追加の型関連のユーティリティと関数をいくつか提供しています。

動的な型生成

types.new_class(name, bases=(), kwds=None, exec_body=None)

適切なメタクラスを使用して動的にクラスオブジェクトを生成します。

最初の3つの引数はクラス定義ヘッダーを構成する—クラス名、基底クラス (順番に)、キーワード引数 (例えば metaclass)—です。

exec_body 引数は、新規に生成されたクラスの名前空間を構築するために使用されるコールバックです。それは唯一の引数としてクラスの名前空間を受け取り、クラスの内容で名前空間を直接更新します。コールバックが渡されない場合、それは lambda ns: None を渡すことと同じ効果があります。

バージョン 3.3 で追加.

types.prepare_class(name, bases=(), kwds=None)

適切なメタクラスを計算してクラスの名前空間を生成します。

引数はクラス定義ヘッダーを構成する要素—クラス名、基底クラス (順番に)、キーワード引数 (例えば metaclass)—です。

返り値は metaclass, namespace, kwds の3要素のタプルです

metaclass は適切なメタクラスです。namespace は用意されたクラスの名前空間です。また kwds は、'metaclass' エントリが削除された、渡された kwds 引数の更新されたコピーです。kwds 引数が渡されなければ、これは空の dict になります。

バージョン 3.3 で追加.

バージョン 3.6 で変更: 返されるタプルの namespace 要素のデフォルト値が変更されました。 現在では、メタクラスが __prepare__ メソッドを持っていないときは、挿入順序を保存するマッピングが使われます。

参考

メタクラス

これらの関数によってサポートされるクラス生成プロセスの完全な詳細

PEP 3115 - Metaclasses in Python 3000

__prepare__ 名前空間フックの導入

types.resolve_bases(bases)

Resolve MRO entries dynamically as specified by PEP 560.

This function looks for items in bases that are not instances of type, and returns a tuple where each such object that has an __mro_entries__() method is replaced with an unpacked result of calling this method. If a bases item is an instance of type, or it doesn't have an __mro_entries__() method, then it is included in the return tuple unchanged.

バージョン 3.7 で追加.

types.get_original_bases(cls, /)

Return the tuple of objects originally given as the bases of cls before the __mro_entries__() method has been called on any bases (following the mechanisms laid out in PEP 560). This is useful for introspecting Generics.

For classes that have an __orig_bases__ attribute, this function returns the value of cls.__orig_bases__. For classes without the __orig_bases__ attribute, cls.__bases__ is returned.

例:

from typing import TypeVar, Generic, NamedTuple, TypedDict

T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", {"a": int, "b": str})

assert Bar.__bases__ == (Foo, float)
assert get_original_bases(Bar) == (Foo[int], float)

assert Baz.__bases__ == (list,)
assert get_original_bases(Baz) == (list[str],)

assert Eggs.__bases__ == (tuple,)
assert get_original_bases(Eggs) == (NamedTuple,)

assert Spam.__bases__ == (dict,)
assert get_original_bases(Spam) == (TypedDict,)

assert int.__bases__ == (object,)
assert get_original_bases(int) == (object,)

バージョン 3.12 で追加.

参考

PEP 560 - typing モジュールとジェネリック型に対する言語コアによるサポート

標準的なインタプリタ型

このモジュールは、Python インタプリタを実装するために必要な多くの型に対して名前を提供します。それは、listiterator 型のような、単に処理中に付随的に発生するいくつかの型が含まれることを意図的に避けています。

これらの名前は典型的に isinstance()issubclass() によるチェックに使われます。

これらのタイプのいずれかをインスタンス化する場合、シグネチャは Python のバージョンによって異なる可能性があることに注意してください。

以下の型に対して標準的な名前が定義されています:

types.NoneType

None の型です。

バージョン 3.10 で追加.

types.FunctionType
types.LambdaType

ユーザ定義の関数と lambda 式によって生成された関数の型です。

引数 code を指定して 監査イベント function.__new__ を送出します。

この監査イベントは、関数オブジェクトを直接インスタンス化した場合にのみ発生し、通常のコンパイル時には発生しません。

types.GeneratorType

ジェネレータ関数によって生成された ジェネレータ イテレータオブジェクトの型です。

types.CoroutineType

async def 関数に生成される コルーチン オブジェクトです。

バージョン 3.5 で追加.

types.AsyncGeneratorType

非同期ジェネレータ関数によって作成された 非同期ジェネレータ イテレータオブジェクトの型です。

バージョン 3.6 で追加.

class types.CodeType(**kwargs)

The type of code objects such as returned by compile().

引数 code, filename, name, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags を指定して 監査イベント code.__new__ を送出します。

Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.

types.CellType

The type for cell objects: such objects are used as containers for a function's free variables.

バージョン 3.8 で追加.

types.MethodType

ユーザー定義のクラスのインスタンスのメソッドの型です。

types.BuiltinFunctionType
types.BuiltinMethodType

len()sys.exit() のような組み込み関数や、組み込み型のメソッドの型です。 (ここでは "組み込み" という単語を "Cで書かれた" という意味で使っています)

types.WrapperDescriptorType

The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__().

バージョン 3.7 で追加.

types.MethodWrapperType

The type of bound methods of some built-in data types and base classes. For example it is the type of object().__str__.

バージョン 3.7 で追加.

types.NotImplementedType

NotImplemented の型です。

バージョン 3.10 で追加.

types.MethodDescriptorType

The type of methods of some built-in data types such as str.join().

バージョン 3.7 で追加.

types.ClassMethodDescriptorType

The type of unbound class methods of some built-in data types such as dict.__dict__['fromkeys'].

バージョン 3.7 で追加.

class types.ModuleType(name, doc=None)

module の型です。コンストラクタは生成するモジュールの名前と任意でその docstring を受け取ります。

注釈

インポートによりコントロールされる様々な属性を設定する場合、importlib.util.module_from_spec() を使用して新しいモジュールを作成してください。

__doc__

モジュールの docstring です。デフォルトは None です。

__loader__

モジュールをロードする loader です。デフォルトは None です。

This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the __spec__ object.

注釈

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the __spec__ attribute instead or use getattr(module, "__loader__", None) if you explicitly need to use this attribute.

バージョン 3.4 で変更: デフォルトが None になりました。以前はオプションでした。

__name__

The name of the module. Expected to match importlib.machinery.ModuleSpec.name.

__package__

モジュールがどの package に属しているかです。モジュールがトップレベルである (すなわち、いかなる特定のパッケージの一部でもない) 場合、この属性は '' に設定されます。そうでない場合、パッケージ名 (モジュールがパッケージ自身なら __name__) に設定されます。デフォルトは None です。

This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the __spec__ object.

注釈

A future version of Python may stop setting this attribute by default. To guard against this potential change, preferably read from the __spec__ attribute instead or use getattr(module, "__package__", None) if you explicitly need to use this attribute.

バージョン 3.4 で変更: デフォルトが None になりました。以前はオプションでした。

__spec__

A record of the module's import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec.

バージョン 3.4 で追加.

types.EllipsisType

Ellipsis の型です。

バージョン 3.10 で追加.

class types.GenericAlias(t_origin, t_args)

The type of parameterized generics such as list[int].

t_origin should be a non-parameterized generic class, such as list, tuple or dict. t_args should be a tuple (possibly of length 1) of types which parameterize t_origin:

>>> from types import GenericAlias

>>> list[int] == GenericAlias(list, (int,))
True
>>> dict[str, int] == GenericAlias(dict, (str, int))
True

バージョン 3.9 で追加.

バージョン 3.9.2 で変更: This type can now be subclassed.

参考

Generic Alias Types

In-depth documentation on instances of types.GenericAlias

PEP 585 - 標準コレクション型の型ヒントにおける総称型 (generics) の使用

Introducing the types.GenericAlias class

class types.UnionType

The type of union type expressions.

バージョン 3.10 で追加.

class types.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

sys.exception().__traceback__ に含まれるようなトレースバックオブジェクトの型です。

See the language reference for details of the available attributes and operations, and guidance on creating tracebacks dynamically.

types.FrameType

The type of frame objects such as found in tb.tb_frame if tb is a traceback object.

types.GetSetDescriptorType

The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.

types.MemberDescriptorType

datetime.timedelta.days のような、拡張モジュールにおいて PyMemberDef によって定義されたオブジェクトの型です。この型は、標準の変換関数を利用するような、Cのシンプルなデータメンバで利用されます。 property 型と同じ目的を持った型ですが、こちらは拡張モジュールで定義された型のためのものです。

In addition, when a class is defined with a __slots__ attribute, then for each slot, an instance of MemberDescriptorType will be added as an attribute on the class. This allows the slot to appear in the class's __dict__.

CPython 実装の詳細: Pythonの他の実装では、この型は GetSetDescriptorType と同じかもしれません。

class types.MappingProxyType(mapping)

読み出し専用のマッピングのプロキシです。マッピングのエントリーに関する動的なビューを提供します。つまり、マッピングが変わった場合にビューがこれらの変更を反映するということです。

バージョン 3.3 で追加.

バージョン 3.9 で変更: Updated to support the new union (|) operator from PEP 584, which simply delegates to the underlying mapping.

key in proxy

元になったマッピングが key というキーを持っている場合 True を返します。そうでなければ False を返します。

proxy[key]

元になったマッピングの key というキーに対応するアイテムを返します。 key が存在しなければ、 KeyError が発生します。

iter(proxy)

元になったマッピングのキーを列挙するイテレータを返します。これは iter(proxy.keys()) のショートカットです。

len(proxy)

元になったマッピングに含まれるアイテムの数を返します。

copy()

元になったマッピングの浅いコピーを返します。

get(key[, default])

key が元になったマッピングに含まれている場合 key に対する値を返し、そうでなければ default を返します。もし default が与えられない場合は、デフォルト値の None になります。そのため、このメソッドが KeyError を発生させることはありません。

items()

元になったマッピングの items ((key, value) ペアの列) に対する新しいビューを返します。

keys()

元になったマッピングの keys に対する新しいビューを返します。

values()

元になったマッピングの values に対する新しいビューを返します。

reversed(proxy)

Return a reverse iterator over the keys of the underlying mapping.

バージョン 3.9 で追加.

hash(proxy)

Return a hash of the underlying mapping.

バージョン 3.12 で追加.

追加のユーティリティクラスと関数

class types.SimpleNamespace

名前空間への属性アクセスに加えて意味のある repr を提供するための、単純な object サブクラスです。

object とは異なり、 SimpleNamespace は、属性を追加したり削除したりすることができます。 SimpleNamespace オブジェクトがキーワード引数で初期化される場合、それらは元になる名前空間に直接追加されます。

この型は以下のコードとほぼ等価です:

class SimpleNamespace:
    def __init__(self, /, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        items = (f"{k}={v!r}" for k, v in self.__dict__.items())
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
           return self.__dict__ == other.__dict__
        return NotImplemented

SimpleNamespaceclass NS: pass を置き換えるものとして有用かもしれません。ですが、構造化されたレコード型に対しては、これよりはむしろ namedtuple() を使用してください。

バージョン 3.3 で追加.

バージョン 3.9 で変更: Attribute order in the repr changed from alphabetical to insertion (like dict).

types.DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

クラスの属性アクセスを __getattr__ に振り替えます。

これは記述子で、インスタンス経由のアクセスとクラス経由のアクセスで振る舞いが異なる属性を定義するのに使います。インスタンスアクセスは通常通りですが、クラス経由の属性アクセスはクラスの __getattr__ メソッドに振り替えられます。これは AttributeError の送出により行われます。

これによって、インスタンス上で有効なプロパティを持ち、クラス上で同名の仮想属性を持つことができます (例については enum.Enum を参照してください)。

バージョン 3.4 で追加.

コルーチンユーティリティ関数

types.coroutine(gen_func)

この関数は、 generator 関数を、ジェネレータベースのコルーチンを返す coroutine function に変換します。返されるジェネレータベースのコルーチンは依然として generator iterator ですが、同時に coroutine オブジェクトかつ awaitable であるとみなされます。ただし、必ずしも __await__() メソッドを実装する必要はありません。

gen_func はジェネレータ関数で、インプレースに変更されます。

gen_func がジェネレータ関数でない場合、この関数はラップされます。この関数が collections.abc.Generator のインスタンスを返す場合、このインスタンスは awaitable なプロキシオブジェクトにラップされます。それ以外のすべての型のオブジェクトは、そのまま返されます。

バージョン 3.5 で追加.