Represents a Python integer object. See the documentation at http://www.python.org/doc/current/api/intObjects.html for details.
Inheritance: PyNumber
Exemple #1
0
 /// <summary>
 /// GetItem Method
 /// </summary>
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual PyObject GetItem(int index)
 {
     using (var key = new PyInt(index))
     {
         return(GetItem(key));
     }
 }
Exemple #2
0
 /// <summary>
 /// DelItem Method
 /// </summary>
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual void DelItem(int index)
 {
     using (var pyindex = new PyInt(index))
     {
         DelItem(pyindex);
     }
 }
Exemple #3
0
 /// <summary>
 /// SetItem Method
 /// </summary>
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual void SetItem(int index, PyObject value)
 {
     using (var pyindex = new PyInt(index))
     {
         SetItem(pyindex, value);
     }
 }
Exemple #4
0
        public static PyObject NewArray(Array content)
        {
            // BlockCopy possibly multidimensional array of arbitrary type to onedimensional byte array
            System.Type ElementType = content.GetType().GetElementType();
            int         nbytes      = content.Length * Marshal.SizeOf(ElementType);

            byte[] data = new byte[nbytes];
            System.Buffer.BlockCopy(content, 0, data, 0, nbytes);

            // Create an python tuple with the dimensions of the input array
            PyObject[] lengths = new PyObject[content.Rank];
            for (int i = 0; i < content.Rank; i++)
            {
                lengths[i] = new PyInt(content.GetLength(i));
            }
            PyTuple shape = new PyTuple(lengths);

            // Create an empty numpy array in correct shape and datatype
            var dtype = GetNumpyDataType(ElementType);
            var arr   = np.InvokeMethod("empty", shape, dtype);

            var meta    = arr.GetAttr("__array_interface__");
            var address = new System.IntPtr((long)meta["data"][0].As <long>());

            // Copy the data to that array
            Marshal.Copy(data, 0, address, nbytes);
            return(arr);
        }
Exemple #5
0
        /// <summary>
        /// SetItem Method
        /// </summary>
        /// <remarks>
        /// 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.
        /// </remarks>
        public virtual void SetItem(int index, PyObject value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            using (var pyindex = new PyInt(index))
            {
                SetItem(pyindex, value);
            }
        }
Exemple #6
0
 /// <summary>
 /// GetItem Method
 /// </summary>
 ///
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual PyObject GetItem(int index)
 {
     PyInt key = new PyInt(index);
     return GetItem((PyObject)key);
 }
Exemple #7
0
 /// <summary>
 /// SetItem Method
 /// </summary>
 ///
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual void SetItem(int index, PyObject value)
 {
     using (PyInt pyindex = new PyInt(index))
     {
         SetItem(pyindex, value);
     }
 }
Exemple #8
0
 /// <summary>
 /// GetItem Method
 /// </summary>
 ///
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual PyObject GetItem(int index)
 {
     using (PyInt key = new PyInt(index))
     {
         return GetItem((PyObject)key);
     }
 }
Exemple #9
0
 /// <summary>
 /// DelItem Method
 /// </summary>
 ///
 /// <remarks>
 /// 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.
 /// </remarks>
 public virtual void DelItem(int index)
 {
     using (PyInt pyindex = new PyInt(index))
     {
         DelItem(pyindex);
     }
 }
Exemple #10
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                serializer.Serialize(writer, null);
                return;
            }

            var jobj      = (PyObject)value;
            var jojb_type = jobj.GetPythonType().ToString();

            if (jojb_type == "<class 'NoneType'>")
            {
                writer.WriteNull();
            }

            else if (PyDict.IsDictType(jobj))
            {
                var dict = new PyDict(jobj);
                var keys = dict.Keys();

                writer.WriteStartObject();

                foreach (PyObject key in keys)
                {
                    string name = key.ToString();
                    var    val  = jobj[key];//.ToString();

                    writer.WritePropertyName(name);
                    serializer.Serialize(writer, val, null);
                }
                writer.WriteEndObject();
            }
            else if (PyLong.IsLongType(jobj))
            {
                var pobj = new PyLong(jobj);
                writer.WriteValue(pobj.ToInt64());
            }
            else if (PyInt.IsIntType(jobj))
            {
                var pobj = new PyInt(jobj);
                writer.WriteValue(pobj.ToInt32());
            }
            else if (PyFloat.IsFloatType(jobj))
            {
                var pobj = new PyFloat(jobj);
                writer.WriteValue(pobj.ToDouble());
            }

            else if (PyString.IsStringType(jobj) || jojb_type == "<class 'datetime.date'>")
            {
                // var pobj = new PyString(jobj);
                writer.WriteValue(jobj.ToString());
            }
            else if (jobj.IsIterable())// && !PyDict.IsDictType(jobj))
            {
                writer.WriteStartArray();
                foreach (var element in jobj)
                {
                    serializer.Serialize(writer, element, null);
                }
                writer.WriteEndArray();
            }
            else
            {
                var properties = jobj.Dir();
                if (properties != null)
                {
                    writer.WriteStartObject();

                    foreach (PyObject property in properties)
                    {
                        string name = property.ToString();
                        if (!property.IsCallable() && !name.StartsWith("__"))
                        {
                            var attr = jobj.GetAttr(property);//.ToString();
                            writer.WritePropertyName(name);
                            try
                            {
                                serializer.Serialize(writer, attr, null);
                            }
                            catch
                            {
                                writer.WriteNull();
                            }
                        }
                    }
                    writer.WriteEndObject();
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// GetItem Method
        /// </summary>
        ///
        /// <remarks>
        /// 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.
        /// </remarks>

        public virtual PyObject GetItem(int index)
        {
            PyInt key = new PyInt(index);

            return(GetItem((PyObject)key));
        }
Exemple #12
0
        internal static bool ToManagedValue(BorrowedReference value, Type obType,
                                            out object?result, bool setError)
        {
            if (obType == typeof(PyObject))
            {
                result = new PyObject(value);
                return(true);
            }

            if (obType.IsSubclassOf(typeof(PyObject)) &&
                !obType.IsAbstract &&
                obType.GetConstructor(new[] { typeof(PyObject) }) is { } ctor)
            {
                var untyped = new PyObject(value);
                result = ToPyObjectSubclass(ctor, untyped, setError);
                return(result is not null);
            }

            // Common case: if the Python value is a wrapped managed object
            // instance, just return the wrapped object.
            result = null;
            switch (ManagedType.GetManagedObject(value))
            {
            case CLRObject co:
                object tmp = co.inst;
                if (obType.IsInstanceOfType(tmp))
                {
                    result = tmp;
                    return(true);
                }
                if (setError)
                {
                    string typeString = tmp is null ? "null" : tmp.GetType().ToString();
                    Exceptions.SetError(Exceptions.TypeError, $"{typeString} value cannot be converted to {obType}");
                }
                return(false);

            case ClassBase cb:
                if (!cb.type.Valid)
                {
                    Exceptions.SetError(Exceptions.TypeError, cb.type.DeletedMessage);
                    return(false);
                }
                result = cb.type.Value;
                return(true);

            case null:
                break;

            default:
                throw new ArgumentException("We should never receive instances of other managed types");
            }

            if (value == Runtime.PyNone && !obType.IsValueType)
            {
                result = null;
                return(true);
            }

            if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                if (value == Runtime.PyNone)
                {
                    result = null;
                    return(true);
                }
                // Set type to underlying type
                obType = obType.GetGenericArguments()[0];
            }

            if (obType.ContainsGenericParameters)
            {
                if (setError)
                {
                    Exceptions.SetError(Exceptions.TypeError, $"Cannot create an instance of the open generic type {obType}");
                }
                return(false);
            }

            if (obType.IsArray)
            {
                return(ToArray(value, obType, out result, setError));
            }

            // Conversion to 'Object' is done based on some reasonable default
            // conversions (Python string -> managed string).
            if (obType == objectType)
            {
                if (Runtime.IsStringType(value))
                {
                    return(ToPrimitive(value, stringType, out result, setError));
                }

                if (Runtime.PyBool_Check(value))
                {
                    return(ToPrimitive(value, boolType, out result, setError));
                }

                if (Runtime.PyFloat_Check(value))
                {
                    return(ToPrimitive(value, doubleType, out result, setError));
                }

                // give custom codecs a chance to take over conversion of ints and sequences
                BorrowedReference pyType = Runtime.PyObject_TYPE(value);
                if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
                {
                    return(true);
                }

                if (Runtime.PyInt_Check(value))
                {
                    result = new PyInt(value);
                    return(true);
                }

                if (Runtime.PySequence_Check(value))
                {
                    return(ToArray(value, typeof(object[]), out result, setError));
                }

                result = new PyObject(value);
                return(true);
            }

            // Conversion to 'Type' is done using the same mappings as above for objects.
            if (obType == typeType)
            {
                if (value == Runtime.PyStringType)
                {
                    result = stringType;
                    return(true);
                }

                if (value == Runtime.PyBoolType)
                {
                    result = boolType;
                    return(true);
                }

                if (value == Runtime.PyLongType)
                {
                    result = typeof(PyInt);
                    return(true);
                }

                if (value == Runtime.PyFloatType)
                {
                    result = doubleType;
                    return(true);
                }

                if (value == Runtime.PyListType)
                {
                    result = typeof(PyList);
                    return(true);
                }

                if (value == Runtime.PyTupleType)
                {
                    result = typeof(PyTuple);
                    return(true);
                }

                if (setError)
                {
                    Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
                }

                return(false);
            }

            if (DecodableByUser(obType))
            {
                BorrowedReference pyType = Runtime.PyObject_TYPE(value);
                if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
                {
                    return(true);
                }
            }

            return(ToPrimitive(value, obType, out result, setError));
        }