Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating classes in python and __repr__

Tags:

python

This is a fairly straightforward question hopefully you all can enlighten me. In the example below how do I define __repr__ to be dynamically set to self.name?

Thanks all!

import re

inputlist = 'Project="Sparcy" Desc=""\nProject="Libs" Desc=""\nProject="Darwin" Desc=""\nProject="Aaple" Desc="The big project"'

regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')

results = []
for project in inputlist.split("\n"):
    items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)]
    if len(items) < 2:
        print("Houston we have a problem - Only %s k/v pair found for %s" % (len(items), project))
        continue
    item_dict = dict(items[1:])
    item_dict['name'] = items[0][1]
    klass = type(items[0][0], (object,), item_dict)
    results.append(klass)

print results

What I am looking for is this

psuedo code

for result in results
 type(result) → Project
 print result → Sparky
like image 617
rh0dium Avatar asked Aug 25 '11 16:08

rh0dium


People also ask

What is __ repr __ In Python class?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

How do you create a dynamic class in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

What is the purpose of the __ repr __ method?

The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object. In other words, if you pass the returned string of the object_name.

What is def __ repr __( self in Python?

Syntax. object. __repr__ (self) Returns a string as a representation of the object. Ideally, the representation should be information-rich and could be used to recreate an object with the same value.


1 Answers

I'm guessing that you want

print results

to return

["Sparcy", "Libs", "Darwin", "Aaple"]
  1. Printing a list shows the repr of its elements.
  2. repr(elt) is determined by type(elt).__repr__.
  3. Since in this case the elements are classes, you need to set the __repr__ for the type of the class.

import re

inputlist = '''\
Project="Sparcy" Desc=""
Project="Libs" Desc=""
Project="Darwin" Desc=""
Project="Aaple" Desc="The big project"
Site="Phoenix" Protocol="Cheese"'''

regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')

results = []
for project in inputlist.split("\n"):
    items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)]
    if len(items) < 2:
        print("Houston we have a problem - Only %s k/v pair found for %s" % (len(items), project))
        continue
    item_dict = dict(items[1:])
    item_dict['name'] = items[0][1]
    projectname=items[0][0]
    metametaklass=type('meta_'+projectname,(type,),{'__repr__':lambda cls: cls.__name__}) 
    metaklass=metametaklass(projectname,(type,),{'__repr__':lambda cls: cls.name})
    klass=metaklass(projectname+'_class', (object,), item_dict)
    results.append(klass)

print(results)

yields

["Sparcy", "Libs", "Darwin", "Aaple", "Phoenix"]

and

for result in results:
    print(type(result))
    print(result)    
    print('-'*80)

yields

Project
"Sparcy"
--------------------------------------------------------------------------------
Project
"Libs"
--------------------------------------------------------------------------------
Project
"Darwin"
--------------------------------------------------------------------------------
Project
"Aaple"
--------------------------------------------------------------------------------
Site
"Phoenix"
--------------------------------------------------------------------------------

PS. Note that this is a perversion of __repr__, since the repr of an object is supposed to be an unambiguous string representation of the object. That is, it is supposed to give enough information to reproduce the object. You probably should be defining a different print function instead of messing with metaclasses.

like image 129
unutbu Avatar answered Oct 19 '22 19:10

unutbu