Capsule Types¶
The CtyCapsule type is a special type in pyvider.cty that allows you to encapsulate and protect foreign data types within the cty system. This is useful when you need to work with data that cannot be represented by the standard cty types, such as file handles, database connections, or other external resources.
๐ค AI-Generated Content
This documentation was generated with AI assistance and is still being audited. Some, or potentially a lot, of this information may be inaccurate. Learn more.
The CtyCapsule Type¶
To create a CtyCapsule type, you must provide a name for the type:
This creates a new CtyCapsule type that can be used to encapsulate file handle objects.
Encapsulating and Accessing Data¶
You can encapsulate a foreign data type in a CtyCapsule value using the validate method:
# Create a dummy file handle object
class FileHandle:
def __init__(self, path):
self.path = path
file_handle = FileHandle("/path/to/file")
# Encapsulate the file handle in a CtyCapsule value
cty_file_handle = file_handle_type.validate(file_handle)
You can then access the encapsulated object using the raw_value property:
Type Safety¶
CtyCapsule types are type-safe. This means that you can only encapsulate objects of the correct type in a CtyCapsule value.
# This will raise a ValidationError
try:
file_handle_type.validate("not a file handle")
except Exception as e:
print(f"Validation failed: {e}")
This type safety ensures that you can't accidentally mix up different types of encapsulated data.
See Also¶
- Understanding Types - Core type system concepts
- Create Custom Types - Building custom type wrappers
- Serialization - Capsule serialization considerations
- API Reference: Capsule Types - Complete capsule API documentation