### Create and Use Python Set in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Illustrates creating a set, adding elements (duplicates are ignored), creating from a slice, checking for membership, and getting the count of unique elements. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a new empty Set s := types.NewSet() // Add elements s.Add("apple") s.Add("banana") s.Add("cherry") s.Add("apple") // Duplicates are ignored // Create from slice s2 := types.NewSetFromSlice([]interface{}{1, 2, 3, 2, 1}) // Check membership fmt.Printf("Has 'apple': %v\n", s.Has("apple")) // Output: Has 'apple': true fmt.Printf("Has 'orange': %v\n", s.Has("orange")) // Output: Has 'orange': false // Get length (unique elements only) fmt.Printf("Length: %d\n", s.Len()) // Output: Length: 3 fmt.Printf("Length: %d\n", s2.Len()) // Output: Length: 3 // Iterate over elements (order not guaranteed) for item := range *s { fmt.Printf(" %v\n", item) } } ``` -------------------------------- ### Create and Access Python Tuple in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Shows how to create a tuple from a slice, access elements by index, get the length, and iterate. Note the string representation for single-element tuples. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a Tuple from a slice t := types.NewTupleFromSlice([]interface{}{"x", "y", "z"}) // Get element by index fmt.Printf("Element 0: %v\n", t.Get(0)) // Output: Element 0: x fmt.Printf("Element 1: %v\n", t.Get(1)) // Output: Element 1: y // Get length fmt.Printf("Length: %d\n", t.Len()) // Output: Length: 3 // Iterate using underlying slice for i := 0; i < t.Len(); i++ { fmt.Printf(" [%d] = %v\n", i, t.Get(i)) } // String representation (single-element tuples have trailing comma) single := types.NewTupleFromSlice([]interface{}{42}) fmt.Println(t.String()) // Output: (x, y, z) fmt.Println(single.String()) // Output: (42,) } ``` -------------------------------- ### Advanced Pickle Unpickler Configuration in Go Source: https://github.com/nlpodyssey/gopickle/blob/master/README.md Configure a custom `pickle.Unpickler` to handle custom classes, resolve persistent IDs, get custom extensions, manage out-of-band buffers, and transform objects for read-only access. Requires `io` and `fmt` imports. ```go import "github.com/nlpodyssey/gopickle/pickle" var r io.Reader // ... u := pickle.NewUnpickler(r) // Handle custom classes u.FindClass = func(module, name string) (interface{}, error) { if module == "foo" && name == "Bar" { return myFooBarClass, nil } return nil, fmt.Errorf("class not found :(") } // Resolve objects by persistent ID u.PersistentLoad = func(persistentId interface{}) (interface{}, error) { obj := doSomethingWithPersistentId(persistentId) return obj, nil } // Handle custom pickle extensions u.GetExtension = func(code int) (interface{}, error) { obj := doSomethingToResolveExtension(code) return obj, nil } // Handle Out-of-band Buffers // https://docs.python.org/3/library/pickle.html#out-of-band-buffers u.NextBuffer = func() (interface{}, error) { buf := getMyNextBuffer() return buf, nil } // Low-level function to handle pickle protocol 5 READONLY_BUFFER opcode. // By default it is completely ignored (sort of no-op); here you have the // ability to manipulate objects as you need. u.MakeReadOnly = func(obj interface{}) (interface{}, error) { newObj := myReadOnlyTransform(obj) return newObj, nil } data, err := u.Load() // ... ``` -------------------------------- ### Create and Use Python OrderedDict in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Demonstrates creating an OrderedDict, setting key-value pairs, retrieving values safely or with panic, checking length, and iterating in insertion order. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a new OrderedDict od := types.NewOrderedDict() // Set key-value pairs (maintains insertion order) od.Set("first", 1) od.Set("second", 2) od.Set("third", 3) // Get values val, exists := od.Get("second") if exists { fmt.Printf("second: %v\n", val) // Output: second: 2 } // Get with panic on missing key first := od.MustGet("first") fmt.Printf("first: %v\n", first) // Output: first: 1 // Get length fmt.Printf("Length: %d\n", od.Len()) // Output: Length: 3 // Iterate in insertion order using the List for e := od.List.Front(); e != nil; e = e.Next() { entry := e.Value.(*types.OrderedDictEntry) fmt.Printf(" %v: %v\n", entry.Key, entry.Value) } // Output: // first: 1 // second: 2 // third: 3 // Updating existing key preserves position od.Set("second", 200) fmt.Printf("Updated second: %v\n", od.MustGet("second")) // Output: Updated second: 200 } ``` -------------------------------- ### Create and Manipulate Python List in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Demonstrates creating a new list, appending elements of various types, creating from a slice, accessing elements by index, and iterating. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a new empty List l := types.NewList() // Append elements l.Append("first") l.Append(42) l.Append(3.14) // Create from existing slice l2 := types.NewListFromSlice([]interface{}{"a", "b", "c"}) // Get element by index fmt.Printf("Element 0: %v\n", l.Get(0)) // Output: Element 0: first fmt.Printf("Element 1: %v\n", l.Get(1)) // Output: Element 1: 42 // Get length fmt.Printf("Length: %d\n", l.Len()) // Output: Length: 3 // Iterate using underlying slice for i, v := range *l { fmt.Printf(" [%d] = %v\n", i, v) } // String representation fmt.Println(l.String()) // Output: [first, 42, 3.14] fmt.Println(l2.String()) // Output: [a, b, c] } ``` -------------------------------- ### Load Pickle Data from File or String in Go Source: https://github.com/nlpodyssey/gopickle/blob/master/README.md Use `pickle.Load` to load data from a file path or `pickle.Loads` to load from a string. Ensure the `pickle` package is imported. ```go import "github.com/nlpodyssey/gopickle/pickle" // ... // from file foo, err := pickle.Load("foo.p") // from string stringDump := "I42\n." bar, err := pickle.Loads(stringDump) // ... ``` -------------------------------- ### Load PyTorch Module File in Go Source: https://github.com/nlpodyssey/gopickle/blob/master/README.md Use `pytorch.Load` to load a PyTorch module file from a given path. Ensure the `pytorch` package is imported. ```go import "github.com/nlpodyssey/gopickle/pytorch" // ... myModel, err := pytorch.Load("module.pt") // ... ``` -------------------------------- ### Use Python Dictionary Type Source: https://context7.com/nlpodyssey/gopickle/llms.txt Demonstrates the use of types.Dict, which supports unhashable keys like slices that standard Go maps cannot handle. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a new empty Dict d := types.NewDict() // Set key-value pairs d.Set("name", "Alice") d.Set("age", 30) d.Set([]int{1, 2, 3}, "slice key") // Supports unhashable keys // Get values name, exists := d.Get("name") if exists { fmt.Printf("Name: %v\n", name) // Output: Name: Alice } // Get with panic on missing key age := d.MustGet("age") fmt.Printf("Age: %v\n", age) // Output: Age: 30 // Get all keys keys := d.Keys() fmt.Printf("Keys: %v\n", keys) // Get length fmt.Printf("Length: %d\n", d.Len()) // Output: Length: 3 // Iterate over entries for _, entry := range *d { fmt.Printf(" %v: %v\n", entry.Key, entry.Value) } // String representation fmt.Println(d.String()) // Output: {name: Alice, age: 30, [1 2 3]: slice key} } ``` -------------------------------- ### Create Custom Unpickler in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Use `pickle.NewUnpickler` to create a customizable unpickler from an `io.Reader`. This allows handling custom classes, persistent objects, extensions, and protocol-5 buffers by providing callback functions. ```go package main import ( "fmt" "io" "log" "os" "github.com/nlpodyssey/gopickle/pickle" ) // Custom class to represent a Python class type MyCustomClass struct { Value interface{} } func (c *MyCustomClass) Call(args ...interface{}) (interface{}, error) { return &MyCustomClass{Value: args}, nil } func main() { f, err := os.Open("custom_data.pkl") if err != nil { log.Fatal(err) } defer f.Close() u := pickle.NewUnpickler(f) // Handle custom Python classes u.FindClass = func(module, name string) (interface{}, error) { if module == "mymodule" && name == "MyClass" { return &MyCustomClass{}, nil } // Return nil to use default GenericClass handling return nil, fmt.Errorf("unknown class: %s.%s", module, name) } // Handle persistent object references (for pickle protocol using PERSID) u.PersistentLoad = func(persistentId interface{}) (interface{}, error) { // Look up object by its persistent ID id, ok := persistentId.(string) if !ok { return nil, fmt.Errorf("invalid persistent ID: %v", persistentId) } return fmt.Sprintf("resolved:%s", id), nil } // Handle pickle extensions (EXT1, EXT2, EXT4 opcodes) u.GetExtension = func(code int) (interface{}, error) { return fmt.Sprintf("extension:%d", code), nil } // Handle protocol 5 out-of-band buffers u.NextBuffer = func() (interface{}, error) { // Return the next buffer from your buffer provider return []byte("buffer data"), nil } // Handle protocol 5 READONLY_BUFFER opcode u.MakeReadOnly = func(obj interface{}) (interface{}, error) { // Transform object to read-only if needed return obj, nil } data, err := u.Load() if err != nil { log.Fatalf("Error unpickling: %v", err) } fmt.Printf("Loaded: %v\n", data) } ``` -------------------------------- ### Load PyTorch Module File Source: https://context7.com/nlpodyssey/gopickle/llms.txt Loads a .pt or .pth file into a Go structure. The resulting model is typically an OrderedDict containing tensors. ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pytorch" "github.com/nlpodyssey/gopickle/types" ) func main() { // Load a PyTorch model file model, err := pytorch.Load("model.pt") if err != nil { log.Fatalf("Error loading PyTorch model: %v", err) } // Models are typically OrderedDicts containing tensors if stateDict, ok := model.(*types.OrderedDict); ok { fmt.Printf("Loaded state dict with %d entries\n", stateDict.Len()) // Iterate over model parameters for e := stateDict.List.Front(); e != nil; e = e.Next() { entry := e.Value.(*types.OrderedDictEntry) key := entry.Key.(string) // Values are typically *pytorch.Tensor if tensor, ok := entry.Value.(*pytorch.Tensor); ok { fmt.Printf(" %s: shape=%v, requires_grad=%v\n", key, tensor.Size, tensor.RequiresGrad) // Access underlying storage data switch storage := tensor.Source.(type) { case *pytorch.FloatStorage: fmt.Printf(" Float32 data, %d elements\n", len(storage.Data)) case *pytorch.DoubleStorage: fmt.Printf(" Float64 data, %d elements\n", len(storage.Data)) case *pytorch.LongStorage: fmt.Printf(" Int64 data, %d elements\n", len(storage.Data)) case *pytorch.HalfStorage: fmt.Printf(" Float16 data (as float32), %d elements\n", len(storage.Data)) case *pytorch.BFloat16Storage: fmt.Printf(" BFloat16 data (as float32), %d elements\n", len(storage.Data)) } } } } } ``` -------------------------------- ### Load PyTorch with Custom Unpickler Source: https://context7.com/nlpodyssey/gopickle/llms.txt Uses a custom unpickler factory to handle specific classes or custom deserialization logic during model loading. ```go package main import ( "fmt" "io" "log" "github.com/nlpodyssey/gopickle/pickle" "github.com/nlpodyssey/gopickle/pytorch" ) func main() { // Create a custom unpickler factory newUnpickler := func(r io.Reader) pickle.Unpickler { u := pickle.NewUnpickler(r) // Add custom class handling u.FindClass = func(module, name string) (interface{}, error) { // Handle custom model classes if module == "mymodels" { switch name { case "CustomLayer": // Return a handler for your custom layer type return &CustomLayerClass{}, nil } } // Fall back to nil for default handling return nil, nil } return u } model, err := pytorch.LoadWithUnpickler("custom_model.pt", newUnpickler) if err != nil { log.Fatalf("Error loading model: %v", err) } fmt.Printf("Loaded model: %T\n", model) } // CustomLayerClass handles deserialization of custom PyTorch layer type CustomLayerClass struct{} func (c *CustomLayerClass) Call(args ...interface{}) (interface{}, error) { return map[string]interface{}{"type": "CustomLayer", "args": args}, nil } ``` -------------------------------- ### Implement Callable and PyNewable for custom class unpickling Source: https://context7.com/nlpodyssey/gopickle/llms.txt Implement the Callable interface for function-style instantiation and PyNewable for __new__ style instantiation. Use the FindClass callback on the Unpickler to map Python module and class names to these Go implementations. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/pickle" "github.com/nlpodyssey/gopickle/types" ) // CustomPoint implements Callable for function-style instantiation type CustomPointClass struct{} var _ types.Callable = &CustomPointClass{} func (c *CustomPointClass) Call(args ...interface{}) (interface{}, error) { if len(args) != 2 { return nil, fmt.Errorf("Point requires 2 arguments, got %d", len(args)) } x, xOk := args[0].(int) y, yOk := args[1].(int) if !xOk || !yOk { return nil, fmt.Errorf("Point requires integer arguments") } return &Point{X: x, Y: y}, nil } type Point struct { X, Y int } // CustomPersonClass implements PyNewable for __new__ style instantiation type CustomPersonClass struct{} var _ types.PyNewable = &CustomPersonClass{} func (c *CustomPersonClass) PyNew(args ...interface{}) (interface{}, error) { person := &Person{} if len(args) > 0 { if name, ok := args[0].(string); ok { person.Name = name } } return person, nil } type Person struct { Name string Age int } // Implement PyStateSettable to handle __setstate__ var _ types.PyStateSettable = &Person{} func (p *Person) PySetState(state interface{}) error { if dict, ok := state.(*types.Dict); ok { if name, exists := dict.Get("name"); exists { p.Name = name.(string) } if age, exists := dict.Get("age"); exists { p.Age = age.(int) } } return nil } func main() { // Usage with Unpickler pickleData := "..." // Your pickle data u := pickle.NewUnpickler(/* reader */) u.FindClass = func(module, name string) (interface{}, error) { switch module + "." + name { case "geometry.Point": return &CustomPointClass{}, nil case "models.Person": return &CustomPersonClass{}, nil default: return nil, fmt.Errorf("unknown class: %s.%s", module, name) } } // The unpickler will now use your custom classes _ = pickleData } ``` -------------------------------- ### pytorch.Load Source: https://context7.com/nlpodyssey/gopickle/llms.txt Loads a PyTorch module file and returns the deserialized model data. ```APIDOC ## pytorch.Load ### Description Loads a PyTorch module file (.pt or .pth) and returns the deserialized model data. Supports both modern zip-compressed format and legacy non-tar format. TorchScript archives are not supported. ### Parameters #### Request Body - **filename** (string) - Required - The path to the PyTorch model file. ### Response #### Success Response (200) - **model** (interface{}) - The deserialized model data, typically an *types.OrderedDict. ``` -------------------------------- ### pickle.NewUnpickler - Create Custom Unpickler Source: https://context7.com/nlpodyssey/gopickle/llms.txt Creates a new Unpickler instance from an io.Reader, allowing for advanced customization. Callbacks can be provided to handle custom classes, persistent object references, extensions, and protocol-5 buffers. ```APIDOC ## pickle.NewUnpickler - Create Custom Unpickler ### Description Creates a new Unpickler from an io.Reader for advanced use cases. The Unpickler can be customized with callback functions to handle custom classes, persistent objects, extensions, and protocol-5 buffers. ### Method `NewUnpickler` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **reader** (io.Reader) - Required - The reader to read pickle data from. #### Request Body N/A ### Customization Callbacks An Unpickler instance has the following customizable callback fields: - **FindClass**: `func(module, name string) (interface{}, error)` - Handles custom Python class lookups. - **PersistentLoad**: `func(persistentId interface{}) (interface{}, error)` - Handles persistent object ID lookups. - **GetExtension**: `func(code int) (interface{}, error)` - Handles pickle extension codes. - **NextBuffer**: `func() (interface{}, error)` - Provides out-of-band buffers for protocol 5. - **MakeReadOnly**: `func(obj interface{}) (interface{}, error)` - Transforms objects for read-only access in protocol 5. ### Request Example ```go package main import ( "fmt" "io" "log" "os" "github.com/nlpodyssey/gopickle/pickle" ) // Custom class to represent a Python class type MyCustomClass struct { Value interface{}: } func (c *MyCustomClass) Call(args ...interface{}) (interface{}, error) { return &MyCustomClass{Value: args}, } func main() { f, err := os.Open("custom_data.pkl") if err != nil { log.Fatal(err) } defer f.Close() u := pickle.NewUnpickler(f) // Handle custom Python classes u.FindClass = func(module, name string) (interface{}, error) { if module == "mymodule" && name == "MyClass" { return &MyCustomClass{}, } // Return nil to use default GenericClass handling return nil, fmt.Errorf("unknown class: %s.%s", module, name) } // Handle persistent object references (for pickle protocol using PERSID) u.PersistentLoad = func(persistentId interface{}) (interface{}, error) { // Look up object by its persistent ID id, ok := persistentId.(string) if !ok { return nil, fmt.Errorf("invalid persistent ID: %v", persistentId) } return fmt.Sprintf("resolved:%s", id), nil } // Handle pickle extensions (EXT1, EXT2, EXT4 opcodes) u.GetExtension = func(code int) (interface{}, error) { return fmt.Sprintf("extension:%d", code), } // Handle protocol 5 out-of-band buffers u.NextBuffer = func() (interface{}, error) { // Return the next buffer from your buffer provider return []byte("buffer data"), } // Handle protocol 5 READONLY_BUFFER opcode u.MakeReadOnly = func(obj interface{}) (interface{}, error) { // Transform object to read-only if needed return obj, } data, err := u.Load() if err != nil { log.Fatalf("Error unpickling: %v", err) } fmt.Printf("Loaded: %v\n", data) } ``` ### Response #### Success Response (200) - **data** (interface{}) - The deserialized data from the pickle stream. #### Response Example ```go // Example output for loaded data: // Loaded: resolved:some_id ``` ``` -------------------------------- ### pytorch.LoadWithUnpickler Source: https://context7.com/nlpodyssey/gopickle/llms.txt Loads a PyTorch module file using a custom unpickler factory function for handling custom classes. ```APIDOC ## pytorch.LoadWithUnpickler ### Description Loads a PyTorch module file using a custom unpickler factory function. This allows handling custom classes or applying custom deserialization logic. ### Parameters #### Request Body - **filename** (string) - Required - The path to the PyTorch model file. - **unpicklerFactory** (func(io.Reader) pickle.Unpickler) - Required - A function that returns a custom unpickler instance. ### Response #### Success Response (200) - **model** (interface{}) - The deserialized model data. ``` -------------------------------- ### Access PyTorch Tensor Properties and Data Source: https://context7.com/nlpodyssey/gopickle/llms.txt Load a PyTorch model and iterate through its state dictionary to access tensor properties like shape, stride, and requires_grad. It also demonstrates how to access the underlying data based on storage type. ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pytorch" "github.com/nlpodyssey/gopickle/types" ) func main() { model, err := pytorch.Load("model.pt") if err != nil { log.Fatal(err) } // Assuming model is an OrderedDict of tensors stateDict, ok := model.(*types.OrderedDict) if !ok { log.Fatal("Expected OrderedDict") } for e := stateDict.List.Front(); e != nil; e = e.Next() { entry := e.Value.(*types.OrderedDictEntry) tensor, ok := entry.Value.(*pytorch.Tensor) if !ok { continue } // Tensor properties fmt.Printf("Parameter: %s\n", entry.Key) fmt.Printf(" Shape: %v\n", tensor.Size) fmt.Printf(" Stride: %v\n", tensor.Stride) fmt.Printf(" Storage Offset: %d\n", tensor.StorageOffset) fmt.Printf(" Requires Grad: %v\n", tensor.RequiresGrad) // Access the underlying data based on storage type switch storage := tensor.Source.(type) { case *pytorch.FloatStorage: fmt.Printf(" Data type: float32\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) if len(storage.Data) > 0 { fmt.Printf(" First few values: %v\n", storage.Data[:min(5, len(storage.Data))]) } case *pytorch.DoubleStorage: fmt.Printf(" Data type: float64\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) case *pytorch.LongStorage: fmt.Printf(" Data type: int64\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) case *pytorch.IntStorage: fmt.Printf(" Data type: int32\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) case *pytorch.HalfStorage: fmt.Printf(" Data type: float16 (stored as float32)\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) case *pytorch.BFloat16Storage: fmt.Printf(" Data type: bfloat16 (stored as float32)\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) case *pytorch.BoolStorage: fmt.Printf(" Data type: bool\n") fmt.Printf(" Total elements: %d\n", len(storage.Data)) } fmt.Println() } } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Load Pickle Data from File in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Use `pickle.Load` to deserialize Python pickle data directly from a file. This function handles file opening and unpickling automatically. The returned data type depends on the pickled content. ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pickle" ) func main() { // Load pickle data from a file data, err := pickle.Load("data.pkl") if err != nil { log.Fatalf("Error loading pickle: %v", err) } // The returned data can be any type depending on what was pickled fmt.Printf("Loaded data: %v\n", data) fmt.Printf("Type: %T\n", data) // Common types you might receive: // - int, float64, string, bool for Python scalars // - *types.List for Python lists // - *types.Dict for Python dicts // - *types.Tuple for Python tuples // - *types.OrderedDict for collections.OrderedDict } ``` -------------------------------- ### types.Dict Source: https://context7.com/nlpodyssey/gopickle/llms.txt Represents a Python dictionary in Go, supporting unhashable keys. ```APIDOC ## types.Dict ### Description Represents a Python dict in Go. Implemented as a slice of key-value entries to support unhashable keys (like slices) that Go maps cannot handle. ### Methods - **NewDict()** - Creates a new empty Dict. - **Set(key, value)** - Sets a key-value pair. - **Get(key)** - Retrieves a value by key. - **MustGet(key)** - Retrieves a value, panics if key is missing. - **Keys()** - Returns all keys. - **Len()** - Returns the number of entries. ``` -------------------------------- ### Load Pickle Data from String in Go Source: https://context7.com/nlpodyssey/gopickle/llms.txt Use `pickle.Loads` to deserialize Python pickle data from a string. This is useful for embedded pickle data. Ensure the input string is valid pickle data. ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pickle" ) func main() { // Simple pickle protocol 0 string representing integer 42 stringDump := "I42\n." value, err := pickle.Loads(stringDump) if err != nil { log.Fatalf("Error loading pickle string: %v", err) } fmt.Printf("Value: %v\n", value) // Output: Value: 42 fmt.Printf("Type: %T\n", value) // Output: Type: int } ``` -------------------------------- ### pickle.Load - Load Pickle Data from File Source: https://context7.com/nlpodyssey/gopickle/llms.txt Loads and deserializes Python pickle data directly from a file path. This function handles file opening and unpickling, returning the deserialized data. ```APIDOC ## pickle.Load - Load Pickle Data from File ### Description Loads and deserializes Python pickle data from a file. This is the simplest way to load a pickle file, automatically handling file opening, creating an Unpickler, and returning the deserialized data. ### Method `Load` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the pickle file to load. ### Request Example ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pickle" ) func main() { // Load pickle data from a file data, err := pickle.Load("data.pkl") if err != nil { log.Fatalf("Error loading pickle: %v", err) } // The returned data can be any type depending on what was pickled fmt.Printf("Loaded data: %v\n", data) fmt.Printf("Type: %T\n", data) } ``` ### Response #### Success Response (200) - **data** (interface{}) - The deserialized data from the pickle file. The type depends on the pickled content (e.g., int, float64, string, bool, *types.List, *types.Dict, *types.Tuple, *types.OrderedDict). #### Response Example ```go // Example output for loaded data: // Loaded data: [1 2 3] // Type: *types.List ``` ``` -------------------------------- ### Handle Unknown Python Classes with GenericClass Source: https://context7.com/nlpodyssey/gopickle/llms.txt Use GenericClass to represent unknown Python classes encountered during unpickling. It captures class information and constructor arguments, creating GenericObject instances. ```go package main import ( "fmt" "github.com/nlpodyssey/gopickle/types" ) func main() { // Create a generic class (normally done by the unpickler) class := types.NewGenericClass("mymodule", "MyClass") fmt.Printf("Module: %s\n", class.Module) // Output: Module: mymodule fmt.Printf("Name: %s\n", class.Name) // Output: Name: MyClass // PyNew creates a GenericObject instance obj, err := class.PyNew("arg1", 42, true) if err != nil { fmt.Printf("Error: %v\n", err) return } // Access the generic object genObj := obj.(*types.GenericObject) fmt.Printf("Class: %s.%s\n", genObj.Class.Module, genObj.Class.Name) fmt.Printf("Constructor args: %v\n", genObj.ConstructorArgs) // Output: // Class: mymodule.MyClass // Constructor args: [arg1 42 true] } ``` -------------------------------- ### pickle.Loads - Load Pickle Data from String Source: https://context7.com/nlpodyssey/gopickle/llms.txt Deserializes Python pickle data from a string. This is useful when the pickle data is available as a string, such as when embedded in code or received over a network. ```APIDOC ## pickle.Loads - Load Pickle Data from String ### Description Deserializes Python pickle data from a string. Useful for loading pickle data that's embedded in code or received as a string from another source. ### Method `Loads` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters - **stringDump** (string) - Required - The string containing the pickled data. ### Request Example ```go package main import ( "fmt" "log" "github.com/nlpodyssey/gopickle/pickle" ) func main() { // Simple pickle protocol 0 string representing integer 42 stringDump := "I42\n." value, err := pickle.Loads(stringDump) if err != nil { log.Fatalf("Error loading pickle string: %v", err) } fmt.Printf("Value: %v\n", value) // Output: Value: 42 fmt.Printf("Type: %T\n", value) // Output: Type: int } ``` ### Response #### Success Response (200) - **value** (interface{}) - The deserialized data from the pickle string. The type depends on the pickled content. #### Response Example ```go // Example output for loaded data: // Value: 42 // Type: int ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.