Python: saving dynamically created object types

I create object types dynamically using a type function. Ex

return type('DynamicType', (object,), dict) 

Dick depends on user input. Now I want to be able to save this return type of the class and use it in different sessions. One possible way is to save the dict as text (or to a database) and create this type of object again from that dict. But is there any other way by which I can save the "type" directly?

+6
python types django class
source share
7 answers

How about creating a Factory class with methods for creating, sorting and unpacking dynamically created type objects? The following is a rough start. To use, simply replace the calls with pickle.dump (type, fh) with TypeFactory.pickle (type, fh) and replace the calls with pickle.load (fh) with TypeFactory.unpickle (fh).

 import pickle class TypeFactory(object): def __init__(self): pass @staticmethod def create_type(name='DynamicType', dict={}): return type(name, (object,), dict) @staticmethod def pickle(t, fh): dict = t.__dict__.copy() name = t.__name__ for key in dict.keys(): if key.startswith('__') and key.endswith('__'): del dict[key] pickle.dump((name, dict), fh) @classmethod def unpickle(cls, fh): name, dict = pickle.load(fh) return cls.create_type(name, dict) 
+2
source share

You cannot sort the classes, even if you solve the problem "... not found as ...", it still will not work (as in the case of saving the class name without content, unpickle, because the class does not exist after restarting your program )

You will have to manually serialize the dict and recreate this class later, which, depending on what it contains, will also be fun: object objects cannot be serialized by anything, you need to extract their code objects, serialize them with the marshal , then recreate them when loading .

+3
source share

In python, classes are objects too. So, you should be able to sort the class objects and save them to a file. Then you can print them later.

+1
source share

Perhaps you could try the json module (note: I did not use it myself, so I don’t know if it will solve your problem, this is just a suggestion):

"The json module provides a pickle-like API for converting Python objects in memory to a serialized representation known as JavaScript Object Notation (JSON). Unlike brine, JSON has the advantage of being implemented in many languages ​​(especially JavaScript), which makes it interoperable between applications. JSON is probably the most widely used for communication between a web server and a client in an AJAX application, but is not limited to this problem domain. (...) "

JSON module on the Python Module of the Week website

0
source share

Saving the dict in JSON seems to be the easiest, but it looks like a pickle or shelf can be used to create some kind of dynamic class serialization.

A quick search on SO opens up this useful post: getting a class or class namespace in python, even if it is nested

0
source share

You can β€œinject” a new class into the global namespace before etching to avoid a pickle error:

 import pickle class TestClass(object): def __init__(self): self.a = 1 # Initial instance attributes self.b = 2 self.c = 3 my_classname = "NewTestClass" obj = type(my_classname, (TestClass,), {})() obj.d = 4 # Extra attributes print obj.a, obj.b, obj.c, obj.d print obj.__class__ globals()[my_classname] = obj.__class__ # Inject the new class in the global namespace obj2 = pickle.dumps(obj) obj = None # Free original obj instance obj = pickle.loads(obj2) print obj.a, obj.b, obj.c, obj.d # 1,2,3,4 
0
source share

There is no automatic solution for your question. All default mechanisms, such as pickle, simply store instance data (including metadata similar to the type). What you want to do is save the class. You may be able to create something using the magic of byte code, but it's probably easier to implement your own serialization code.

0
source share

All Articles