Skip to main content

Dynamically generate classes from JSON or Dicts

Project description

PyDict2Class

Dynamic create classes from dict or json like you would develop them yourself.

Introduction

This tool makes it possible to generate a Python class with attributes from a dict or a JSON, or to create an object with the corresponding assigned values. The data type of the value of the dict or JSON is recognized and automatically initialized with the appropriate builtins data types. Non Python standard types or methods can also be included by adding them to the type attribute, this can also override the internal data types.

i use this tool to dynamically create mongoengine data classes with the appropriate attributes. Actual i am implement the Functionality to create SQLAlchemy Data Model classes.

Usage

install the library from source or over pip. import package and inherit Class object. e builtins data types. Non Python standard types or methods can also be inc

from pydict2class import Dict2Class
dict2class = Dict2Class()

Define the Dictionary you want to generate a class from.

mydict = {"integer": 1, "string": "my string", "boolean": True, "list": [1, 2, 3]}

Now you have to decide whether you want to generate only the class or if you want to generate the class and instantiate it with the values given in your dict or json.

Only generate the class:

myclass = dict2class.generate(mydict, "myclassname")

The magic is done and you have a dynamic class with the dictionary keys as attribute names and the value data type as datatype.

Generate class and initialize object:

myobj = dict2class.generate_and_init(mydict, "classfdict")

Use JSON instead of Dict:

myjsonstr = '{"integer": 1, "string": "my string", "boolean": True, "list": [1, 2, 3]}'
myclass = dict2class.generate(myjsonstr, "myclass", json=True)

Add Custom methods to types and use them:

    dict2class = Dict2Class()
    dict2class.types = mycustommethods
    

Add list of custom methods to type and use them:

    dict2class = Dict2Class()
    dict2class.types = [custommethod1, custommethod2, custommethod3, custommethod4, custommethod5]

Documentation for PyDict2Class:

This module provides a class called PyDict2Class that allows you to dynamically generate Python classes from dictionaries. The generated classes can be used to create objects based on the key-value pairs in the dictionary.

PyDict2Class class:

The PyDict2Class class has the following methods:

init(self, debug: bool = False) - Constructor method that initializes the PyDict2Class object. It takes an optional parameter 'debug' which, if set to True, enables debug logging.

types - Property that returns the type dictionary maintained by PyDict2Class. The type dictionary maps class names to their corresponding types.

types.setter - Property setter method that allows you to update the type dictionary maintained by PyDict2Class.

generate(self, condict, classname: str, BaseClass=BaseClass, json: bool = False, prioritizetypedict: bool = False) - Method that generates a new class dynamically based on the key-value pairs in the input dictionary 'condict'. The generated class is assigned the name 'classname'. The optional parameter 'BaseClass' allows you to specify a base class that the generated class should inherit from. The optional parameter 'json' allows you to specify whether the input dictionary 'condict' is a JSON string. The optional parameter 'prioritizetypedict' specifies whether to prioritize the type dictionary maintained by PyDict2Class over the built-in types when mapping values to their corresponding types.

generate_and_fill(self, condict, classname: str, BaseClass=BaseClass, type_dict=None, json=False, prioritizetypedict: bool = False) - Method that generates a new class dynamically based on the key-value pairs in the input dictionary 'condict', and then instantiates an object of the generated class with the input dictionary as the constructor arguments. The optional parameter 'type_dict' allows you to specify a type dictionary to use for type mapping. The optional parameter 'json' allows you to specify whether the input dictionary 'condict' is a JSON string. The optional parameter 'prioritizetypedict' specifies whether to prioritize the type dictionary maintained by PyDict2Class over the built-in types when mapping values to their corresponding types.

BaseClass class:

The BaseClass class is a helper class that is used as a base class for the dynamically generated classes. It has the following attributes:

_dynamic_class - Boolean attribute that indicates whether the class is dynamically generated or not.

_created - Datetime attribute that records the creation time of the object.

_init - Boolean attribute that indicates whether the object has been initialized or not.

_init_datetime - Datetime attribute that records the initialization time of the object.

init(self, kwargs) - Constructor method that initializes the object with the input keyword arguments.

Example usage:

Here is an example of how to use PyDict2Class to generate a class dynamically based on a dictionary:

from pydict2class import PyDict2Class

# Create a PyDict2Class object
pdc = PyDict2Class()

# Define a dictionary
d = {"name": "Alice", "age": 30}

# Generate a class dynamically based on the dictionary
Person = pdc.generate(d, "Person")

# Create an object of the generated class
alice = Person(name="Alice", age=30)

# Print the object
print(alice)

This will output:

<__main__.Person object at 0x7f7c4c4b6048>

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydict2class-0.0.1-py3-none-any.whl (16.7 kB view details)

Uploaded Python 3

File details

Details for the file pydict2class-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: pydict2class-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 16.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.6

File hashes

Hashes for pydict2class-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6488ed8a63a707c62fd1c00aaffb381892a3421354a07aa462aa6da4da54dd8e
MD5 b755b904a74b5e0eaa1354bea7dec44b
BLAKE2b-256 f34c779f2f64fea3afd800a3444ca2b55611ad2b3204fbd572e9eae15cfacc8b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page