python

package module
v3.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2024 License: MIT Imports: 5 Imported by: 2

README

Go high-level bindings for the CPython-3 C-API

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

[!IMPORTANT] Currently supports python-3.11 only.

The package provides a higher level for interacting with Python-3 C-API without directly using the PyObject.

Main goals:

  • Provide generic a Object that interact with Golang types.
  • Automatically marshal and unmarshal Golang types to Python types.

Prerequisites

  • Go >= 1.22
  • Python = 3.11

Install

go get go.nhat.io/python/v3

Examples

package main

import (
    "fmt"

    python3 "go.nhat.io/python/v3"
)

func main() {
    sys := python3.MustImportModule("sys")
    version := sys.GetAttr("version_info")

    pyMajor := version.GetAttr("major")
    defer pyMajor.DecRef()

    pyMinor := version.GetAttr("minor")
    defer pyMinor.DecRef()

    pyReleaseLevel := version.GetAttr("releaselevel")
    defer pyReleaseLevel.DecRef()

    major := python3.AsInt(pyMajor)
    minor := python3.AsInt(pyMinor)
    releaseLevel := python3.AsString(pyReleaseLevel)

    fmt.Println("major:", major)
    fmt.Println("minor:", minor)
    fmt.Println("release level:", releaseLevel)

    // Output:
    // major: 3
    // minor: 11
    // release level: final
}
package main

import (
    "fmt"

    python3 "go.nhat.io/python/v3"
)

func main() { //nolint: govet
    math := python3.MustImportModule("math")

    pyResult := math.CallMethodArgs("sqrt", 4)
    defer pyResult.DecRef()

    result := python3.AsFloat64(pyResult)

    fmt.Printf("sqrt(4) = %.2f\n", result)

    // Output:
    // sqrt(4) = 2.00
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package python provides a high-level interface to the Python C API.

Index

Constants

This section is empty.

Variables

View Source
var ErrPythonInterpreterNotInitialized = "cannot initialize the python interpreter"

ErrPythonInterpreterNotInitialized is the error message when the python interpreter is not initialized.

False is a wrapper of cpy3.Py_False.

True is a wrapper of cpy3.Py_True.

Functions

func AsBool

func AsBool(o *Object) bool

AsBool converts a Python object to a bool.

func AsFloat64

func AsFloat64(o *Object) float64

AsFloat64 converts a Python object to a float64.

func AsInt

func AsInt(o *Object) int

AsInt converts a Python object to an int.

func AsInt64

func AsInt64(o *Object) int64

AsInt64 converts a Python object to an int64.

func AsString

func AsString(o *Object) string

AsString is an alias for Str.

func AsUint

func AsUint(o *Object) uint

AsUint converts a Python object to an unsigned int.

func AsUint64

func AsUint64(o *Object) uint64

AsUint64 converts a Python object to an unsigned int64.

func ClearError

func ClearError()

ClearError clears the last error that occurred in the Python interpreter.

func Finalize

func Finalize()

Finalize finializes the python interpreter.

func IsBool

func IsBool(o PyObjector) bool

IsBool returns true if the object is a Python bool.

func IsFloat

func IsFloat(o PyObjector) bool

IsFloat returns true if the object is a Python float.

func IsInt

func IsInt(o PyObjector) bool

IsInt returns whether the given object is a Python int object.

func IsList

func IsList(o PyObjector) bool

IsList returns true if the object is a tuple.

func IsString

func IsString(o PyObjector) bool

IsString returns true if o is a Python string object.

func IsTuple

func IsTuple(o PyObjector) bool

IsTuple returns true if the object is a tuple.

func LastError

func LastError() error

LastError returns the last error that occurred in the Python interpreter.

func MustSuccess

func MustSuccess()

MustSuccess panics if the last Python operation failed.

func MustUnmarshal

func MustUnmarshal(o *Object, v any)

MustUnmarshal converts the Python object to a value of the same type as v or panics if an error occurs.

func MustUnmarshalAs

func MustUnmarshalAs[T any](o *Object) T

MustUnmarshalAs converts the Python object to a value of the same type as T or panics if an error occurs.

func Str

func Str(o *Object) string

Str returns a string representation of object o.

func TypeName

func TypeName(o *Object) string

TypeName returns the name of the type of the given object.

func Unmarshal

func Unmarshal(o *Object, v any) error

Unmarshal converts the Python object to a value of the same type as v.

func UnmarshalAs

func UnmarshalAs[T any](o *Object) (T, error)

UnmarshalAs converts the Python object to a value of the same type as T.

Types

type AnyList

type AnyList = List[any]

AnyList is a Python tuple.

func NewList

func NewList(length int) *AnyList

NewList creates a new tuple.

func NewListFromAny

func NewListFromAny(values ...any) *AnyList

NewListFromAny converts a slice of any to a tuple.

type AnyTuple

type AnyTuple = Tuple[any]

AnyTuple is a Python tuple.

func NewTuple

func NewTuple(length int) *AnyTuple

NewTuple creates a new tuple.

func NewTupleFromAny

func NewTupleFromAny(values ...any) *AnyTuple

NewTupleFromAny converts a slice of any to a tuple.

type Exception

type Exception struct {
	Message string
}

Exception is a Python exception.

func NewException

func NewException(message string) Exception

NewException creates a new Exception.

func (Exception) Error

func (e Exception) Error() string

Error returns a string representation of the Exception.

type ImportError

type ImportError struct {
	Exception

	Module string
	Path   string
}

ImportError is returned when a Python module cannot be imported.

type IndexError

type IndexError struct {
	Exception
}

IndexError is returned when a sequence subscript is out of range.

type InvalidUnmarshalError

type InvalidUnmarshalError struct {
	Type reflect.Type
}

An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer).

func (*InvalidUnmarshalError) Error

func (e *InvalidUnmarshalError) Error() string

type List

type List[T any] struct {
	// contains filtered or unexported fields
}

List is a generic Python tuple.

func NewListForType

func NewListForType[T any](length int) *List[T]

NewListForType creates a new tuple for a given type.

func NewListFromValues

func NewListFromValues[T any](values ...T) *List[T]

NewListFromValues converts a slice of any data type to a tuple.

func (*List[T]) AsObject

func (l *List[T]) AsObject() *Object

AsObject returns the tuple as Object.

func (*List[T]) AsSlice

func (l *List[T]) AsSlice() []T

AsSlice converts a tuple to a slice.

func (*List[T]) AsTuple

func (l *List[T]) AsTuple() *Tuple[T]

AsTuple converts a list to a tuple.

func (*List[T]) DecRef

func (l *List[T]) DecRef()

DecRef decreases the reference count of the object.

func (*List[T]) Get

func (l *List[T]) Get(index int) T

Get returns the item at index.

func (*List[T]) Length

func (l *List[T]) Length() int

Length returns the length of the tuple.

func (*List[T]) PyObject

func (l *List[T]) PyObject() *cpy3.PyObject

PyObject returns the underlying PyObject.

func (*List[T]) Set

func (l *List[T]) Set(index int, value T)

Set sets the item at index to value.

func (*List[T]) String

func (l *List[T]) String() string

String returns the string representation of the object.

func (*List[T]) UnmarshalPyObject

func (l *List[T]) UnmarshalPyObject(o *Object) error

UnmarshalPyObject unmarshals a Python object to a list.

type ListObject

type ListObject cpy3.PyObject

ListObject is a generic Python tuple.

func NewListObject

func NewListObject(length int) *ListObject

NewListObject creates a new tuple.

func (*ListObject) AsObject

func (o *ListObject) AsObject() *Object

AsObject returns the tuple as Object.

func (*ListObject) AsTuple

func (o *ListObject) AsTuple() *TupleObject

AsTuple converts a list to a tuple.

func (*ListObject) DecRef

func (o *ListObject) DecRef()

DecRef decreases the reference count of the object.

func (*ListObject) Get

func (o *ListObject) Get(index int) *Object

Get returns the item at index.

func (*ListObject) Length

func (o *ListObject) Length() int

Length returns the length of the tuple.

func (*ListObject) PyObject

func (o *ListObject) PyObject() *cpy3.PyObject

PyObject returns the underlying PyObject.

func (*ListObject) Set

func (o *ListObject) Set(index int, value any)

Set sets the item at index to value.

func (*ListObject) String

func (o *ListObject) String() string

String returns the string representation of the object.

type Marshaler

type Marshaler interface {
	MarshalPyObject() *Object
}

Marshaler is the interface implemented by types that can marshal themselves into a Python object.

type ModuleNotFoundError

type ModuleNotFoundError struct {
	ImportError
}

ModuleNotFoundError is returned when a Python module cannot be found.

type Object

type Object cpy3.PyObject

Object is a wrapper around the C type python3.PyObject.

func ImportModule

func ImportModule(name string) (*Object, error)

ImportModule is a wrapper around the C function PyImport_ImportModule.

func Marshal

func Marshal(v any) (*Object, error)

Marshal returns the Python object for v.

func MustImportModule

func MustImportModule(name string) *Object

MustImportModule imports a Python module and panics if it fails.

func MustMarshal

func MustMarshal(v any) *Object

MustMarshal returns the Python object for v or panics if an error occurs.

func NewBool

func NewBool(v bool) *Object

NewBool creates a new Python bool object.

func NewFloat64

func NewFloat64(v float64) *Object

NewFloat64 creates a new Python float object.

func NewInt

func NewInt(v int) *Object

NewInt creates a new Python int object.

func NewInt64

func NewInt64(v int64) *Object

NewInt64 creates a new Python int object.

func NewObject

func NewObject(obj *cpy3.PyObject) *Object

NewObject wraps a python object with convenient methods.

func NewString

func NewString(s string) *Object

NewString creates a new Python string object.

func NewUint

func NewUint(v uint) *Object

NewUint creates a new Python unsigned int object.

func NewUint64

func NewUint64(v uint64) *Object

NewUint64 creates a new Python unsigned int object.

func (*Object) CallMethodArgs

func (o *Object) CallMethodArgs(name string, args ...any) *Object

CallMethodArgs calls a method of the object.

func (*Object) DecRef

func (o *Object) DecRef()

DecRef decreases the reference count of the object.

func (*Object) Equal

func (o *Object) Equal(o2 *Object) bool

Equal returns true if the object is equal to o2.

func (*Object) GetAttr

func (o *Object) GetAttr(name string) *Object

GetAttr returns the attribute value of the object.

func (*Object) GetItem

func (o *Object) GetItem(key any) *Object

GetItem returns the item of the object.

func (*Object) HasItem

func (o *Object) HasItem(value any) bool

HasItem returns true if the object has the item.

func (*Object) Length

func (o *Object) Length() int

Length returns the length of the object.

func (*Object) PyObject

func (o *Object) PyObject() *cpy3.PyObject

PyObject returns the underlying PyObject.

func (*Object) SetAttr

func (o *Object) SetAttr(name string, value any)

SetAttr sets the attribute value of the object.

func (*Object) SetItem

func (o *Object) SetItem(key, value any)

SetItem returns the item of the object.

func (*Object) String

func (o *Object) String() string

String returns the string representation of the object.

func (*Object) Type

func (o *Object) Type() *Object

Type returns the type of the object.

type Objector

type Objector interface {
	AsObject() *Object
}

Objector is an interface for types that can return an Object.

type PyObjector

type PyObjector interface {
	PyObject() *cpy3.PyObject
}

PyObjector is an interface for types that can return a PyObject.

type Tuple

type Tuple[T any] struct {
	// contains filtered or unexported fields
}

Tuple is a generic Python tuple.

func NewTupleForType

func NewTupleForType[T any](length int) *Tuple[T]

NewTupleForType creates a new tuple for a given type.

func NewTupleFromValues

func NewTupleFromValues[T any](values ...T) *Tuple[T]

NewTupleFromValues converts a slice of any data type to a tuple.

func (*Tuple[T]) AsList

func (t *Tuple[T]) AsList() *List[T]

AsList converts a tuple to a list.

func (*Tuple[T]) AsObject

func (t *Tuple[T]) AsObject() *Object

AsObject returns the tuple as Object.

func (*Tuple[T]) AsSlice

func (t *Tuple[T]) AsSlice() []T

AsSlice converts a tuple to a slice.

func (*Tuple[T]) DecRef

func (t *Tuple[T]) DecRef()

DecRef decreases the reference count of the object.

func (*Tuple[T]) Get

func (t *Tuple[T]) Get(index int) T

Get returns the item at index.

func (*Tuple[T]) Length

func (t *Tuple[T]) Length() int

Length returns the length of the tuple.

func (*Tuple[T]) PyObject

func (t *Tuple[T]) PyObject() *cpy3.PyObject

PyObject returns the underlying PyObject.

func (*Tuple[T]) Set

func (t *Tuple[T]) Set(index int, value T)

Set sets the item at index to value.

func (*Tuple[T]) String

func (t *Tuple[T]) String() string

String returns the string representation of the object.

func (*Tuple[T]) UnmarshalPyObject

func (t *Tuple[T]) UnmarshalPyObject(o *Object) error

UnmarshalPyObject unmarshals a Python object to the tuple.

type TupleObject

type TupleObject cpy3.PyObject

TupleObject is a generic Python tuple.

func NewTupleObject

func NewTupleObject(length int) *TupleObject

NewTupleObject creates a new tuple.

func (*TupleObject) AsList

func (o *TupleObject) AsList() *ListObject

AsList converts a tuple to a list.

func (*TupleObject) AsObject

func (o *TupleObject) AsObject() *Object

AsObject returns the tuple as Object.

func (*TupleObject) DecRef

func (o *TupleObject) DecRef()

DecRef decreases the reference count of the object.

func (*TupleObject) Get

func (o *TupleObject) Get(index int) *Object

Get returns the item at index.

func (*TupleObject) Length

func (o *TupleObject) Length() int

Length returns the length of the tuple.

func (*TupleObject) PyObject

func (o *TupleObject) PyObject() *cpy3.PyObject

PyObject returns the underlying PyObject.

func (*TupleObject) Set

func (o *TupleObject) Set(index int, value any)

Set sets the item at index to value.

func (*TupleObject) String

func (o *TupleObject) String() string

String returns the string representation of the object.

type UnmarshalTypeError

type UnmarshalTypeError struct {
	Value  string       // Description of the value - "bool", "array", "number -5".
	Type   reflect.Type // Type of Go value it could not be assigned to.
	Struct string       // Name of the struct type containing the field.
	Field  string       // The full path from root node to the field.
}

An UnmarshalTypeError describes a python Object that was not appropriate for a value of a specific Go type.

func (*UnmarshalTypeError) Error

func (e *UnmarshalTypeError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalPyObject(o *Object) error
}

Unmarshaler is the interface implemented by types that can unmarshal a Python object of themselves.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL