Skip to main content

dconstruct

Extremely simple way to build objects from a dictionary specification, recursively.

Contains one main function, construct, which takes a type dispatch dictionary and a dictionary to construct an object from, and returns the object.

Basic Example

from dconstruct import construct

def create_model(spec):
    return construct(
        dict(Conv1d=torch.nn.Conv1d, Linear=torch.nn.Linear),
        spec,
        device='cpu'
    )

This function creates a model from a specification dictionary. For example, the following specification:

spec = {
    'type': 'Conv1d',
    'in_channels': 1,
    'out_channels': 16,
    'kernel_size': 3
}
create_model(spec)

Will create a torch.nn.Conv1d object with the specified parameters. The device='cpu' argument is passed to the constructor, but the specification dictionary can override it.

Recursive Example

If we want to support Sequential models, we can use the construct function recursively:

def create_model(spec):
    return construct(
        dict(
            Conv1d=torch.nn.Conv1d,
            Linear=torch.nn.Linear,
            Sequential=lambda subspecs: torch.nn.Sequential(*[
                create_model(subspec) for subspec in subspecs
            ]),
        ),
        spec,
        device='cpu'
    )

Now we can create a model like this:

spec = {
    'type': 'Sequential',
    'subspecs': [
        {
            'type': 'Conv1d',
            'in_channels': 1,
            'out_channels': 16,
            'kernel_size': 3
        },
        {
            'type': 'Linear',
            'in_features': 16,
            'out_features': 10
        }
    ]
}
create_model(spec)

This will create a torch.nn.Sequential object with the specified submodules.

Metadata

Release files for dconstruct 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dconstruct 1.0.1
File Size Uploaded
dconstruct-1.0.1.tar.gz 15.2 kB Details

Release files / dconstruct-1.0.1.tar.gz

Download URL dconstruct-1.0.1.tar.gz
Size 15.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a3e40ba902ce959d5dffea010b4bf162be53ef066be87d27bcc9d49798636559
BLAKE2b-256 checksum
How to use checksums
a6cc1eda5de10e75f1e3a73636e1b984e974e5406469a4a72dbe4603c62efee0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.7

Release history Release notifications | RSS feed

This release

1.0.1 This release

1 release file

1.0.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page