### Example Generated setup.py Source: https://github.com/go-python/gopy/blob/master/_autodocs/configuration.md This is an example of a setup.py file automatically generated by gopy for Python package installation. It is created only if it does not already exist. ```python #!/usr/bin/env python3 # setup.py auto-generated by gopy from setuptools import setup, find_packages setup( name="mylib", version="1.0.0", description="My Go library", author="Jane Doe", author_email="jane@example.com", url="https://example.com/mylib", packages=find_packages(), ext_modules=[Extension("mylib._mylib", sources=[...])], ) ``` -------------------------------- ### Install Gopy Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Install the gopy tool from source. ```bash go install github.com/go-python/gopy@latest ``` -------------------------------- ### Run Go Tests for gopy Examples Source: https://github.com/go-python/gopy/blob/master/README.md Example of how to run Go tests for the gopy examples, typically used for verification. ```sh go test -v -run=TestHi ``` -------------------------------- ### Install gopy and Dependencies Source: https://github.com/go-python/gopy/blob/master/README.md Installs pybindgen, goimports, and gopy using pip and go install. Ensure Go is installed and its bin directory is in your PATH. ```sh python3 -m pip install pybindgen $ go install golang.org/x/tools/cmd/goimports@latest $ go install github.com/go-python/gopy@latest ``` -------------------------------- ### Go Test Package Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Create a minimal Go package to test Gopy generation and isolate issues. This serves as a baseline to verify your Gopy setup. ```go package testpkg func Add(a, b int) int { return a + b } type Counter struct { Value int } func (c *Counter) Increment() { c.Value++ } ``` -------------------------------- ### Complete Gopy Package Command Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/configuration.md This example demonstrates a comprehensive usage of the `gopy pkg` command with multiple flags to configure package name, version, author, description, URL, build tags, and exclusions. ```bash gopy pkg \ -output=/tmp/dist \ -name=mylib \ -vm=python3 \ -version=1.0.0 \ -author="John Doe" \ -email=john@example.com \ -desc="High-performance math library" \ -url=https://github.com/example/mylib \ -rename \ -exclude="vendor,testdata" \ -build-tags="release" \ github.com/example/mylib ``` -------------------------------- ### Verify Gopy Installation Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Run 'gopy help' to confirm the installation. If not found, add the Go binary directory to your PATH. ```bash gopy help ``` ```bash export PATH=$PATH:$HOME/go/bin ``` -------------------------------- ### Go Map Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Demonstrates using Go maps for configuration and accessing them from Python. ```go package mylib // Config represents configuration as a map type Config map[string]string // GetConfig returns the default configuration func GetConfig() Config { return Config{ "host": "localhost", "port": "8080", } } // SetOption sets a configuration option func (c Config) SetOption(key, value string) { c[key] = value } // GetOption gets a configuration option func (c Config) GetOption(key string) string { return c[key] } ``` -------------------------------- ### Verify Go Installation Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Check if Go is installed and its version is compatible. ```bash go version ``` -------------------------------- ### Importing Locally Installed Package Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Demonstrates how to import the Go-based Python package after it has been installed locally. ```python import mylib ``` -------------------------------- ### ResetPackages Usage Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md Demonstrates the usage of the ResetPackages function before processing new packages. ```go bind.ResetPackages() // Now process new packages ``` -------------------------------- ### Go Name Examples Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Examples of Go identifiers, illustrating exported and unexported names. ```text MyFunction, MyType, myPrivate ``` -------------------------------- ### Go Relationship Building Phase Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Demonstrates Phase 3: linking constructors and methods to their respective structs. ```go // Remove constructors from funcs, attach to structs for sname, s := range structs { for name, fct := range funcs { ret := fct.Return() if ret == styp || (retIsPtr && retptr.Elem() == styp) { // This function is a constructor for struct s delete(funcs, name) s.ctors = append(s.ctors, fct) } } // Attach methods to struct for mi := 0; mi < nmeth; mi++ { meth := ntyp.Method(mi) if meth.Exported() { m, _ := newFuncFrom(p, sname, meth, msig) s.meths = append(s.meths, m) } } } ``` -------------------------------- ### Go Slice Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Demonstrates using Go slices and callbacks with Python. ```go package mylib // IntSlice is a type alias for slice of integers type IntSlice []int // Sum returns the sum of all integers in the slice func Sum(nums []int) int { total := 0 for _, n := range nums { total += n } return total } // Filter returns numbers that pass the test function func Filter(nums []int, fn func(int) bool) []int { var result []int for _, n := range nums { if fn(n) { result = append(result, n) } } return result } ``` -------------------------------- ### Install Build Tools (Linux) Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Installs essential build tools on Linux, including `make`, `gcc`, and other utilities required for compiling C/Go code. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Go Interface Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Demonstrates defining and using Go interfaces with Python. ```go package mylib // Reader defines something that can read data type Reader interface { Read(size int) (string, error) } // FileReader reads from a file type FileReader struct { filename string } func NewFileReader(filename string) *FileReader { return &FileReader{filename: filename} } func (fr *FileReader) Read(size int) (string, error) { // Simulated implementation return "data from " + fr.filename, nil } // ProcessReader reads data using a Reader interface func ProcessReader(r Reader, size int) string { data, err := r.Read(size) if err != nil { return "Error: " + err.Error() } return "Read: " + data } ``` -------------------------------- ### Install Python Packaging Tools Source: https://github.com/go-python/gopy/blob/master/README.md Installs or upgrades setuptools and wheel for Python module packaging. This is a prerequisite for building and distributing Python packages. ```sh python3 -m pip install --upgrade setuptools wheel ``` -------------------------------- ### Install Python Development Headers (macOS) Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Install Python development headers using Homebrew. ```bash brew install python3 ``` -------------------------------- ### Creating Wheel Distribution Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Build a wheel distribution for the Go-based Python package and install it using pip. ```bash cd /tmp/dist/mylib python setup.py bdist_wheel pip install dist/mylib-1.0.0-py3-none-linux_x86_64.whl ``` -------------------------------- ### Local Python Package Installation Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Install the generated Go-based Python package locally in editable mode using pip. ```bash cd /tmp/dist/mylib pip install -e . ``` -------------------------------- ### Build Go Package for Python using gopy CLI Source: https://github.com/go-python/gopy/blob/master/README.md Demonstrates the command-line steps to initialize a Go module, get a package, and build it for Python using gopy. ```sh $ go mod init dummy.com/dum $ go get github.com/go-python/gopy/_examples/hi $ gopy build -output=out -vm=python3 github.com/go-python/gopy/_examples/hi $ ls out ``` -------------------------------- ### Installing Build Tools Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Resolve 'Makefile.*: command not found' errors by installing essential build tools like `make` and compilers on various operating systems. ```bash # Ubuntu/Debian: sudo apt-get install build-essential # macOS: xcode-select --install # Windows: # Install MinGW or use MSVC ``` -------------------------------- ### Display gopy help Source: https://github.com/go-python/gopy/blob/master/README.md Run the 'gopy help' command to see a list of available commands and a brief description of each. Use this to get an overview of gopy's capabilities. ```sh $ gopy help gopy - Commands: pkg generate and compile Python bindings for Go, automatically including subdirs also creates all the python files needed to install module exe like pkg but makes a standalone executable with Go packages bultin this is particularly useful when using -main arg to start process on gen generate (C)Python language bindings for Go build generate and compile main thread -- python interpreter can run on another thread. Use "gopy help " for more information about a command. ``` -------------------------------- ### Python Name Transformation Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Shows how Go names are optionally transformed into Pythonic names using the '-rename' flag. ```text MyFunction → my_function (with -rename) MyType → MyType (unchanged) myPrivate → not exported ``` -------------------------------- ### Verify Build Tools Installation Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Check if essential build tools like gcc and make are installed. ```bash gcc --version make --version ``` -------------------------------- ### Install Python Development Headers (Linux) Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Ensures that the necessary Python development headers are installed on your Linux system, which is crucial for compiling Go code that interfaces with Python. ```bash sudo apt-get install python3-dev ``` -------------------------------- ### ErrorList Example Output Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Shows an example of how multiple errors are accumulated and reported together using an `ErrorList` in GoPy. This helps in diagnosing complex build failures. ```text multiple errors: - unsupported parameter type: chan int - unsupported return type: unsafe.Pointer - method lacks exported receiver ``` -------------------------------- ### Go Type Discovery Phase Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Code snippet demonstrating Phase 1 of the type processing flow: discovering exported names in a package scope. ```go scope := p.pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if !obj.Exported() { continue // Skip private } p.n++ p.syms.addSymbol(obj) } ``` -------------------------------- ### Verify Python 3 Installation Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Check if Python 3 and pip are installed. ```bash python3 --version python3 -m pip --version ``` -------------------------------- ### Python: Simple Object Lifetime Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/memory-management.md Illustrates the lifecycle of a Go object created from Python. It shows object creation, usage, and deletion, and how the handle table and reference counts evolve. ```python import mylib # Create object (allocates in Go, creates handle 1001, refcount = 1) person = mylib.NewPerson("Alice") # Use object name = person.Name # Delete Python reference (refcount = 0, handle freed, Go memory freed) del person ``` -------------------------------- ### Example Commit Message: Implementing Interface Wrapping Source: https://github.com/go-python/gopy/blob/master/CONTRIBUTE.md This commit message shows how to describe changes that affect multiple packages, such as implementing the wrapping of Go interfaces. ```git py,bind: implement wrapping of Go interfaces bla-bla Fixes go-python/gopy#40. ``` -------------------------------- ### ErrorList Usage Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md Illustrates how to use the ErrorList to collect and report multiple errors. If any errors are added, the combined error is logged fatally. ```go var errs bind.ErrorList errs.Add(err1) errs.Add(err2) if len(errs) > 0 { log.Fatal(errs.Error()) } ``` -------------------------------- ### Gopy Multi-Package Invocation Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Command-line example for invoking Gopy to process multiple Go packages simultaneously. ```bash gopy gen pkg1 pkg2 pkg3 ``` -------------------------------- ### Pkg Command Workflow Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Outlines the steps for the 'pkg' command, focusing on Python package setup, recursive directory processing, and compilation. ```text pkg command invoked ↓ gopyRunCmdPkg() called ↓ Parse flags including: user, version, author, email, desc, url, exclude ↓ Validate arguments ↓ Create output directory (if needed) ↓ Create setup.py (if doesn't exist) via GenPyPkgSetup() ↓ Set output directory to subdir (output/name) ↓ Recursively process packages: - buildPkgRecurse() for each directory - Load packages (skip excluded dirs) - Parse packages ↓ runBuild("pkg", cfg) ↓ Generate all files ↓ Compile via Makefile ↓ Return success ``` -------------------------------- ### Example go.mod Configuration Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md A go.mod file is required for module-based projects to enable gopy to properly resolve and build packages. Ensure the Go version and gopy dependency are correctly specified. ```go module example.com/mymodule go 1.15 require github.com/go-python/gopy v1.0.0 ``` -------------------------------- ### Example Commit Message: Adding CFFI Support Source: https://github.com/go-python/gopy/blob/master/CONTRIBUTE.md This commit message demonstrates how to announce the addition of a new backend, specifying the affected packages and referencing related issues. ```git bind: add support for cffi This CL adds support for the cffi python backend. The existing implementation, cpython, only generates code for the CPython-2 C API. Now, with cffi, we support generation of python modules for Python-2, Python-3 and PyPy VMs. Fixes go-python/gopy#42. ``` -------------------------------- ### Install Python 3.10 (macOS) Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Installs a specific version of Python (3.10) using Homebrew on macOS. This is often necessary when dealing with version-specific compatibility issues. ```bash brew install python@3.10 ``` -------------------------------- ### Go Code with Build Tags Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Example of Go code that is conditionally compiled based on build tags specified during the `gopy gen` process. ```go //go:build experimental // +build experimental func ExperimentalFeature() string { return "only available in experimental build" } ``` -------------------------------- ### Creating a Python Package with gopy pkg Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Use the `gopy pkg` command to generate a complete Python package structure, including setup files and compiled Go extensions. ```bash gopy pkg \ -output=/tmp/dist \ -name=mylib \ -version=1.0.0 \ -author="John Doe" \ -email=john@example.com \ -desc="My Go library" \ -url=https://github.com/example/mylib \ example.com/mylib ``` -------------------------------- ### Go Callback Function Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/supported-types.md Defines a Go function 'Process' that accepts a slice of integers and a callback function. The callback is used to conditionally process items in the slice. ```go func Process(items []int, fn func(int) bool) { for _, item := range items { if fn(item) { // use item } } } ``` -------------------------------- ### Go Interface and Implementation Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Shows a Go Writer interface with a Write method and a FileWriter struct that implements this interface. This example illustrates interface translation to Python classes. ```go type Writer interface { Write(p []byte) (int, error) } type FileWriter struct { path string } func (fw *FileWriter) Write(p []byte) (int, error) { // implementation } ``` ```python class Writer: def Write(self, p: bytes) -> Tuple[int, error]: pass class FileWriter: path: str def Write(self, p: bytes) -> Tuple[int, error]: pass ``` -------------------------------- ### Display gopy exe command help Source: https://github.com/go-python/gopy/blob/master/README.md Use 'gopy help exe' to get detailed usage information for the 'exe' command, including its arguments and available options. This command generates standalone Python executables with Go packages built-in. ```sh $ gopy help exe Usage: gopy exe [other-go-package...] exe generates and compiles (C)Python language bindings for a Go package, including subdirectories, and generates a standalone python executable and associated module packaging suitable for distribution. if setup.py file does not yet exist in the target directory, then it along with other default packaging files are created, using arguments. Typically you create initial default versions of these files and then edit them, and after that, only regenerate the Go binding files. The primary need for an exe instead of a pkg dynamic library is when the main thread must be used for something other than running the python interpreter, such as for a GUI library where the main thread must be used for running the GUI event loop (e.g., GoGi). ex: $ gopy exe [options] [other-go-package...] $ gopy exe github.com/go-python/gopy/_examples/hi Options: -author="gopy": author name -desc="": short description of project (long comes from README.md) -email="gopy@example.com": author email -exclude="": comma-separated list of package names to exclude -main="": code string to run in the Go main() function in the cgo library -- defaults to GoPyMainRun() but typically should be overriden -name="": name of output package (otherwise name of first package is used) -output="": output directory for root of package ``` -------------------------------- ### Verify Goimports and GCC Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Checks if `goimports` and `gcc` are installed and accessible in your system's PATH. These are common dependencies for Go projects. ```bash goimports -v ``` ```bash gcc --version ``` -------------------------------- ### Display gopy pkg command help Source: https://github.com/go-python/gopy/blob/master/README.md Use 'gopy help pkg' to get detailed usage information for the 'pkg' command, including its arguments and available options. This command generates Python bindings for Go packages. ```sh $ gopy help pkg Usage: gopy pkg [other-go-package...] pkg generates and compiles (C)Python language bindings for a Go package, including subdirectories, and generates python module packaging suitable for distribution. if setup.py file does not yet exist in the target directory, then it is created along with other default packaging files, using arguments. Typically you create initial default versions of these files and then edit them, and after that, only regenerate the Go binding files. ex: $ gopy pkg [options] [other-go-package...] $ gopy pkg github.com/go-python/gopy/_examples/hi Options: -author="gopy": author name -desc="": short description of project (long comes from README.md) -email="gopy@example.com": author email -exclude="": comma-separated list of package names to exclude -main="": code string to run in the Go GoPyInit() function in the cgo library -name="": name of output package (otherwise name of first package is used) -output="": output directory for root of package -symbols=true: include symbols in output -url="https://github.com/go-python/gopy": home page for project -user="": username on https://www.pypa.io/en/latest/ for package name suffix -version="0.1.0": semantic version number -- can use e.g., git to get this from tag and pass as argument -vm="python": path to python interpreter -dynamic-link=false: whether to link output shared library dynamically to Python -build-tags="": build tags to be passed to `go build` ``` -------------------------------- ### Go Type Classification Phase Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Illustrates Phase 2 of type processing, classifying discovered symbols into different Go types like Const, Var, Func, Struct, and Interface. ```go switch obj := obj.(type) { case *types.Const: p.addConst(obj) case *types.Var: p.addVar(obj) case *types.Func: fv, err := newFuncFrom(p, "", obj, obj.Type().(*types.Signature)) funcs[name] = fv case *types.TypeName: // Classify type switch typ := typ.(type) { case *types.Struct: sv, err := newStruct(p, obj) structs[name] = sv case *types.Interface: iv, err := newInterface(p, obj) ifaces[name] = iv // ... more type cases } } ``` -------------------------------- ### Get Python Configuration Variables (macOS) Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Retrieves configuration variables for a specific Python installation on macOS, which can be useful for diagnosing linking or path issues. ```bash /usr/local/opt/python@3.10/bin/python3 --config-vars ``` -------------------------------- ### Example gopy gen Command Invocation Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md This snippet shows a typical invocation of the `gopy gen` command to generate Python bindings for Go packages. It includes common flags for specifying the Python VM, output directory, library name, package prefix, renaming behavior, and build tags. ```bash gopy gen \ -vm=python3 \ -output=/tmp/out \ -name=mylib \ -package-prefix=mylib \ -rename \ -build-tags="debug" \ github.com/example/lib1 \ github.com/example/lib2 ``` -------------------------------- ### Complex Type Usage Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/supported-types.md Illustrates the usage of Go structs, methods, interfaces, and functions with Python. This includes creating instances, calling methods, and passing Python callables to Go functions. ```go package mylib type User struct { ID int Name string } func NewUser(name string) *User { return &User{ID: 0, Name: name} } func (u *User) DisplayName() string { return fmt.Sprintf("User: %s (#%d)", u.Name, u.ID) } type Repository interface { GetUser(id int) (*User, error) SaveUser(u *User) error } func ProcessUsers(repo Repository, filter func(*User) bool) int { // ... } ``` ```python import mylib # Create instance user = mylib.NewUser("Alice") print(user.DisplayName()) # With custom filter def is_named_alice(u): return u.Name == "Alice" count = mylib.ProcessUsers(my_repo, is_named_alice) ``` -------------------------------- ### Set GOPY_LIBDIR and GOPY_PYLIB (Windows) Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Configures GoPy's library directory and Python library name on Windows. Ensure `C:\Python39\libs` points to your actual Python installation's libs directory. ```bash set GOPY_LIBDIR=C:\Python39\libs set GOPY_PYLIB=python39 ``` -------------------------------- ### ModePkg Build Process Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Flowchart for ModePkg, detailing the process from input parsing to generating a Python package structure with a setup.py file. ```text Input → Parse → Generate → Compile → Package files → setup.py ``` -------------------------------- ### Initialize Go Module Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Create a new directory for your Go package and initialize a Go module. ```bash mkdir mylib cd mylib go mod init example.com/mylib ``` -------------------------------- ### Compile Bindings Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Navigate to the output directory and run 'make' to compile the bindings. ```bash cd out make ``` -------------------------------- ### Install psutil for Windows Testing Source: https://github.com/go-python/gopy/blob/master/README.md Installs the psutil package for memory tracking on Windows. This is required for tests that check memory leaks, as Python's built-in 'resource' module is Unix-specific. ```sh python -m pip install psutil ``` -------------------------------- ### GenPyPkgSetup() Function Signature Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Signature for the GenPyPkgSetup helper function, used to create setup.py and related files for Python packages. ```go func GenPyPkgSetup(cfg *BuildCfg, user, version, author, email, desc, url string) error ``` -------------------------------- ### Build Command Workflow Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Details the execution flow for the 'build' command, including package loading, generation, and compilation via Makefile. ```text build command invoked ↓ gopyRunCmdBuild() called ↓ Parse flags ↓ Validate arguments ↓ For each package: - loadPackage(path, buildFirst=true, buildTags) - parsePackage(bpkg) ↓ runBuild("build", cfg) ↓ genPkg(ModeBuild, cfg) ↓ bind.GenPyBind(...) called ↓ Generate source files ↓ Compile via Makefile ↓ Return success ``` -------------------------------- ### Create a Python package with custom output and version Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'pkg' command to generate a Python package. Specify the output directory and the package version. ```bash gopy pkg -output=/tmp/dist -version=1.0.0 github.com/example/mylib ``` -------------------------------- ### Cross-Platform Binding Generation with Docker Source: https://github.com/go-python/gopy/blob/master/README.md Demonstrates using a Docker container to perform cross-platform builds of Go packages for Python. ```sh $ cd github.com/go-python/gopy/_examples/hi $ docker run --rm -v `pwd`:/go/src/in -v `pwd`:/out gopy/gopy app bind -output=/out in $ file hi.so ``` -------------------------------- ### Provide Go Package Name Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Demonstrates the correct way to provide a Go package import path as an argument to `gopy gen`. This is a required argument. ```bash gopy gen github.com/example/mylib ``` -------------------------------- ### Go Struct Embedding for Inheritance Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Example of Go struct embedding, demonstrating how Gopy translates this into Python class inheritance. ```go type Animal struct { Name string } type Dog struct { Animal // embedded Breed string } ``` -------------------------------- ### Go Embedded Struct Detection Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Code snippet demonstrating how to detect if the first field of a Go struct is an embedded field. ```go func (s *Struct) FirstEmbed() *symbol { st := s.Struct() if st.NumFields() == 0 { return nil } f := st.Field(0) if !f.Embedded() { // Check if embedded (no name) return nil } return current.symtype(f.Type()) } ``` -------------------------------- ### ModeBuild Build Process Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Diagram illustrating the build steps for ModeBuild, which includes generating and compiling source files into an extension module. ```text Input → Parse → Generate → Compile → .so/.pyd ``` -------------------------------- ### Create a Python package with PyPI user and version Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'pkg' command to generate a Python package. Specify a PyPI username suffix and the package version. ```bash gopy pkg -user=mydomain -version=2.0.0 github.com/example/mylib ``` -------------------------------- ### Moving Compiled Library to Site-Packages Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Resolve import errors by manually copying the compiled Go extension (`.so` file) and Python wrapper to the Python site-packages directory. ```bash cp out/_mylib.so /usr/local/lib/python3.10/site-packages/ cp out/mylib.py /usr/local/lib/python3.10/site-packages/ ``` -------------------------------- ### Python Usage of Go Map Functions Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Shows how to interact with Go maps (as Python dictionaries) for configuration. ```python import mylib cfg = mylib.GetConfig() print(cfg["host"]) # localhost cfg.SetOption("debug", "true") print(cfg["debug"]) # true ``` -------------------------------- ### Gopy Generate Command Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Use this command to generate Go-Python bindings for a test package. It helps verify if your Gopy installation and basic environment are working correctly. ```bash gopy gen -output=/tmp/test github.com/example/testpkg ``` -------------------------------- ### Invalid Flag Example: Symbols Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Illustrates an invalid flag value for the `-symbols` flag, which expects a boolean but is given a string. This will cause a flag parsing error. ```bash gopy gen -symbols=maybe ``` -------------------------------- ### Build gopy Docker Image Locally Source: https://github.com/go-python/gopy/blob/master/README.md Shows the commands to build the gopy Docker image on a local machine. ```sh $ cd $GOPATH/src/github.com/go-python/gopy $ docker build -t go-python/gopy . $ docker run -it --rm go-python/gopy ``` -------------------------------- ### Unsupported Type: Unexported Field Example Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Gopy may encounter issues with unexported fields. Make fields public or use accessor methods to resolve. ```Go // Bad: unexported field type Config struct { secret string // private } // Good: make public or use accessor type Config struct { Secret string // public } func (c *Config) GetSecret() string { // accessor method return c.Secret } ``` -------------------------------- ### Exe Command Workflow Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Describes the execution path for the 'exe' command, similar to 'pkg' but without package prefixes, for creating executables. ```text exe command invoked ↓ gopyRunCmdExe() called ↓ Parse flags (same as pkg, no package-prefix) ↓ Validate arguments ↓ Create output directory (if needed) ↓ Create setup.py (if doesn't exist) ↓ Set output directory to subdir (output/name) ↓ Recursively process packages (like pkg command) ↓ runBuild("exe", cfg) ↓ Generate all files ↓ Compile via Makefile ↓ Return success ``` -------------------------------- ### Main Entry Point Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md The main function serves as the primary entry point for the CLI application. It calls the run function with command-line arguments and handles fatal errors. ```go func main() { err := run(os.Args[1:]) if err != nil { log.Fatal(err) } os.Exit(0) } ``` -------------------------------- ### Create a Python package with custom author and email Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'pkg' command to generate a Python package. Customize author and email metadata. ```bash gopy pkg -author="John Doe" -email=john@example.com github.com/example/mylib ``` -------------------------------- ### Global Flags in Bind Package Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Demonstrates how module-level variables in the bind package can control global behavior like warning suppression and Makefile generation. ```go bind.NoWarn = cfg.NoWarn // Suppress warnings bind.NoMake = cfg.NoMake // Skip Makefile generation bind.WindowsOS = false // Set on Windows ``` -------------------------------- ### Struct Field Access in Python Source: https://github.com/go-python/gopy/blob/master/_autodocs/supported-types.md Shows how exported struct fields in Go are exposed as instance attributes in Python. This allows direct access for getting and setting values. ```go type Config struct { Timeout time.Duration Debug bool } c := NewConfig() ``` ```python c = Config() c.Timeout = 30 # Set field print(c.Debug) # Get field ``` -------------------------------- ### Custom Initialization Code with gopy gen Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Execute custom Go code upon Python module import by providing it to the `-main` flag in `gopy gen`. ```bash gopy gen -main='initLogging(); setupWorkers()' example.com/mylib ``` -------------------------------- ### ModeExe Build Process Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Visual representation of the ModeExe build process, which generates, compiles, and packages Go code into a standalone executable. ```text Input → Parse → Generate → Compile → Package files → Executable ``` -------------------------------- ### NewPackage Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md Creates a new Package object from Go's type and documentation information. This is the entry point for analyzing a Go package for binding generation. ```APIDOC ## NewPackage ### Description Creates a new Package from a `types.Package` and `doc.Package`. This function initializes the binding generation process for a given Go package. ### Signature ```go func NewPackage(pkg *types.Package, doc *doc.Package) (*Package, error) ``` ### Parameters #### Path Parameters - **pkg** (*types.Package) - Type information from Go's type analysis - **doc** (*doc.Package) - Documentation extracted from comments ### Returns - **(*Package)**: Newly created package with all symbols processed - **error**: Non-nil if package processing fails (e.g., unsupported types) ### Example ```go import ( "go/types" "go/doc" "github.com/go-python/gopy/bind" ) func parseGoPackage(pkg *types.Package, doc *doc.Package) { bindPkg, err := bind.NewPackage(pkg, doc) if err != nil { log.Fatalf("failed to create package: %v", err) } // Use bindPkg for further processing } ``` ``` -------------------------------- ### Inject Go Code into Main/GoPyInit Source: https://github.com/go-python/gopy/blob/master/_autodocs/configuration.md Provides Go code to be injected into the generated `main()` or `GoPyInit()` function using the `-main` CLI flag. This is useful for initialization tasks. ```bash gopy gen -main="initialize(); setupLogging()" github.com/example/mylib ``` -------------------------------- ### Gopy Configuration Propagation Flow Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Illustrates the flow of configuration from CLI flags to build configuration, then to binding configuration, and finally to code generators. Configuration is immutable during generation. ```text CLI Flags ↓ BuildCfg → BindCfg ↓ genPkg() ↓ GenPyBind() ↓ Code generators (access cfg fields) ``` -------------------------------- ### gopy Command Reference Source: https://github.com/go-python/gopy/blob/master/_autodocs/README.md Common commands for generating, building, packaging, and executing Go code for Python. ```bash gopy gen -vm=python3 -output=out github.com/example/lib ``` ```bash gopy build -rename github.com/example/lib ``` ```bash gopy pkg -version=1.0.0 -author="Name" github.com/example/lib ``` ```bash gopy exe -main="startApp()" github.com/example/lib ``` -------------------------------- ### Command Registration Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md The run function initializes a commander.Command object and registers all subcommands. It parses flags and dispatches the appropriate command based on the provided arguments. ```go func run(args []string) error { app := &commander.Command{ UsageLine: "gopy", Subcommands: []*commander.Command{ gopyMakeCmdGen(), gopyMakeCmdBuild(), gopyMakeCmdPkg(), gopyMakeCmdExe(), }, Flag: *flag.NewFlagSet("gopy", flag.ExitOnError), } err := app.Flag.Parse(args) if err != nil { return fmt.Errorf("could not parse flags: %v", err) } appArgs := app.Flag.Args() err = app.Dispatch(appArgs) if err != nil { return fmt.Errorf("error dispatching command: %v", err) } return nil } ``` -------------------------------- ### Enabling Handle Tracking Debugging Source: https://github.com/go-python/gopy/blob/master/_autodocs/memory-management.md Instructions on how to enable detailed handle allocation and deallocation logging by setting the `GOPY_DEBUG_HANDLES` environment variable. ```bash GOPY_DEBUG_HANDLES=1 python3 script.py ``` -------------------------------- ### Load Go Package Directly from Python Shell using gopy Source: https://github.com/go-python/gopy/blob/master/README.md Illustrates using the `gopy.load` function within a Python shell to dynamically load and interact with a Go package. ```python >>> import gopy >>> hi = gopy.load("github.com/go-python/gopy/_examples/hi") gopy> inferring package name... gopy> loading 'github.com/go-python/gopy/_examples/hi'... gopy> importing 'github.com/go-python/gopy/_examples/hi'... >>> print hi >>> print hi.__doc__ package hi exposes a few Go functions to be wrapped and used from Python. ``` -------------------------------- ### Gen Command Workflow Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Illustrates the sequence of operations when the 'gen' command is invoked, from parsing flags to generating Python bindings. ```text gen command invoked ↓ gopyRunCmdGen() called ↓ Parse flags ↓ Validate arguments (package names required) ↓ For each package: - loadPackage(path, buildFirst=true, buildTags) - parsePackage(bpkg) - Update config name if needed ↓ genPkg(ModeGen, cfg) ↓ bind.GenPyBind(...) called ↓ Generate source files ↓ Return success ``` -------------------------------- ### Python Usage of Go Interface Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Shows how to create a concrete Go type and pass it to a function expecting an interface. ```python import mylib # Create a concrete implementation reader = mylib.NewFileReader("data.txt") # Pass to function that expects Reader interface result = mylib.ProcessReader(reader, 100) print(result) ``` -------------------------------- ### ModeGen Build Process Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Diagram showing the input-to-output flow for the ModeGen build mode, which focuses solely on source file generation. ```text Input → Parse → Generate → Output files ``` -------------------------------- ### NewPackage Function Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md Creates a new Package object from Go's type and documentation information. Use this to initialize the binding process for a Go package. It returns an error if package processing fails due to unsupported types. ```go import ( "go/types" "go/doc" "github.com/go-python/gopy/bind" ) func parseGoPackage(pkg *types.Package, doc *doc.Package) { bindPkg, err := bind.NewPackage(pkg, doc) if err != nil { log.Fatalf("failed to create package: %v", err) } // Use bindPkg for further processing } ``` -------------------------------- ### Create Output Directory Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Ensures that the parent directory for the specified output path exists. Use the `-p` flag to create parent directories as needed. ```bash mkdir -p /tmp/mylib ``` -------------------------------- ### Importing with Custom Package Name Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Demonstrates how to import a Go package in Python when a custom name has been specified during generation with `gopy gen`. ```python import myalias ``` -------------------------------- ### Build Go Package for Python Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Command to build a Go package for Python using gopy. Specify the target Python VM and output directory. ```bash gopy build -vm=python3 -output=out github.com/example/mylib ``` -------------------------------- ### Clean Rebuild Procedure Source: https://github.com/go-python/gopy/blob/master/_autodocs/errors.md Perform a clean rebuild by removing all previous output and then rebuilding the specified Go package. This is useful for resolving issues caused by stale build artifacts. ```bash rm -rf /tmp/output/* gopy build -output=/tmp/output github.com/example/mylib ``` -------------------------------- ### Test Generated Bindings Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Import and use the generated Go bindings in a Python script. ```python import sys sys.path.insert(0, '/path/to/out') import mylib # Call functions print(mylib.Hello("World")) # Hello, World! print(mylib.Add(2, 3)) # 5 # Create objects p = mylib.NewPerson("Alice", 30) print(p.Greet()) # Hi! I'm Alice print(p.Name) # Alice print(p.Age) # 30 ``` -------------------------------- ### Provide Short Package Description Source: https://github.com/go-python/gopy/blob/master/_autodocs/configuration.md Use the -desc flag to provide a short description for the package. If this flag is empty, gopy will attempt to read a long description from README.md in the package directory. ```bash gopy pkg -desc="Fast math library" github.com/example/mylib ``` -------------------------------- ### Build Configuration Source: https://github.com/go-python/gopy/blob/master/_autodocs/INDEX.md Extended configuration structure including build options. ```APIDOC ## BuildCfg ### Description Extended configuration structure that includes build options, inheriting from `BindCfg`. ### Type `BuildCfg` ### Package main ``` -------------------------------- ### Inspecting Active Handles in Python Source: https://github.com/go-python/gopy/blob/master/_autodocs/memory-management.md Demonstrates how to use `mylib.NumHandles()` to inspect the number of active object handles before and after creating and deleting objects. ```python import mylib print("Active handles:", mylib.NumHandles()) # Create and observe obj = mylib.NewObject() print("After creation:", mylib.NumHandles()) del obj print("After deletion:", mylib.NumHandles()) ``` -------------------------------- ### Package Methods Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md Provides methods to retrieve information about a Go package after it has been processed by `NewPackage`. ```APIDOC ## Package Methods ### Name Returns the Go package name. #### Signature ```go func (p *Package) Name() string ``` #### Returns - `string`: The exported package name (e.g., `"mylib"`) ### ImportPath Returns the full import path of the package. #### Signature ```go func (p *Package) ImportPath() string ``` #### Returns - `string`: The import path (e.g., `"github.com/example/mylib"`) ### AddPyImport Registers a Python import statement needed by this package. #### Signature ```go func (p *Package) AddPyImport(ipath string, extra bool) ``` #### Parameters - **ipath** (string) - Import path to add - **extra** (bool) - Whether this is an extra/incidental import ### Lookup Finds an Object (function, type, constant, etc.) in the package by name. #### Signature ```go func (p *Package) Lookup(o types.Object) (Object, bool) ``` #### Parameters - **o** (types.Object) - Go type object to look up #### Returns - **Object**: The bind package's representation of the symbol - **bool**: True if found, false otherwise ``` -------------------------------- ### Go Zero Values and Python Equivalents Source: https://github.com/go-python/gopy/blob/master/_autodocs/supported-types.md Demonstrates how Go zero values for various types are represented in Python. This includes strings, integers, pointers, slices, and maps. ```go var s string // "" in Python var i int // 0 in Python var p *MyType // None in Python var sl []int // empty list in Python var m map[K]V // empty dict in Python ``` -------------------------------- ### Custom Preprocessing in Go Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md This Go code snippet demonstrates how to add custom preprocessing logic before the `parsePackage` function is called. It shows loading a package and then manually parsing it after potential custom modifications. ```go bpkg, _ := loadPackage(path, true, buildTags) // Custom preprocessing pkg, _ := parsePackage(bpkg) ``` -------------------------------- ### Python Usage of Go Callback Source: https://github.com/go-python/gopy/blob/master/_autodocs/supported-types.md Demonstrates how to define a Python callback function and pass it to the Go 'Process' function. The 'is_even' function serves as the callback. ```python def is_even(x): return x % 2 == 0 Process([1, 2, 3, 4], is_even) ``` -------------------------------- ### Go API for Creating a New Package Source: https://github.com/go-python/gopy/blob/master/_autodocs/README.md Function signature for creating a new Go package representation for Python binding. ```go func NewPackage(pkg *types.Package, doc *doc.Package) (*Package, error) ``` -------------------------------- ### runBuild() Function Signature Source: https://github.com/go-python/gopy/blob/master/_autodocs/cli-structure.md Signature for the runBuild helper function, orchestrating package generation and compilation. ```go func runBuild(mode bind.BuildMode, cfg *BuildCfg) error ``` -------------------------------- ### Generate a standalone Python executable with a specified version Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'exe' command to create a standalone Python executable. Specify the package version. ```bash gopy exe -version=1.0.0 github.com/example/tui ``` -------------------------------- ### Generate Go Bindings Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Use gopy to generate Python bindings for the Go package. ```bash gopy gen -output=out -vm=python3 example.com/mylib ``` -------------------------------- ### Generate Python Bindings for Go Package Source: https://github.com/go-python/gopy/blob/master/_autodocs/bind-api.md This Go code snippet demonstrates the workflow for generating Python bindings from a Go package using the GoPy library. It includes loading the package, creating documentation, and configuring the binding generation process. ```go import ( "go/doc" "go/types" "golang.org/x/tools/go/packages" "github.com/go-python/gopy/bind" ) func generateBindings(pkgPath string) error { // Load package cfg := &packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo} pkgs, err := packages.Load(cfg, pkgPath) if err != nil { return err } pkg := pkgs[0] // Create doc docPkg := doc.New(/* ast, path, etc */) // Create bind package bindPkg, err := bind.NewPackage(pkg.Types, docPkg) if err != nil { return err } // Generate bindings cfg := &bind.BindCfg{ OutputDir: "./out", Name: "mymodule", VM: "/usr/bin/python3", } return bind.GenPyBind( bind.ModeBuild, ".so", "", 3, false, cfg, ) } ``` -------------------------------- ### Build Python Extension Module with Gopy Build Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'build' command to generate and compile Python bindings into a shared library. This command includes compilation, unlike 'gen'. ```bash gopy build -vm=python3 -output=out github.com/example/mylib ``` ```bash gopy build -symbols github.com/example/mylib ``` ```bash gopy build -dynamic-link github.com/example/mylib ``` -------------------------------- ### Go Symbol Table Methods Source: https://github.com/go-python/gopy/blob/master/_autodocs/type-system.md Key methods for the 'symtab' struct, used for managing and retrieving type information. ```go func (tab *symtab) symtype(typ types.Type) *symbol func (tab *symtab) addSymbol(obj types.Object) func (tab *symtab) addType(name string, typ types.Type) *symbol ``` -------------------------------- ### Handle-Based Memory Management in Gopy Source: https://github.com/go-python/gopy/blob/master/_autodocs/architecture.md Illustrates Gopy's handle-based approach for managing memory and object references across Python and Go, ensuring safety and GC compatibility. ```text Python ──int64 handle──> Go Handle Table ├─ handle 1 → *MyType ├─ handle 2 → *OtherType └─ handle 3 → *MyType (with reference counting) ``` -------------------------------- ### Set Output Directory via CLI Source: https://github.com/go-python/gopy/blob/master/_autodocs/configuration.md Specifies the directory where generated bindings will be written using the `-output` CLI flag. The directory is created if it does not exist. ```bash gopy build -output=/tmp/mylib github.com/example/mylib ``` -------------------------------- ### Generate a standalone Python executable with embedded Go code Source: https://github.com/go-python/gopy/blob/master/_autodocs/commands.md Use the 'exe' command to create a standalone Python executable. Provide custom Go code for the main function and specify the output directory. ```bash gopy exe -main="GoPyMainRun()" -output=/tmp/dist github.com/example/gui ``` -------------------------------- ### Standard Copyright Header for New Files Source: https://github.com/go-python/gopy/blob/master/CONTRIBUTE.md This is the standard copyright header to be included in new files contributed to the go-python repository. ```go // Copyright 20xx The go-python Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. ``` -------------------------------- ### Python Usage of Go Slice Functions Source: https://github.com/go-python/gopy/blob/master/_autodocs/usage-guide.md Shows how Python lists are used with Go slice functions and how Go callbacks work. ```python import mylib # Lists work seamlessly print(mylib.Sum([1, 2, 3, 4, 5])) # 15 # Callbacks work! def is_even(x): return x % 2 == 0 evens = mylib.Filter([1, 2, 3, 4, 5, 6], is_even) print(evens) # [2, 4, 6] ``` -------------------------------- ### NewPackage Function Source: https://github.com/go-python/gopy/blob/master/_autodocs/INDEX.md Creates a Package object from Go types. ```APIDOC ## NewPackage() ### Description Creates a new `Package` object, which represents a parsed Go package, from the provided Go types. ### Signature `NewPackage()` ### Package bind ```