Top Description Inners Fields Constructors Methods
org.python.core

public Class PyType

extends PyObject
implements Serializable, Traverseproc
Class Inheritance
All Implemented Interfaces
org.python.core.Traverseproc, java.io.Serializable
Known Direct Subclasses
org.python.core.PyTypeDerived, org.python.core.PyJavaType
Annotations
@ExposedType
name:type
doc:type(object) -> the object\'s type type(name, bases, dict) -> a new type
Imports
java.io.Serializable, java.lang.ref.Reference, .ReferenceQueue, .WeakReference, java.util.ArrayList, .Arrays, .HashMap, .HashSet, .IdentityHashMap, .Iterator, .List, .Map, .Set, java.util.concurrent.atomic.AtomicReferenceArray, org.python.antlr.ast.cmpopType, org.python.expose.ExposeAsSuperclass, .ExposedDelete, .ExposedGet, .ExposedMethod, .ExposedNew, .ExposedSet, .ExposedType, .MethodType, .TypeBuilder, org.python.modules._weakref.WeakrefModule, org.python.util.Generic

This class implements the Python type object and the static methods and data structures that support the Python type system in Jython (the type registry).

The class PyType contains static data that describes Python types, that are consulted and modified through its static API (notably fromClass(Class)). The data structures are guarded against modification by concurrent threads (or consultation while being modified). They support construction of type objects that are visible to Python.

Bootstrapping of the type system: The first attempt to construct or get a PyObject (or instance of a subclass of PyObject), to use the Py class utilities, or to call PyType#fromClass(Class), causes the Jython type system to be initialised. By the time that call returns, the type system will be in working order: any PyTypes the application sees will be fully valid. Also, provided that the static initialisation of the PyObject subclass in question is not obstructed for any other reason, the instance returned will also be fully functional. Note that it is possible to refer to C.class, and (if it is not an exposed type) to produce a PyType for it, without causing the static initialisation of C.

This may be no less than the reader expected, but we mention it because, for classes encountered during the bootstrapping of the type system, this guarantee is not offered. The (static) initialisation of the type system is highly reentrant. Classes that are used by the type system itself, and their instances, do encounter defective PyType objects. Instances of these classes, which include mundane classes like PyNone and PyString, may exist before their class is statically initialised in the JVM sense. The type system has been implemented with this fact constantly in mind. The PyType encountered is always the "right" one — the unique instance representing the Python type of that class — but it may not be completely filled in. Debugging that enters these classes during bootstrapping will take surprising turns. Changes to these classes should also take this into account.

Nested and Inner Type Summary

Modifier and TypeClass and Description
protected static class
PyType.Constant

Constants (singletons) for PyTypes that we use repeatedly in the logic of PyType and PyJavaType.

pack-priv static class
PyType.MethodCache

A thread safe, non-blocking version of Armin Rigo's mro cache.

pack-priv static class
PyType.MROMergeState

Tracks the status of merging a single base into a subclass' mro in computeMro.

private static interface
private static class
PyType.Registry

The class PyType contains a registry that describes Python types through a system of indexes and PyType objects.

pack-priv static class

Field Summary

Modifier and TypeField and Description
protected PyType
base

__base__, the direct base type or null.

protected PyObject[]
bases

__bases__, the base classes.

protected boolean
builtin

Whether this is a builtin type.

protected PyObject
dict

The real, internal __dict__.

pack-priv boolean
pack-priv boolean
hasGet

Whether this type implements descriptor __get/set/delete__ methods.

pack-priv boolean
protected boolean
instantiable

Whether new instances of this type can be instantiated

private boolean
isBaseType

Whether this type allows subclassing.

protected PyObject[]
mro

__mro__, the method resolution.

protected String
name

The type's name.

protected boolean
needs_finalizer

Whether finalization is required for this type's instances (implements __del__).

protected boolean
needs_userdict

Whether this type has a __dict__.

protected boolean
needs_weakref

Whether this type has a __weakref__ slot (however all types are weakrefable).

private int
numSlots

The number of __slots__ defined by this type + bases.

private int
ownSlots

The number of __slots__ defined by this type itself.

private Set<WeakReference<PyType>>
private transient ReferenceQueue<PyType>
private long
tp_flags

__flags__, the type's options.

public static final PyType
TYPE

Hides org.python.core.PyObject.TYPE.

The PyType of PyType (or type(type)).
protected Class<?>
underlying_class

The Java Class that instances of this type represent (when that is a PyObject), or null if the type is not a PyObject, in which case the class is indicated through a JyAttribute#JAVA_PROXY_ATTR.

private volatile boolean
usesObjectGetattribute

Whether this type's __getattribute__ is object.__getattribute__.

private volatile Object
versionTag

MethodCacheEntry version tag.

Inherited from org.python.core.PyObject:
attributesgcMonitorGlobalobjtype

Constructor Summary

AccessConstructor and Description
protected
PyType(PyType
Python subclass of this object
subtype
)

Create a "blank" PyType instance, for a Python subclass of type, that is, for a Python metatype.

private
PyType()

Create a "blank" PyType instance.

protected
PyType(boolean
if true, this is a proxy
isProxy
)

Create the PyType instance for type itself, or for a subclass of it.

protected
PyType(PyType subtype, Class<?> c)

As PyType(Class), but also specifying the sub-type of Python type for which it is created.

protected
PyType(Class<?>
the underlying class or null.
c
)

Create a built-in type for the given Java class.

Method Summary

Modifier and TypeMethod and Description
public PyObject
__call__(PyObject[]
all arguments to the function (including keyword arguments).
args
,
String[]
the keywords used for all keyword arguments.
keywords
)

Overrides org.python.core.PyObject.__call__.

The basic method to override when implementing a callable object.

public void
__delattr__(String
the name which will be removed - must be an interned string .
name
)

Overrides org.python.core.PyObject.__delattr__.

A variant of the __delattr__ method which accepts a String as the key.

public PyObject
__findattr_ex__(String name)

Overrides org.python.core.PyObject.__findattr_ex__.

Attribute lookup hook.

protected void
public void
__setattr__(String
the name whose value will be set - must be an interned string .
name
,
PyObject
the value to set this name to
value
)

Overrides org.python.core.PyObject.__setattr__.

A variant of the __setattr__ method which accepts a String as the key.

public Object
__tojava__(Class<?>
the Class to convert this PyObject to.
c
)

Overrides org.python.core.PyObject.__tojava__.

Equivalent to the Jython __tojava__ method.

public static void
addBuilder(Class<?>
class for which this is the builder
c
,
TypeBuilder
to register
builder
)

Register the TypeBuilder for the given class.

public void
addMethod(PyBuiltinMethod meth)

Adds the given method to this type's dict under its name in its descriptor.

private synchronized void
private static PyType
best_base(PyObject[] bases)

Find the base selected from a bases array that has the "most derived solid base".

private void
cacheDescrBinds()

Determine if this type is a descriptor, and if so what kind.

protected void
private static PyObject[]
classic_mro(PyClass classic_cl)

private void
public void
compatibleForAssignment(PyType other, String attribute)

Ensures that the physical layout between this type and other are compatible.

protected void
computeLinearMro(Class<?> baseClass)

Fills the base and bases of this type with the type of baseClass as sets its mro to this type followed by the mro of baseClass.

pack-priv PyObject[]

Returns:

the MRO of this class
computeMro
()

Examine the bases (which must contain no repetition) and the MROs of these bases and return the MRO of this class.

pack-priv PyObject[]

Returns:

the MRO of this class
computeMro
(PyType.MROMergeState[]
data structure representing the (partly processed) MROs of bases.
toMerge
,
List<PyObject>
partial MRO (initially only this class)
mro
)

Core algorithm for computing the MRO for "new-style" (although it's been a while) Python classes.

private static String
private void
createAllSlots(boolean
whether a __dict__ descriptor is allowed on this type
mayAddDict
,
boolean
whether a __weakref__ descriptor is allowed on this type
mayAddWeak
)

Create all slots and related descriptors.

private void
createDictSlot()

Create the __dict__ descriptor.

private void
createWeakrefSlot()

Create the __weakref__ descriptor.

public void
public void
public void
private synchronized void
private void
ensureAttributes()

Setup this type's special attributes.

public static synchronized boolean

Returns:

whether bootstrapping was successful
ensureBootstrapped
()

Attempt to ensure that the that the type system has fully constructed the types necessary to build a fully-working, exposed, PyObject (the "bootstrap types").

public static void
ensureDoc(PyObject
a PyObject mapping
dict
)

Ensure dict contains a __doc__.

public static void
ensureModule(PyObject
a PyObject mapping
dict
)

Ensure dict contains a __module__, retrieving it from the current frame if it doesn't exist.

public PyObject
fastGetDict()

Overrides org.python.core.PyObject.fastGetDict.

Returns the actual dict underlying this type instance.

public String
private static void
private static PyType
findMostDerivedMetatype(PyObject[] bases_list, PyType initialMetatype)

Finds the most derived subtype of initialMetatype in the types of bases, or initialMetatype if it is already the most derived.

private static int

Returns:

position of first ancestor that is not equal to or ancestor of primary base
findSlottedAncestors
(PyType
type to be investigated
tp
,
List<PyType>
list collecting all ancestors
dest
,
Map<PyType, PyObject>
map linking each type to its slots
slotsMap
)

Used internally by createAllSlots().

public static PyType

Returns:

the PyType found or created
fromClass
(Class<?>
for which the corresponding PyType is to be found
c
,
boolean
ignored
hardRef
)

Equivalent to fromClass(Class), which is to be preferred.

public static PyType

Returns:

the PyType found or created
fromClass
(Class<?>
for which the corresponding PyType is to be found
c
)

Look up (create if necessary) the PyType for the given target Java class.

public PyObject
public PyObject
public PyObject
public PyObject
getDict()

Overrides org.python.core.PyObject.getDict.

xxx implements where meaningful

public PyObject
getDoc()

Equivalent of CPython's typeobject.c::type_get_doc; handles __doc__ descriptors.

public PyLong
private static Class<?>

Returns:

base Java proxy Class
getJavaLayout
(PyObject[]
array of base Jython classes
bases
,
List<Class<?>>
List for collecting interfaces to
interfaces
)

Get the most parent Java proxy Class from bases, tallying any encountered Java interfaces.

private PyType
getLayout()

Gets the most parent PyType that determines the layout of this type, ie it has slots or an underlying_class.

public PyObject
public PyTuple
public String
public int
pack-priv static Object
getProxyAttr(PyObject obj)

Brevity for JyAttribute.getAttr(obj, JyAttribute.JAVA_PROXY_ATTR).

public Class<?>
getProxyType()

Returns the Java Class that this type inherits from, or null if this type is Python-only.

public PyObject
pack-priv boolean
pack-priv void
handleMroError(PyType.MROMergeState[]
partially processed algorithm state
toMerge
,
List<PyObject>
output MRO (incomplete)
mro
)

This method is called when the computeMro(MROMergeState[], List) reaches an impasse as far as its official algorithm is concerned, with the partial MRO and current state of the working lists at the point the problem is detected.

pack-priv static boolean
hasProxyAttr(PyObject obj)

Brevity for JyAttribute.hasAttr(obj, JyAttribute.JAVA_PROXY_ATTR).

private void
inheritSpecial()

Inherit special attributes from the dominant base.

protected void
init(Set<PyJavaType>
ignored in the base implementation (see PyJavaType#init(Set)
needsInners
)

Complete the initialisation of the PyType for an exposed PyObject.

private static void
insertSlots(PyObject
names to be added as slots
slots
,
Set<String>
set collecting all slots
dest
)

Used internally by createAllSlots().

public PyObject
protected void
invalidateMethodCache()

Invalidate this type's MethodCache entries.

private static PyObject
invokeNew(PyObject new_, PyType type, boolean init, PyObject[] args, String[] keywords)

pack-priv boolean
private static boolean
private static boolean
isSolidBase(PyType type)

A "solid base" is a type that has an underlying_class, or defines __slots__ and no instance level dictionary (no __dict__ attribute).

public boolean
isSubType(PyType supertype)

public PyObject

Returns:

found object or null
lookup
(String
attribute name (must be interned)
name
)

Attribute lookup for name through mro objects' dicts.

protected PyObject

Returns:

found object or null
lookup_mro
(String
attribute name (must be interned)
name
)

Attribute lookup for name directly through mro objects' dicts.

public PyObject

Returns:

found object or null
lookup_where
(String
attribute name (must be interned)
name
,
PyObject[]
Where in the mro the attribute was found is written to index 0
where
)

Attribute lookup for name through mro objects' dicts.

protected PyObject

Returns:

found object or null
lookup_where_mro
(String
attribute name (must be interned)
name
,
PyObject[]
Where in the mro the attribute was found is written to index 0
where
)

Attribute lookup for name through mro objects' dicts.

private static String
mangleName(String classname, String methodname)

private void
mro_internal()

Set the mro field from the Python mro() method which uses (computeMro() by default.

private void
mro_subclasses(List<Object> mroCollector)

Collects the subclasses and current mro of this type in mroCollector.

public final boolean

Returns:

a boolean indicating whether the type implements __del__
needsFinalizer
()

Offers public read-only access to the protected field needs_finalizer.

public static PyObject
newType(PyNewWrapper new_, PyType metatype, String name, PyTuple bases, PyObject dict)

public void
noAttributeError(String name)

Overrides org.python.core.PyObject.noAttributeError.

Raises AttributeError on type objects.

pack-priv void
pack-priv void
public void
public PyObject
public void
public boolean
public void
removeMethod(PyBuiltinMethod meth)

Removes the given method from this type's dict or raises a KeyError.

protected PyObject
public void
public void
setBases(PyObject newBasesTuple)

public void
private void
setIsBaseType(boolean isBaseType)

public void
pack-priv static void
setProxyAttr(PyObject obj, Object value)

Brevity for JyAttribute.setAttr(obj, JyAttribute.JAVA_PROXY_ATTR, value).

private void
setupProxy(Class<?>
this type's base proxyClass
baseProxyClass
,
List<Class<?>>
a list of Java interfaces in bases
interfaces
)

Setup the javaProxy for this type.

pack-priv void
setUsesObjectGetattribute(boolean usesObjectGetattribute)

private static PyType
solid_base(PyType type)

Finds the first super-type of the given type that is a "solid base" of the type, that is, the returned type has an underlying_class, or it defines __slots__ and no instance level dictionary (__dict__ attribute).

public PyObject
public String
toString()

Overrides org.python.core.PyObject.toString.

Returns a string representation of the object.

public int
traverse(Visitproc visit, Object arg)

Implements org.python.core.Traverseproc.traverse.

Traverses all directly contained PyObjects.

private synchronized void
traverse_hierarchy(boolean top, PyType.OnType behavior)

pack-priv final PyObject
type___call__(PyObject[] args, String[] keywords)

pack-priv final void
pack-priv void
public PyObject
pack-priv final PyObject
public PyObject
pack-priv final PyObject
public PyObject
pack-priv final void
type___init__(PyObject[] args, String[] kwds)

public final synchronized boolean
public PyObject
public PyObject
public PyObject
pack-priv static final PyObject
type___new__(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords)

pack-priv final void
pack-priv void
public final synchronized boolean
public final synchronized PyObject
pack-priv final PyList
pack-priv final String
protected boolean
useMetatypeFirst(PyObject attr)

Returns true if the given attribute retrieved from an object's metatype should be used before looking for the object on the actual object.

protected Object
writeReplace()

Used when serializing this type.

Inherited from org.python.core.PyObject:
__abs____add____and____call____call____call____call____call____call____call____call____call____call____call____call____call____call____call____cmp____coerce____coerce_ex____complex____contains____delattr____delete____delitem____delitem____delslice____delslice____dir____div____divmod____ensure_finalizer____eq____findattr____findattr____finditem____finditem____finditem____float____floordiv____format____ge____get____getattr____getattr____getitem____getitem____getnewargs____getslice____getslice____gt____hash____hex____iadd____iand____idiv____idivmod____ifloordiv____ilshift____imod____imul____index____int____invert____ior____ipow____irshift____isub____iter____iternext____itruediv____ixor____le____len____long____lshift____lt____mod____mul____ne____neg____nonzero____not____oct____or____pos____pow____pow____radd____rand____rdiv____rdivmod____reduce____reduce_ex____reduce_ex____repr____rfloordiv____rlshift____rmod____rmul____ror____rpow____rrshift____rshift____rsub____rtruediv____rxor____set____setattr____setitem____setitem____setitem____setslice____setslice____str____sub____truediv____trunc____unicode____xor___add_and_basic_add_basic_and_basic_div_basic_divmod_basic_floordiv_basic_iadd_basic_iand_basic_idiv_basic_idivmod_basic_ifloordiv_basic_ilshift_basic_imod_basic_imul_basic_ior_basic_ipow_basic_irshift_basic_isub_basic_itruediv_basic_ixor_basic_lshift_basic_mod_basic_mul_basic_or_basic_pow_basic_rshift_basic_sub_basic_truediv_basic_xor_callextra_cmp_coerce_div_divmod_doget_doget_doset_eq_floordiv_ge_gt_iadd_iand_idiv_idivmod_ifloordiv_ilshift_imod_imul_in_ior_ipow_irshift_is_isnot_isub_itruediv_ixor_jcall_jcallexc_jthrow_le_lshift_lt_mod_mul_ne_notin_or_pow_rshift_sub_truediv_unsupportedop_xoradaptToCoerceTupleasDoubleasIndexasIndexasIntasIntasIterableasLongasLongasNameasNameasStringasStringasStringOrNullasStringOrNullbit_lengthconjugatedelTypedispatch__init__equalsfastGetClassfinalizegetJavaProxygetTypehashCodeimpAttrimplementsDescrDeleteimplementsDescrGetimplementsDescrSetinvokeinvokeinvokeinvokeinvokeinvokeisCallableisDataDescrisIndexisIntegerisMappingTypeisNumberTypeisSequenceTypejdontdelmergeClassDictmergeDictAttrmergeListAttrobject___contains__object___delattr__object___delattr__object___findattr__object___format__object___getattribute__object___hash__object___init__object___new__object___reduce__object___reduce_ex__object___setattr__object___setattr__object___subclasshook__object_toStringproxyInitreadonlyAttributeErrorrunsupportedopMessagesetTypeunsupportedopMessage