Python.Runtime Specifies that null is allowed as an input even if the corresponding type disallows it. Specifies that null is disallowed as an input even if the corresponding type allows it. Specifies that an output may be null even if the corresponding type disallows it. Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. Initializes the attribute with the specified return value condition. The return value condition. If the method returns this value, the associated parameter may be null. Gets the return value condition. Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns. Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. Initializes the attribute with the specified return value condition. The return value condition. If the method returns this value, the associated parameter will not be null. Gets the return value condition. Specifies that the output will be non-null if the named parameter is non-null. Initializes the attribute with the associated parameter name. The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. Gets the associated parameter name. Specifies that the method or property will ensure that the listed field and property members have not-null values. Initializes the attribute with a field or property member. The field or property member that is promised to be not-null. Initializes the attribute with the list of field and property members. The list of field and property members that are promised to be not-null. Gets field or property member names. Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition. Initializes the attribute with the specified return value condition and a field or property member. The return value condition. If the method returns this value, the associated parameter will not be null. The field or property member that is promised to be not-null. Initializes the attribute with the specified return value condition and list of field and property members. The return value condition. If the method returns this value, the associated parameter will not be null. The list of field and property members that are promised to be not-null. Gets the return value condition. Gets field or property member names. The AssemblyManager maintains information about loaded assemblies namespaces and provides an interface for name-based type lookup. Initialization performed on startup of the Python runtime. Here we scan all of the currently loaded assemblies to determine exported names, and register to be notified of new assembly loads. Cleanup resources upon shutdown of the Python runtime. Event handler for assembly load events. At the time the Python runtime loads, we scan the app domain to map the assemblies that are loaded at the time. We also have to register this event handler so that we can know about assemblies that get loaded after the Python runtime is initialized. Event handler for assembly resolve events. This is needed because we augment the assembly search path with the PYTHONPATH when we load an assembly from Python. Because of that, we need to listen for failed loads, because they might be dependencies of something we loaded from Python which also needs to be found on PYTHONPATH. We __really__ want to avoid using Python objects or APIs when probing for assemblies to load, since our ResolveHandler may be called in contexts where we don't have the Python GIL and can't even safely try to get it without risking a deadlock ;( To work around that, we update a managed copy of sys.path (which is the main thing we care about) when UpdatePath is called. The import hook calls this whenever it knows its about to use the assembly manager, which lets us keep up with changes to sys.path in a relatively lightweight and low-overhead way. Given an assembly name, try to find this assembly file using the PYTHONPATH. If not found, return null to indicate implicit load using standard load semantics (app base directory then GAC, etc.) Given an assembly name, try to find this assembly file using the PYTHONPATH. If not found, return null to indicate implicit load using standard load semantics (app base directory then GAC, etc.) Loads an assembly from the application directory or the GAC given its name. Returns the assembly if loaded. Loads an assembly using an augmented search path (the python path). Loads an assembly using full path. Returns an assembly that's already been loaded Scans an assembly for exported namespaces, adding them to the mapping of valid namespaces. Note that for a given namespace a.b.c.d, each of a, a.b, a.b.c and a.b.c.d are considered to be valid namespaces (to better match Python import semantics). Returns true if the given qualified name matches a namespace exported by an assembly loaded in the current app domain. Returns an enumerable collection containing the namepsaces exported by loaded assemblies in the current app domain. Returns list of assemblies that declare types in a given namespace Returns the current list of valid names for the input namespace. Returns the objects for the given qualified name, looking in the currently loaded assemblies for the named type. The ClassManager is responsible for creating and managing instances that implement the Python type objects that reflect managed classes. Each managed type reflected to Python is represented by an instance of a concrete subclass of ClassBase. Each instance is associated with a generated Python type object, whose slots point to static methods of the managed instance's class. Return the ClassBase-derived instance that implements a particular reflected managed type, creating it if it doesn't yet exist. Create a new ClassBase-derived instance that implements a reflected managed type. The new object will be associated with a generated Python type object. This class owns references to PyObjects in the `members` member. The caller has responsibility to DECREF them. Represents a group of s. Useful to group them by priority. Add specified decoder to the group Remove all decoders from the group Gets a concrete instance of (potentially selecting one from a collection), that can decode from to , or null if a matching decoder can not be found. Represents a group of s. Useful to group them by priority. Add specified encoder to the group Remove all encoders from the group Gets specific instances of (potentially selecting one from a collection), that can encode the specified . A .NET object encoder, that returns raw proxies (e.g. no conversion to Python types). You must inherit from this class and override . Defines conversion to CLR types (unmarshalling) Checks if this decoder can decode from to Attempts do decode into a variable of specified type CLR type to decode into Object to decode The variable, that will receive decoding result Defines conversion from CLR objects into Python objects (e.g. ) (marshalling) Checks if encoder can encode CLR objects of specified type Attempts to encode CLR object into Python object This class allows to register additional marshalling codecs. Python.NET will pick suitable encoder/decoder registered first Registers specified encoder (marshaller) Python.NET will pick suitable encoder/decoder registered first Registers specified decoder (unmarshaller) Python.NET will pick suitable encoder/decoder registered first Performs data conversions between managed types and Python types. Given a builtin Python type, return the corresponding CLR type. In a few situations, we don't have any advisory type information when we want to convert an object to Python. Return a managed object for the given Python object, taking funny byref types into account. A Python object The desired managed type Receives the managed object If true, call Exceptions.SetError with the reason for failure. True on success Unlike , this method does not have a setError parameter, because it should only be called after . Convert a Python value to an instance of a primitive managed type. Convert a Python value to a correctly typed managed array instance. The Python value must support the Python iterator protocol or and the items in the sequence must be convertible to the target array type. Minimal Python base type provider The DelegateManager class manages the creation of true managed delegate instances that dispatch calls to Python methods. GetDispatcher is responsible for creating a class that provides an appropriate managed callback method for a given delegate type. Given a delegate type and a callable Python object, GetDelegate returns an instance of the delegate type. The delegate instance returned will dispatch calls to the given Python object. Encapsulates the Python exception APIs. Readability of the Exceptions class improvements as we look toward version 2.7 ... Initialization performed on startup of the Python runtime. Cleanup resources upon shutdown of the Python runtime. Set the 'args' slot on a python exception object that wraps a CLR exception. This is needed for pickling CLR exceptions as BaseException_reduce will only check the slots, bypassing the __getattr__ implementation, and thus dereferencing a NULL pointer. Shortcut for (pointer == NULL) -> throw PythonException Pointer to a Python object Shortcut for (pointer == NULL or ErrorOccurred()) -> throw PythonException ExceptionMatches Method Returns true if the current Python exception matches the given Python object. This is a wrapper for PyErr_ExceptionMatches. Sets the current Python exception given a native string. This is a wrapper for the Python PyErr_SetString call. SetError Method Sets the current Python exception given a Python object. This is a wrapper for the Python PyErr_SetObject call. SetError Method Sets the current Python exception given a CLR exception object. The CLR exception instance is wrapped as a Python object, allowing it to be handled naturally from Python. When called after SetError, sets the cause of the error. The cause of the current error ErrorOccurred Method Returns true if an exception occurred in the Python runtime. This is a wrapper for the Python PyErr_Occurred call. Clear Method Clear any exception that has been set in the Python runtime. Alias for Python's warnings.warn() function. Raises a and attaches any existing exception as its cause. The exception message null Gets the object, whose finalization failed. If this function crashes, you can also try , which does not attempt to increase the object reference count. Gets the object, whose finalization failed without incrementing its reference count. This should only ever be called during debugging. When the result is disposed or finalized, the program will crash. Implements the "import hook" used to integrate Python with the CLR. Initialization performed on startup of the Python runtime. Cleanup resources upon shutdown of the Python runtime. Sets up the tracking of loaded namespaces. This makes available to Python, as a Python object, the loaded namespaces. The set of loaded namespaces is used during the import to verify if we can import a CLR assembly as a module or not. The set is stored on the clr module. Removes the set of available namespaces from the clr module. Because we use a proxy module for the clr module, we somtimes need to force the py_clr_module to sync with the actual clr module's dict. Return the clr python module (new reference) The hook to import a CLR module into Python. Returns a new reference to the module. xxx This file defines objects to support binary interop with the Python runtime. Generally, the definitions here need to be kept up to date when moving to new Python versions. TypeFlags(): The actual bit values for the Type Flags stored in a class. Note that the two values reserved for stackless have been put to good use as PythonNet specific flags (Managed and Subclass) PythonNet specific PythonNet specific Enables replacing base types of CLR types as seen from Python Get Python types, that should be presented to Python as the base types for the specified .NET type. A MethodBinder encapsulates information about a (possibly overloaded) managed method, and is responsible for selecting the right method given a set of Python arguments. This is also used as a base class for the ConstructorBinder, a minor variation used to invoke constructors. The overloads of this method Given a sequence of MethodInfo and a sequence of types, return the MethodInfo that matches the signature represented by those types. Given a sequence of MethodInfo and a sequence of type parameters, return the MethodInfo(s) that represents the matching closed generic. If unsuccessful, returns null and may set a Python error. Given a sequence of MethodInfo and two sequences of type parameters, return the MethodInfo that matches the signature and the closed generic. Return the array of MethodInfo for this method. The result array is arranged in order of precedence (done lazily to avoid doing it at all for methods that are never called). Precedence algorithm largely lifted from Jython - the concerns are generally the same so we'll start with this and tweak as necessary. Based from Jython `org.python.core.ReflectedArgs.precedence` See: https://github.com/jythontools/jython/blob/master/src/org/python/core/ReflectedArgs.java#L192 Return a precedence value for a particular Type object. Bind the given Python instance and arguments to a particular method overload in and return a structure that contains the converted Python instance, converted arguments and the correct method to call. If unsuccessful, may set a Python error. The Python target of the method invocation. The Python arguments. The Python keyword arguments. A Binding if successful. Otherwise null. Bind the given Python instance and arguments to a particular method overload in and return a structure that contains the converted Python instance, converted arguments and the correct method to call. If unsuccessful, may set a Python error. The Python target of the method invocation. The Python arguments. The Python keyword arguments. If not null, only bind to that method. A Binding if successful. Otherwise null. Bind the given Python instance and arguments to a particular method overload in and return a structure that contains the converted Python instance, converted arguments and the correct method to call. If unsuccessful, may set a Python error. The Python target of the method invocation. The Python arguments. The Python keyword arguments. If not null, only bind to that method. If not null, additionally attempt to bind to the generic methods in this array by inferring generic type parameters. A Binding if successful. Otherwise null. Attempts to convert Python positional argument tuple and keyword argument table into an array of managed objects, that can be passed to a method. If unsuccessful, returns null and may set a Python error. Information about expected parameters true, if the last parameter is a params array. A pointer to the Python argument tuple Number of arguments, passed by Python Dictionary of keyword argument name to python object pointer A list of default values for omitted parameters Returns number of output parameters If successful, an array of .NET arguments that can be passed to the method. Otherwise null. Try to convert a Python argument object to a managed CLR type. If unsuccessful, may set a Python error. Pointer to the Python argument object. That parameter's managed type. Converted argument. Whether the CLR type is passed by reference. true on success Determine the managed type that a Python argument object needs to be converted into. The parameter's managed type. Pointer to the Python argument object. null if conversion is not possible Check whether the number of Python and .NET arguments match, and compute additional arg information. Number of positional args passed from Python. Parameters of the specified .NET method. Keyword args passed from Python. True if the final param of the .NET method is an array (`params` keyword). List of default values for arguments. Number of kwargs from Python that are also present in the .NET method. Number of non-null defaultsArgs. Utility class to sort method info by parameter type precedence. A Binding is a utility instance that bundles together a MethodInfo representing a method to call, a (possibly null) target instance for the call, and the arguments for the call (all as managed values). Catch-all type for native function objects (to be pointed to) PyGILState_STATE 1-character string 8-bit signed int bools contained in the structure (assumed char) Like but raises AttributeError when the value is NULL, instead of converting to None Allows a method to be entered even though a slot has already filled the entry. When defined, the flag allows a separate method, "__contains__" for example, to coexist with a defined slot like sq_contains. 3.10+ The function stores an additional reference to the class that defines it; both self and class are passed to it. It uses PyCMethodObject instead of PyCFunctionObject. May not be combined with METH_NOARGS, METH_O, METH_CLASS or METH_STATIC. 3.9+ Represents a reference to a Python object, that is being lent, and can only be safely used until execution returns to the caller. Gets a raw pointer to the Python object Gets a raw pointer to the Python object Creates new instance of from raw pointer. Unsafe. Abstract class defining boiler plate methods that Custom Marshalers will use. Custom Marshaler to deal with Managed String to Native conversion differences on UCS2/UCS4. Utility function for Marshaling Unicode Managed String Ptr to Native String You MUST deallocate the IntPtr of the Return when done with it. Custom Marshaler to deal with Managed String Arrays to Native conversion differences on UCS2/UCS4. Provides support for calling native code indirectly through function pointers. Most of the important parts of the Python C API can just be wrapped with p/invoke, but there are some situations (specifically, calling functions through Python type structures) where we need to call functions indirectly. Represents a reference to a Python object, that is tracked by Python's reference counting. Creates a pointing to the same object Creates a pointing to the same object Returns wrapper around this reference, which now owns the pointer. Sets the original reference to null, as it no longer owns it. Creates new instance of which now owns the pointer. Sets the original reference to null, as it no longer owns the pointer. Moves ownership of this instance to unmanged pointer Moves ownership of this instance to unmanged pointer Returns wrapper around this reference, which now owns the pointer. Sets the original reference to null, as it no longer owns it. Call this method to move ownership of this reference to a Python C API function, that steals reference passed to it. Call this method to move ownership of this reference to a Python C API function, that steals reference passed to it. Removes this reference to a Python object, and sets it to null. Creates from a raw pointer These members can not be directly in type, because this is always passed by value, which we need to avoid. (note this in NewReference vs the usual this NewReference) Gets a raw pointer to the Python object Buffer size in bytes Simple buffer without shape strides and suboffsets Controls the field. If set, the exporter MUST provide a writable buffer or else report failure. Otherwise, the exporter MAY provide either a read-only or writable buffer, but the choice MUST be consistent for all consumers. Controls the field. If set, this field MUST be filled in correctly. Otherwise, this field MUST be NULL. N-Dimensional buffer with shape Buffer with strides and shape C-Contigous buffer with strides and shape F-Contigous buffer with strides and shape C or Fortran contigous buffer with strides and shape Buffer with suboffsets (if needed) Writable C-Contigous buffer with shape Readonly C-Contigous buffer with shape Writable buffer with shape and strides Readonly buffer with shape and strides Writable buffer with shape, strides and format Readonly buffer with shape, strides and format Writable indirect buffer with shape, strides, format and suboffsets (if needed) Readonly indirect buffer with shape, strides, format and suboffsets (if needed) Checks if the reference points to Python object None. Checks if the reference points to Python object None. Should only be used for the arguments of Python C API functions, that steal references, and internal constructors. Given a module or package name, import the module and return the resulting object. Fully-qualified module or package name Controls visibility to Python for public .NET type or an entire assembly This class provides the public interface of the Python runtime. Set to true to enable GIL debugging assistance. Set the NoSiteFlag to disable loading the site module. Must be called before Initialize. https://docs.python.org/3/c-api/init.html#c.Py_NoSiteFlag Initialize Method Initialize the Python runtime. It is safe to call this method more than once, though initialization will only happen on the first call. It is *not* necessary to hold the Python global interpreter lock (GIL) to call this method. initSigs can be set to 1 to do default python signal configuration. This will override the way signals are handled by the application. A helper to perform initialization from the context of an active CPython interpreter process - this bootstraps the managed runtime when it is imported by the CLR extension module. Shutdown and release resources held by the Python runtime. The Python runtime can no longer be used in the current process after calling the Shutdown method. Called when the engine is shut down. Shutdown handlers are run in reverse order they were added, so that resources available when running a shutdown handler are the same as what was available when it was added. Add a function to be called when the engine is shut down. Shutdown handlers are executed in the opposite order they were added, so that you can be sure that everything that was initialized when you added the handler is still initialized when you need to shut down. If the same shutdown handler is added several times, it will be run several times. Don't add shutdown handlers while running a shutdown handler. Remove a shutdown handler. If the same shutdown handler is added several times, only the last one is removed. Don't remove shutdown handlers while running a shutdown handler. Run all the shutdown handlers. They're run in opposite order they were added. AcquireLock Method Acquire the Python global interpreter lock (GIL). Managed code *must* call this method before using any objects or calling any methods on objects in the Python.Runtime namespace. The only exception is PythonEngine.Initialize, which may be called without first calling AcquireLock. Each call to AcquireLock must be matched by a corresponding call to ReleaseLock, passing the token obtained from AcquireLock. For more information, see the "Extending and Embedding" section of the Python documentation on www.python.org. ReleaseLock Method Release the Python global interpreter lock using a token obtained from a previous call to AcquireLock. For more information, see the "Extending and Embedding" section of the Python documentation on www.python.org. BeginAllowThreads Method Release the Python global interpreter lock to allow other threads to run. This is equivalent to the Py_BEGIN_ALLOW_THREADS macro provided by the C Python API. For more information, see the "Extending and Embedding" section of the Python documentation on www.python.org. EndAllowThreads Method Re-aquire the Python global interpreter lock for the current thread. This is equivalent to the Py_END_ALLOW_THREADS macro provided by the C Python API. For more information, see the "Extending and Embedding" section of the Python documentation on www.python.org. Eval Method Evaluate a Python expression and returns the result. It's a subset of Python eval function. Exec Method Run a string containing Python code. It's a subset of Python exec function. Exec Method Run a string containing Python code. It's a subset of Python exec function. Gets the Python thread ID. The Python thread ID. Interrupts the execution of a thread. The Python thread ID. The number of thread states modified; this is normally one, but will be zero if the thread id is not found. RunString Method. Function has been deprecated and will be removed. Use Exec/Eval/RunSimpleString instead. Internal RunString Method. Run a string containing Python code. Returns the result of executing the code string as a PyObject instance, or null if an exception was raised. Provides a managed interface to exceptions thrown by the Python runtime. Rethrows the last Python exception as corresponding CLR exception. It is recommended to call this as throw ThrowLastAsClrException() to assist control flow checks. Requires lock to be acquired elsewhere Restores python error. Returns the exception type as a Python object. Returns the exception value as a Python object. Returns the TraceBack as a Python object. StackTrace Property A string representing the python exception stack trace. Replaces Value with an instance of Type, if Value is not already an instance of Type. Formats this PythonException object into a message as would be printed out via the Python console. See traceback.format_exception Returns true if the current Python exception matches the given exception type. An array of length indicating the shape of the memory as an n-dimensional array. An array of length giving the number of bytes to skip to get to a new element in each dimension. Will be null except when PyBUF_STRIDES or PyBUF_INDIRECT flags in GetBuffer/>. An array of Py_ssize_t of length ndim. If suboffsets[n] >= 0, the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing. A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block). Return the implied itemsize from format. On error, raise an exception and return -1. New in version 3.9. Returns true if the memory defined by the view is C-style (order is 'C') or Fortran-style (order is 'F') contiguous or either one (order is 'A'). Returns false otherwise. C-style (order is 'C') or Fortran-style (order is 'F') contiguous or either one (order is 'A') Get the memory area pointed to by the indices inside the given view. indices must point to an array of view->ndim indices. Copy contiguous len bytes from buf to view. fort can be 'C' or 'F' (for C-style or Fortran-style ordering). Copy len bytes from view to its contiguous representation in buf. order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error. order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one). Buffer to copy to Fill the strides array with byte-strides of a contiguous (C-style if order is 'C' or Fortran-style if order is 'F') array of the given shape with the given number of bytes per element. FillInfo Method Handle buffer requests for an exporter that wants to expose buf of size len with writability set according to readonly. buf is interpreted as a sequence of unsigned bytes. The flags argument indicates the request type. This function always fills in view as specified by flags, unless buf has been designated as read-only and PyBUF_WRITABLE is set in flags. On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1; If this function is used as part of a getbufferproc, exporter MUST be set to the exporting object and flags must be passed unmodified.Otherwise, exporter MUST be NULL. On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1; Writes a managed byte array into the buffer of a python object. This can be used to pass data like images from managed to python. Reads the buffer of a python object into a managed byte array. This can be used to pass data like images from python to managed. Release the buffer view and decrement the reference count for view->obj. This function MUST be called when the buffer is no longer being used, otherwise reference leaks may occur. It is an error to call this function on a buffer that was not obtained via . Represents a Python dictionary object. See the documentation at PY2: https://docs.python.org/2/c-api/dict.html PY3: https://docs.python.org/3/c-api/dict.html for details. Creates a new Python dictionary object. Wraps existing dictionary object. Thrown if the given object is not a Python dictionary object IsDictType Method Returns true if the given object is a Python dictionary. HasKey Method Returns true if the object key appears in the dictionary. HasKey Method Returns true if the string key appears in the dictionary. Keys Method Returns a sequence containing the keys of the dictionary. Values Method Returns a sequence containing the values of the dictionary. Items Method Returns a sequence containing the items of the dictionary. Copy Method Returns a copy of the dictionary. Update Method Update the dictionary from another dictionary. Clear Method Clears the dictionary. Represents a Python float object. See the documentation at PY3: https://docs.python.org/3/c-api/float.html for details. PyFloat Constructor Copy constructor - obtain a PyFloat from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python float object. PyFloat Constructor Creates a new Python float from a double value. PyFloat Constructor Creates a new Python float from a string value. IsFloatType Method Returns true if the given object is a Python float. Convert a Python object to a Python float if possible, raising a PythonException if the conversion is not possible. This is equivalent to the Python expression "float(object)". Represents a Python integer object. See the documentation at https://docs.python.org/3/c-api/long.html PyInt Constructor Copy constructor - obtain a PyInt from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python int object. PyInt Constructor Creates a new Python int from an int32 value. PyInt Constructor Creates a new Python int from a uint32 value. PyInt Constructor Creates a new Python int from an int64 value. Creates a new Python int from a value. PyInt Constructor Creates a new Python int from an int16 value. PyInt Constructor Creates a new Python int from a uint16 value. PyInt Constructor Creates a new Python int from a byte value. PyInt Constructor Creates a new Python int from an sbyte value. PyInt Constructor Creates a new Python int from a string value. IsIntType Method Returns true if the given object is a Python int. Convert a Python object to a Python int if possible, raising a PythonException if the conversion is not possible. This is equivalent to the Python expression "int(object)". ToInt16 Method Return the value of the Python int object as an int16. Return the value of the Python int object as an . ToInt64 Method Return the value of the Python int object as an int64. Represents a standard Python iterator object. See the documentation at PY2: https://docs.python.org/2/c-api/iterator.html PY3: https://docs.python.org/3/c-api/iterator.html for details. PyIter Constructor Creates a new PyIter from an existing iterator reference. Note that the instance assumes ownership of the object reference. The object reference is not checked for type-correctness. Creates new from an untyped reference to Python object. The object must support iterator protocol. Create a new from a given iterable. Like doing "iter()" in Python. Creates new instance from an existing object. This constructor does not check if is actually iterable. Return a new PyIter object for the object. This allows any iterable python object to be iterated over in C#. A PythonException will be raised if the object is not iterable. Represents a standard Python list object. See the documentation at PY2: https://docs.python.org/2/c-api/list.html PY3: https://docs.python.org/3/c-api/list.html for details. Creates new pointing to the same object, as the given reference. PyList Constructor Copy constructor - obtain a PyList from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python list object. Creates a new empty Python list object. Creates a new Python list object from an array of objects. Returns true if the given object is a Python list. Converts a Python object to a Python list if possible, raising a PythonException if the conversion is not possible. This is equivalent to the Python expression "list(object)". Append an item to the list object. Insert an item in the list object at the given index. Reverse Method Reverse the order of the list object in place. Sort Method Sort the list in place. Given a module or package name, import the module and return the resulting object. Fully-qualified module or package name Reloads the module, and returns the updated object Returns the variables dict of the module. Create a scope, and import all from this scope Import module by its name. Import module as a variable of given name. The 'import .. as ..' statement in Python. Import a module as a variable. Import all variables of the module into this module. Import all variables of the module into this module. Import all variables in the dictionary into this module. Execute method Execute a Python ast and return the result as a PyObject. The ast can be either an expression or stmts. Execute a Python ast and return the result as a , and convert the result to a Managed Object of given type. The ast can be either an expression or stmts. Evaluate a Python expression and return the result as a . Evaluate a Python expression Evaluate a Python expression and convert the result to a Managed Object of given type. Exec Method Exec a Python script and save its local variables in the current local variable dict. Set Variable Method Add a new variable to the variables dict if it not exist or update its value if the variable exists. Remove Method Remove a variable from the variables dict. Returns true if the variable exists in the module. Returns the value of the variable with the given name. Thrown when variable with the given name does not exist. TryGet Method Returns the value of the variable, local variable first. If the variable does not exist, return null. Get Method Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, throw an Exception. TryGet Method Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, return false. Represents a generic Python number. The methods of this class are equivalent to the Python "abstract number API". See PY3: https://docs.python.org/3/c-api/number.html for details. TODO: add all of the PyNumber_XXX methods. IsNumberType Method Returns true if the given object is a Python numeric type. Represents a generic Python object. The methods of this class are generally equivalent to the Python "abstract object API". See PY2: https://docs.python.org/2/c-api/object.html PY3: https://docs.python.org/3/c-api/object.html for details. PyObject Constructor Creates a new PyObject from an IntPtr object reference. Note that the PyObject instance assumes ownership of the object reference and the reference will be DECREFed when the PyObject is garbage collected or explicitly disposed. Creates new pointing to the same object as the . Increments refcount, allowing to have ownership over its own reference. Create a new PyObject instance of this object, bumping the reference count. Gets the native handle of the underlying Python object. This value is generally for internal use by the PythonNet runtime. Gets raw Python proxy for this object (bypasses all conversions, except null <==> None) Given an arbitrary managed object, return a Python instance that reflects the managed object. Creates new from a nullable reference. When is null, null is returned. AsManagedObject Method Return a managed object of the given type, based on the value of the Python object. Return a managed object of the given type, based on the value of the Python object. The Dispose method provides a way to explicitly release the Python object represented by a PyObject instance. It is a good idea to call Dispose on PyObjects that wrap resources that are limited or need strict lifetime control. Otherwise, references to Python objects will not be released until a managed garbage collection occurs. GetPythonType Method Returns the Python type of the object. This method is equivalent to the Python expression: type(object). TypeCheck Method Returns true if the object o is of type typeOrClass or a subtype of typeOrClass. HasAttr Method Returns true if the object has an attribute with the given name. HasAttr Method Returns true if the object has an attribute with the given name, where name is a PyObject wrapping a string or unicode object. GetAttr Method Returns the named attribute of the Python object, or raises a PythonException if the attribute access fails. Returns the named attribute of the Python object, or the given default object if the attribute access throws AttributeError. This method ignores any AttrubiteError(s), even ones not raised due to missing requested attribute. For example, if attribute getter calls other Python code, and that code happens to cause AttributeError elsewhere, it will be ignored and value will be returned instead. Name of the attribute. The object to return on AttributeError. GetAttr Method Returns the named attribute of the Python object or raises a PythonException if the attribute access fails. The name argument is a PyObject wrapping a Python string or unicode object. Returns the named attribute of the Python object, or the given default object if the attribute access throws AttributeError. This method ignores any AttrubiteError(s), even ones not raised due to missing requested attribute. For example, if attribute getter calls other Python code, and that code happens to cause AttributeError elsewhere, it will be ignored and value will be returned instead. Name of the attribute. Must be of Python type 'str'. The object to return on AttributeError. SetAttr Method Set an attribute of the object with the given name and value. This method throws a PythonException if the attribute set fails. SetAttr Method Set an attribute of the object with the given name and value, where the name is a Python string or unicode object. This method throws a PythonException if the attribute set fails. DelAttr Method Delete the named attribute of the Python object. This method throws a PythonException if the attribute set fails. DelAttr Method Delete the named attribute of the Python object, where name is a PyObject wrapping a Python string or unicode object. This method throws a PythonException if the attribute set fails. GetItem Method For objects that support the Python sequence or mapping protocols, return the item at the given object index. This method raises a PythonException if the indexing operation fails. GetItem Method For objects that support the Python sequence or mapping protocols, return the item at the given string index. This method raises a PythonException if the indexing operation fails. GetItem Method For objects that support the Python sequence or mapping protocols, return the item at the given numeric index. This method raises a PythonException if the indexing operation fails. SetItem Method For objects that support the Python sequence or mapping protocols, set the item at the given object index to the given value. This method raises a PythonException if the set operation fails. SetItem Method For objects that support the Python sequence or mapping protocols, set the item at the given string index to the given value. This method raises a PythonException if the set operation fails. SetItem Method For objects that support the Python sequence or mapping protocols, set the item at the given numeric index to the given value. This method raises a PythonException if the set operation fails. DelItem Method For objects that support the Python sequence or mapping protocols, delete the item at the given object index. This method raises a PythonException if the delete operation fails. DelItem Method For objects that support the Python sequence or mapping protocols, delete the item at the given string index. This method raises a PythonException if the delete operation fails. DelItem Method For objects that support the Python sequence or mapping protocols, delete the item at the given numeric index. This method raises a PythonException if the delete operation fails. Returns the length for objects that support the Python sequence protocol. String Indexer Provides a shorthand for the string versions of the GetItem and SetItem methods. PyObject Indexer Provides a shorthand for the object versions of the GetItem and SetItem methods. Numeric Indexer Provides a shorthand for the numeric versions of the GetItem and SetItem methods. Return a new (Python) iterator for the object. This is equivalent to the Python expression "iter(object)". Thrown if the object can not be iterated. Invoke Method Invoke the callable object with the given arguments, passed as a PyObject[]. A PythonException is raised if the invocation fails. Invoke Method Invoke the callable object with the given arguments, passed as a Python tuple. A PythonException is raised if the invocation fails. Invoke Method Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails. Invoke Method Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails. InvokeMethod Method Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful. InvokeMethod Method Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful. InvokeMethod Method Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful. InvokeMethod Method Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful. InvokeMethod Method Invoke the named method of the object with the given arguments and keyword arguments. Keyword args are passed as a PyDict object. A PythonException is raised if the invocation is unsuccessful. InvokeMethod Method Invoke the named method of the object with the given arguments and keyword arguments. Keyword args are passed as a PyDict object. A PythonException is raised if the invocation is unsuccessful. IsInstance Method Return true if the object is an instance of the given Python type or class. This method always succeeds. Return true if the object is identical to or derived from the given Python type or class. This method always succeeds. IsCallable Method Returns true if the object is a callable object. This method always succeeds. IsIterable Method Returns true if the object is iterable object. This method always succeeds. IsTrue Method Return true if the object is true according to Python semantics. This method always succeeds. Return true if the object is None Dir Method Return a list of the names of the attributes of the object. This is equivalent to the Python expression "dir(object)". Repr Method Return a string representation of the object. This method is the managed equivalent of the Python expression "repr(object)". ToString Method Return the string representation of the object. This method is the managed equivalent of the Python expression "str(object)". Equals Method Return true if this object is equal to the given object. This method is based on Python equality semantics. GetHashCode Method Return a hashcode based on the Python object. This returns the hash as computed by Python, equivalent to the Python expression "hash(obj)". GetBuffer Method. This Method only works for objects that have a buffer (like "bytes", "bytearray" or "array.array") Send a request to the PyObject to fill in view as specified by flags. If the PyObject cannot provide a buffer of the exact type, it MUST raise PyExc_BufferError, set view->obj to NULL and return -1. On success, fill in view, set view->obj to a new reference to exporter and return 0. In the case of chained buffer providers that redirect requests to a single object, view->obj MAY refer to this object instead of exporter(See Buffer Object Structures). Successful calls to must be paired with calls to , similar to malloc() and free(). Thus, after the consumer is done with the buffer, must be called exactly once. Returns the enumeration of all dynamic member names. This method exists for debugging purposes only. A sequence that contains dynamic member names. Represents a generic Python sequence. The methods of this class are equivalent to the Python "abstract sequence API". See PY2: https://docs.python.org/2/c-api/sequence.html PY3: https://docs.python.org/3/c-api/sequence.html for details. Creates new instance from an existing object. does not provide sequence protocol Returns true if the given object implements the sequence protocol. Return the slice of the sequence with the given indices. Sets the slice of the sequence with the given indices. DelSlice Method Deletes the slice of the sequence with the given indices. Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence. Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence. Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence. Return true if the sequence contains the given item. This method throws a PythonException if an error occurs during the check. Return the concatenation of the sequence object with the passed in sequence object. Return the sequence object repeated N times. This is equivalent to the Python expression "object * count". Represents a Python (ANSI) string object. See the documentation at PY2: https://docs.python.org/2/c-api/string.html PY3: No Equivalent for details. 2011-01-29: ...Then why does the string constructor call PyUnicode_FromUnicode()??? PyString Constructor Copy constructor - obtain a PyString from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python string object. PyString Constructor Creates a Python string from a managed string. Returns true if the given object is a Python string. Represents a Python tuple object. See the documentation at PY2: https://docs.python.org/2/c-api/tupleObjects.html PY3: https://docs.python.org/3/c-api/tupleObjects.html for details. PyTuple Constructor Creates a new PyTuple from an existing object reference. The object reference is not checked for type-correctness. PyTuple Constructor Copy constructor - obtain a PyTuple from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python tuple object. PyTuple Constructor Creates a new empty PyTuple. PyTuple Constructor Creates a new PyTuple from an array of PyObject instances. See caveats about PyTuple_SetItem: https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/ Returns true if the given object is a Python tuple. Convert a Python object to a Python tuple if possible. This is equivalent to the Python expression "tuple()". Raised if the object can not be converted to a tuple. Creates heap type object from the . Wraps an existing type object. Create a new PyType instance of this object, bumping the reference count. Returns true when type is fully initialized Checks if specified object is a Python type. Checks if specified object is a Python type. Gets , which represents the specified CLR type. New in 3.5 Encapsulates the low-level Python C API. Note that it is the responsibility of the caller to have acquired the GIL before calling any of these methods. Initialize the runtime... Always call this method from the Main thread. After the first call to this method, the main thread has acquired the GIL. Alternates .NET and Python GC runs in an attempt to collect all garbage Total number of GC loops to run true if a steady state was reached upon the requested number of tries (e.g. on the last try no objects were collected). Check if any Python Exceptions occurred. If any exist throw new PythonException. Can be used instead of `obj == IntPtr.Zero` for example. Managed exports of the Python C API. Where appropriate, we do some optimization to avoid managed <--> unmanaged transitions (mostly for heavily used methods). Call specified function, and handle PythonDLL-related failures. Export of Macro Py_XIncRef. Use XIncref instead. Limit this function usage for Testing and Py_Debug builds PyObject Ptr Export of Macro Py_XDecRef. Use XDecref instead. Limit this function usage for Testing and Py_Debug builds PyObject Ptr Return value: New reference. This is a simplified interface to Py_CompileStringFlags() below, leaving flags set to NULL. A macro-like method to get the type of a Python object. This is designed to be lean and mean in IL & avoid managed <-> unmanaged transitions. Note that this does not incref the type object. Test whether the Python object is an iterable. Return value: New reference. Create a Python integer from the pointer p. The pointer value can be retrieved from the resulting value using PyLong_AsVoidPtr(). Convert a Python integer pylong to a C void pointer. If pylong cannot be converted, an OverflowError will be raised. This is only assured to produce a usable void pointer for values created with PyLong_FromVoidPtr(). Length in code points Function to access the internal PyUnicode/PyString object and convert it to a managed string with the correct encoding. We can't easily do this through through the CustomMarshaler's on the returns because will have access to the IntPtr but not size. For PyUnicodeType, we can't convert with Marshal.PtrToStringUni since it only works for UCS2. PyStringType or PyUnicodeType object to convert Managed String Return NULL if the key is not present, but without setting an exception. Return 0 on success or -1 on failure. Return 0 on success or -1 on failure. Return 1 if found, 0 if not found, and -1 if an error is encountered. The module to add the object to. The key that will refer to the object. The object to add to the module. Return -1 on error, 0 on success. Return value: New reference. Return value: Borrowed reference. Return the object name from the sys module or NULL if it does not exist, without setting an exception. Finalize a type object. This should be called on all type objects to finish their initialization. This function is responsible for adding inherited slots from a type�s base class. Return 0 on success, or return -1 and sets an exception on error. Set the cause associated with the exception to cause. Use NULL to clear it. There is no type check to make sure that cause is either an exception instance or None. This steals a reference to cause. Callback called as a last step in the serialization process Callback called as the first step in the deserialization process Clears the old "clr_data" entry if a previous one is present. Removes the serialization capsule from the `sys` module object. The serialization data must have been set with StashSerializationData The name given to the capsule on the `sys` module object Stores the data in the argument in a Python capsule and stores the capsule on the `sys` module object with the name . No checks on pre-existing names on the `sys` module object are made. The name given to the capsule on the `sys` module object A MemoryStream that contains the data to be placed in the capsule Retreives the previously stored data on a Python capsule. Throws if the object corresponding to the parameter on the `sys` module object is not a capsule. The name given to the capsule on the `sys` module object A MemoryStream containing the previously saved serialization data. The stream is empty if no name matches the key. The TypeManager class is responsible for building binary-compatible Python type objects that are implemented in managed code. initialized in rather than in constructor Given a managed Type derived from ExtensionType, get the handle to a Python type object that delegates its implementation to the Type object. These Python type instances are used to implement internal descriptor and utility types like ModuleObject, PropertyObject, etc. The following CreateType implementations do the necessary work to create Python types to represent managed extension types, reflected types, subclasses of reflected types and the managed metatype. The dance is slightly different for each kind of type due to different behavior needed and the desire to have the existing Python runtime do as much of the allocation and initialization work as possible. Utility method to allocate a type object & do basic initialization. Inherit substructs, that are not inherited by default: https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_as_number Given a newly allocated Python type object and a managed Type that provides the implementation for the type, connect the type slots of the Python object to the managed methods of the implementing Type. Utility method to copy slots from a given type to another type. Create slots holder for holding the delegate of slots and be able to reset them. Steals a reference to target type Implements a Python type for managed arrays. This type is essentially the same as a ClassObject, except that it provides sequence semantics to support natural array usage (indexing) from Python. Implements __getitem__ for array types. Implements __setitem__ for array types. Implements __contains__ for array types. Base class for Python types that reflect managed types / classes. Concrete subclasses include ClassObject and DelegateObject. This class provides common attributes and common machinery for doing class initialization (initialization of the class __dict__). The concrete subclasses provide slot implementations appropriate for each variety of reflected type. Default implementation of [] semantics for reflected types. Standard comparison implementation for instances of reflected types. Standard iteration support for instances of reflected types. This allows natural iteration over objects that either are IEnumerable or themselves support IEnumerator directly. Standard __hash__ implementation for instances of reflected types. Standard __str__ implementation for instances of reflected types. Standard dealloc implementation for instances of reflected types. Implements __getitem__ for reflected classes and value types. Implements __setitem__ for reflected classes and value types. Implements __delitem__ (del x[...]) for IList<T> and IDictionary<TKey, TValue>. Managed class that provides the implementation for reflected types. Managed classes and value types are represented in Python by actual Python type objects. Each of those type objects is associated with an instance of ClassObject, which provides its implementation. interface used to identify which C# types were dynamically created as python subclasses No-op clear. Real cleanup happens in Called from Converter.ToPython for types that are python subclasses of managed types. The referenced python object is returned instead of a new wrapper. Creates a new managed type derived from a base type with any virtual methods overridden to call out to python if the associated python object has overridden the method. Add a constructor override that calls the python ctor after calling the base type constructor. constructor to be called before calling the python ctor Python callable object TypeBuilder for the new type the ctor is to be added to Add a virtual method override that checks for an override on the python instance and calls it, otherwise fall back to the base class method. virtual method to be overridden Python callable object TypeBuilder for the new type the method is to be added to Python method may have the following function attributes set to control how they're exposed: - _clr_return_type_ - method return type (required) - _clr_arg_types_ - list of method argument types (required) - _clr_method_name_ - method name, if different from the python method name (optional) Method name to add to the type Python callable object TypeBuilder for the new type the method/property is to be added to Python properties may have the following function attributes set to control how they're exposed: - _clr_property_type_ - property type (required) Property name to add to the type Python property object TypeBuilder for the new type the method/property is to be added to PythonDerivedType contains static methods used by the dynamically created derived type that allow it to call back into python from overridden virtual methods, and also handle the construction and destruction of the python object. This has to be public as it's called from methods on dynamically built classes potentially in other assemblies. This is the implementation of the overridden methods in the derived type. It looks for a python method with the same name as the method on the managed base class and if it exists and isn't the managed method binding (i.e. it has been overridden in the derived python class) it calls it, otherwise it calls the base method. If the method has byref arguments, reinterprets Python return value as a tuple of new values for those arguments, and updates corresponding elements of array. Managed class that provides the implementation for reflected types. Managed classes and value types are represented in Python by actual Python type objects. Each of those type objects is associated with an instance of ClassObject, which provides its implementation. Helper to get docstring from reflected constructor info. given an enum, write a __repr__ string formatted in the same way as a python repr string. Something like: '<Color.GREEN: 2>'; with a binary value for [Flags] enums Instace of the enum object ClassObject __repr__ implementation. Implements __new__ for reflected classes and value types. Construct a new .NET String object from Python args This manual implementation of all individual relevant constructors is required because System.String can't be allocated uninitialized. Additionally, it implements `String(pythonStr)` Create a new Python object for a primitive type The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single. All numeric types and Boolean can be handled by a simple conversion, (U)IntPtr has to be handled separately as we do not want to convert them automically to/from integers. .NET type to construct Corresponding Python type Constructor arguments Implementation of [] semantics for reflected types. This exists both to implement the Array[int] syntax for creating arrays and to support generic name overload resolution using []. The CLR module is the root handler used by the magic import hook to import assemblies. It has a fixed module name "clr" and doesn't provide a namespace. The initializing of the preload hook has to happen as late as possible since sys.ps1 is created after the CLR module is created. Get a Type instance for a class object. clr.GetClrType(IComparable) gives you the Type for IComparable, that you can e.g. perform reflection on. Similar to typeof(IComparable) in C# or clr.GetClrType(IComparable) in IronPython. The Type object Note: This should *not* be called directly. The function that get/import a CLR assembly as a python module. This function should only be called by the import machinery as seen in importhook.cs A ModuleSpec Python object A new reference to the imported module, as a PyObject. Managed class that provides the implementation for reflected delegate types. Delegates are represented in Python by generated type objects. Each of those type objects is associated an instance of this class, which provides its implementation. Given a PyObject pointer to an instance of a delegate type, return the true managed delegate the Python object represents (or null). DelegateObject __new__ implementation. The result of this is a new PyObject whose type is DelegateObject and whose ob_data is a handle to an actual delegate instance. The method wrapped by the actual delegate instance belongs to an object generated to relay the call to the Python callable passed in. Implements __call__ for reflected delegate types. Implements __cmp__ for reflected delegate types. Implements a Python event binding type, similar to a method binding. EventBinding += operator implementation. EventBinding -= operator implementation. EventBinding __hash__ implementation. EventBinding __repr__ implementation. Implements a Python descriptor type that provides access to CLR events. Descriptor __get__ implementation. A getattr on an event returns a "bound" event that keeps a reference to the object instance. Descriptor __set__ implementation. This actually never allows you to set anything; it exists solely to support the '+=' spelling of event handler registration. The reason is that given code like: 'ob.SomeEvent += method', Python will attempt to set the attribute SomeEvent on ob to the result of the '+=' operation. Descriptor __repr__ implementation. Base class for Python types that reflect managed exceptions based on System.Exception Exception __repr__ implementation Exception __str__ implementation Base class for extensions whose instances *share* a single Python type object, such as the types that represent CLR methods, fields, etc. Instances implemented by this class do not support sub-typing. Type __setattr__ implementation. Called during tp_clear before the GCHandle is released. Override to eagerly dispose Python object references (PyObject fields) held by the subclass, preventing the multi-hop .NET finalizer chain from delaying Python-side refcount decrements. Implements a Python descriptor type that provides access to CLR fields. Descriptor __get__ implementation. This method returns the value of the field on the given object. The returned value is converted to an appropriately typed Python object. Descriptor __set__ implementation. This method sets the value of a field based on the given Python value. The Python value must be convertible to the type of the field. Descriptor __repr__ implementation. Implements reflected generic types. Note that the Python behavior is the same for both generic type definitions and constructed open generic types. Both are essentially factories for creating closed types based on the required generic type parameters. Implements __new__ for reflected generic types. Implements __call__ for reflected generic types. Bundles the information required to support an indexer property. This will return default arguments a new instance of a tuple. The size of the tuple will indicate the number of default arguments. This is pointing to the tuple args passed in a new instance of the tuple containing the default args Provides the implementation for reflected interface types. Managed interfaces are represented in Python by actual Python type objects. Each of those type objects is associated with an instance of this class, which provides the implementation for the Python type. Implements __new__ for reflected interface types. Wrap the given object in an interface object, so that only methods of the interface are available. Expose the wrapped implementation through attributes in both converted/encoded (__implementation__) and raw (__raw_implementation__) form. Implements a generic Python iterator for IEnumerable objects and managed array objects. This supports 'for i in object:' in Python. Implements support for the Python iteration protocol. Common base class for all objects that are implemented in managed code. It defines the common fields that associate CLR and Python objects and common utilities to convert between those identities. Given a Python object, return the associated managed object or null. Wrapper for calling tp_clear Initializes given object, or returns false and sets Python error on failure The managed metatype. This object implements the type of all reflected types. It also provides support for single-inheritance from reflected managed types. Metatype initialization. This bootstraps the CLR metatype to life. Metatype __new__ implementation. This is called to create a new class / type when a reflected class is subclassed. Metatype __call__ implementation. This is needed to ensure correct initialization (__init__ support), because the tp_call we inherit from PyType_Type won't call __init__ for metatypes it doesn't know. Type __setattr__ implementation for reflected types. Note that this is slightly different than the standard setattr implementation for the normal Python metatype (PyTypeType). We need to look first in the type object of a reflected type for a descriptor in order to support the right setattr behavior for static fields and properties. The metatype has to implement [] semantics for generic types, so here we just delegate to the generic type def implementation. Its own mp_subscript Dealloc implementation. This is called when a Python type generated by this metatype is no longer referenced from the Python runtime. Implements a Python binding type for CLR methods. These work much like standard Python method bindings, but the same type is used to bind both static and instance methods. Implement binding of generic methods using the subscript syntax []. MethodBinding __getattribute__ implementation. MethodBinding __call__ implementation. MethodBinding __hash__ implementation. MethodBinding __repr__ implementation. Implements a Python type that represents a CLR method. Method objects support a subscript syntax [] to allow explicit overload selection. TODO: ForbidPythonThreadsAttribute per method info Helper to get docstrings from reflected method / param info. This is a little tricky: a class can actually have a static method and instance methods all with the same name. That makes it tough to support calling a method 'unbound' (passing the instance as the first argument), because in this case we can't know whether to call the instance method unbound or call the static method. The rule we is that if there are both instance and static methods with the same name, then we always call the static method. So this method returns true if any of the methods that are represented by the descriptor are static methods (called by MethodBinding). Descriptor __getattribute__ implementation. Descriptor __get__ implementation. Accessing a CLR method returns a "bound" method similar to a Python bound method. Descriptor __repr__ implementation. Module level functions __call__ implementation. __repr__ implementation. Implements a Python type that provides access to CLR namespaces. The type behaves like a Python module, and can contain other sub-modules. is initialized in Returns a ClassBase object representing a type that appears in this module's namespace or a ModuleObject representing a child namespace (or null if the name is not found). This method does not increment the Python refcount of the returned object. Stores an attribute in the instance dict for future lookups. Preloads all currently-known names for the module namespace. This can be called multiple times, to add names from assemblies that may have been loaded since the last call to the method. Initialize module level functions and attributes ModuleObject __getattribute__ implementation. Module attributes are always either classes or sub-modules representing subordinate namespaces. CLR modules implement a lazy pattern - the sub-modules and classes are created when accessed and cached for future use. ModuleObject __repr__ implementation. Override the setattr implementation. This is needed because the import mechanics need to set a few attributes Module level properties (attributes) Implements __len__ for classes that implement ICollection (this includes any IList implementer or Array subclass) Maps the compiled method name in .NET CIL (e.g. op_Addition) to the equivalent Python operator (e.g. __add__) as well as the offset that identifies that operator's slot (e.g. nb_add) in heap space. For the operator methods of a CLR type, set the special slots of the corresponding Python type's operator methods. Check if the method should have a reversed operation. The operator method. Implements the __overloads__ attribute of method objects. This object supports the [] syntax to explicitly select an overload by signature. Implement explicit overload selection using subscript syntax ([]). OverloadMapper __repr__ implementation. Implements a Python descriptor type that manages CLR properties. Descriptor __get__ implementation. This method returns the value of the property on the given object. The returned value is converted to an appropriately typed Python object. Descriptor __set__ implementation. This method sets the value of a property based on the given Python value. The Python value must be convertible to the type of the property. Descriptor __repr__ implementation. Get the Python type that reflects the given CLR type. Returned might be partially initialized. Several places in the runtime generate code on the fly to support dynamic functionality. The CodeGenerator class manages the dynamic assembly used for code generation and provides utility methods for certain repetitive tasks. DefineType is a shortcut utility to get a new TypeBuilder. DefineType is a shortcut utility to get a new TypeBuilder. Generates code, that copies potentially modified objects in args array back to the corresponding byref arguments Debugging helper utilities. The methods are only executed when the DEBUG flag is set. Otherwise they are automagically hidden by the compiler and silently suppressed. Helper function to inspect/compare managed to native conversions. Especially useful when debugging CustomMarshaler. Register a new Python object event handler with the event. Remove the given Python object event handler. This class is responsible for efficiently maintaining the bits of information we need to support aliases with 'nice names'. Maps namespace -> generic base name -> list of generic type names Register a generic type that appears in a given namespace. A generic type definition (t.IsGenericTypeDefinition must be true) xxx Finds a generic type with the given number of generic parameters and the same name and namespace as . Finds a generic type in the given namespace with the given name and number of generic parameters. xxx An utility class, that can only have one value: null. Useful for overloading operators on structs, that have meaningful concept of null value (e.g. pointers and references). Compares Python object wrappers by Python object references. Similar to but for Python objects Gets substring after last occurrence of