473,785 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.

For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_informati on):
#Somehow pass extra_informati on to the MetaThing

extra_informati on = 1
t = Thing(extra_inf ormation)

The above sample won't work but I hope it demonstrates what I'm trying
to do.

Jun 22 '06 #1
9 1863
sa*****@gmail.c om wrote:
Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.
Do you really need a metaclass for this ?
For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_informati on):
#Somehow pass extra_informati on to the MetaThing

extra_informati on = 1
t = Thing(extra_inf ormation)
Why would you want a new *class* here ?
The above sample won't work but I hope it demonstrates what I'm trying
to do.


Not enough, I'm afraid - unless it's just me being dumb. From what I see
here, you just can add the extra informations on the object in the
initializer. What's your *real* use case ?


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 23 '06 #2

Bruno Desthuilliers wrote:
sa*****@gmail.c om wrote:
Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.


Do you really need a metaclass for this ?
For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_informati on):
#Somehow pass extra_informati on to the MetaThing

extra_informati on = 1
t = Thing(extra_inf ormation)


Why would you want a new *class* here ?
The above sample won't work but I hope it demonstrates what I'm trying
to do.


Not enough, I'm afraid - unless it's just me being dumb. From what I see
here, you just can add the extra informations on the object in the
initializer. What's your *real* use case ?


The extra_informati on is used in MetaThing to tell it what attributes
to add to the class. For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on
setattr(cls, make_name(extra _information),
make_object(ext ra_information) )

Does that clarify things? I might have the wrong approach - I'm new to
metaclasses. However I do think the solution to my problem lies with
them since I have to dynamically generate a class and metaclasses
provide a mechanism for doing this.

Jun 23 '06 #3
sa*****@gmail.c om wrote:
However I do think the solution to my problem lies with
them since I have to dynamically generate a class and metaclasses
provide a mechanism for doing this.


You rarely need a custom metaclass to generate classes. A class factory

def makeclass(class name, *attributes):
cls = type(classname, mybases, mydic)
for name, value in attributes:
setattr(cls, name, attr)
return cls

is the typical solution for your use case.

OTOH, if you are looking for use classes for metaclasses, look at the
Python Wiki
and use Google.

Michele Simionato

Jun 23 '06 #4
sa*****@gmail.c om wrote:
Bruno Desthuilliers wrote:
sa*****@gmail .com wrote:
Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.
Do you really need a metaclass for this ?

For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_informati on):
#Somehow pass extra_informati on to the MetaThing

extra_inform ation = 1
t = Thing(extra_inf ormation)


Why would you want a new *class* here ?

The above sample won't work but I hope it demonstrates what I'm trying
to do.


Not enough, I'm afraid - unless it's just me being dumb. From what I see
here, you just can add the extra informations on the object in the
initializer . What's your *real* use case ?


The extra_informati on is used in MetaThing to tell it what attributes
to add to the class. For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on
setattr(cls, make_name(extra _information),
make_object(ext ra_information) )

Does that clarify things? I might have the wrong approach


There's at least something wrong here : the metaclass code is executed
when the class statement (the one for a class having this metaclass) is
eval'd. It won't be called on class instanciation.

http://www.python.org/download/relea...intro/#__new__

Also, you need to understand that modifying a class with impact all it's
instances.
- I'm new to
metaclasses. However I do think the solution to my problem lies with
them since I have to dynamically generate a class
You don't have to create classes for this - it's perfectly legal to set
attributes (data or methods) on a per-object basis. Classes are more
object-factories than rigid types. Just add the needed extra attributes
in the __init__ (the class one, not the metaclass) and you should be done.
and metaclasses
provide a mechanism for doing this.


Metaclasses provides a hook on class creation process. But AFAICT, you
don't necessarily need metaclasses to dynamically create classes...


--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 23 '06 #5
sa*****@gmail.c om wrote:
Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.

For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_informati on):
#Somehow pass extra_informati on to the MetaThing

extra_informati on = 1
t = Thing(extra_inf ormation)
Tricky. First of all, __init__ belongs to the class, not the object.
(Sometimes it's convenient to say it's the object's __init__ method,
but when mucking around with metaclasses it's important be precise
about what belongs to who, otherwise everyone gets confused.) Because
__init__ belongs to the class, the object's class must already exist
before calling it, which is contrary to what you seem to want to do.

It seem as if, when creating an object, you want to create it's very
own class to go with it. I suppose there could be use case for it, but
I highly recommend you consider whether features like instance methods
or classmethods can accomplish what you want. If you'd still rather
that a Thing have its very own class, I recommend you forget about
metaclasses and use a factory function with a closure:

def create_thing(ex tra_information ):
class Thing(object):
def __init__(self):
# use extra_informati on here
...
return Thing()

If you don't like this, or if you insist on using a metaclass, and you
don't care that you'll be confusing the hell out of anyone reading the
code, the answer is to override the class's __new__ method. Unlike
__int__, the __new__ method can return any object it wants, including
an object of a different class. The class should subclass itself in
its __new__ method, providing the passed extra_informati on to the
constructor of the new subclass, then return an object created from
that subclass. The subclass should override __new__ so as not to
repeat the hijinks of the class's __new__.

Don't follow? The actual source code won't be much easier. Here's an
example.

class MetaThing(type) :
def __new__(metacls ,name,bases,cls dict,extra_info rmation):
# use extra_informati on
return type.__new__(me tacls,name,base s,clsdict)

class Thing(object):
def __new__(cls,ext ra_information) :
clsdict = {'__new__':obje ct.__new__}
my_very_own_cla ss = MetaThing(
"Subthing",(Thi ng,),clsdict,ex tra_information )
return object.__new__( my_very_own_cla ss)

Note that Thing doesn't and shouldn't define __metaclass__, since it
creates its subclass directly from the metaclass's constructor. You
could, of course, also use the closure method I demonstrated above in
Thing's __new__ method--essentially you'd be using Thing's __new__
method as the factory function.

The above sample won't work but I hope it demonstrates what I'm trying
to do.


Again, I highly recommend you consider whether what you're "trying to
do" can be done more easily with instance or class methods.
Carl Banks

Jun 23 '06 #6
sa*****@gmail.c om wrote:
The extra_informati on is used in MetaThing to tell it what attributes
to add to the class. For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on
setattr(cls, make_name(extra _information),
make_object(ext ra_information) )

Does that clarify things?


Why do the extra attributes need to be part of the class? ISTM each
instance has its own class; therefore there it doesn't matter whether a
member is a class member or an instance member.
Carl Banks

Jun 23 '06 #7
Carl Banks <in**********@a erojockey.com> wrote:
sa*****@gmail.c om wrote:
The extra_informati on is used in MetaThing to tell it what attributes
to add to the class. For example:

class MetaThing(type) :
def __init__(cls, name, bases, dict, extra_informati on):
super(MetaThing , cls).__init__(n ame, bases, dict)
#setup the class based on the parameter extra_informati on
setattr(cls, make_name(extra _information),
make_object(ext ra_information) )

Does that clarify things?


Why do the extra attributes need to be part of the class? ISTM each
instance has its own class; therefore there it doesn't matter whether a
member is a class member or an instance member.


It matters for a "member" that is actually a special-method: Python's
automatic search for special methods (except on old-style classes) does
NOT look at per-instance members, only at per-class ones.

But, as many have already said, a custom metaclass is probably not the
optimal tool for this task (and it's definitely wrong to alter a
metaclass's __init__'s signature in incompatible ways -- you would never
be able to make classes with metaclass MetaThing with a normal class
statement, since the intrinsic call to the metaclass's __init__ fails!).
Alex
Jun 23 '06 #8
Le Vendredi 23 Juin 2006 16:03, Carl Banks a écrit*:
Don't follow? *The actual source code won't be much easier. *Here's an
example.

* * class MetaThing(type) :
* * * * def __new__(metacls ,name,bases,cls dict,extra_info rmation):
* * * * * * # use extra_informati on
* * * * * * return type.__new__(me tacls,name,base s,clsdict)

* * class Thing(object):
* * * * *def __new__(cls,ext ra_information) :
* * * * * * *clsdict = {'__new__':obje ct.__new__}
* * * * * * *my_very_own_cl ass = MetaThing(
* * * * * * * * *"Subthing",(Th ing,),clsdict,e xtra_informatio n)
* * * * * * *return object.__new__( my_very_own_cla ss)


Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances are
class.
Something like that :

In [114]: class MetaClass(objec t) :
.....: def __new__(cls, name, bases=(), **some_attribut es) :
.....: return type('newtype %s' % name, bases, some_attributes )
.....:
.....:
Let's play with it :
In [115]: Concrete1 = MetaClass('conc 1', (), classprop=1, method=lambda
s : "fun")

In [116]: Concrete2 = MetaClass('conc 1', (), classprop=1, method=lambda
s : "fun")

In [117]: isinstance(Conc rete1(), Concrete2)
Out[117]: False

In [118]: isinstance(Conc rete1(), Concrete1)
Out[118]: True

In [119]: Concrete1().met hod()
Out[119]: 'fun'

In [120]: Concrete1.class prop
Out[120]: 1

In [121]: class Abstract(object ) :
.....: def __init__(self) : self._attr = self._attr_type ()
.....:
.....:

In [122]: Concrete = MetaClass('conc rete_with_list' , (Abstract,),
_attr_type=list )

In [123]: Concrete()._att r
Out[123]: []

In [124]: Concrete = MetaClass('conc rete_with_int', (Abstract,),
_attr_type=int)

In [125]: Concrete()._att r
Out[125]: 0

In [126]: type(Concrete)
Out[126]: <type 'type'>

In [127]: type(Concrete() )
Out[127]: <class '__main__.newty pe concrete_with_i nt'>
regards,

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 23 '06 #9
Le Vendredi 23 Juin 2006 17:09, Maric Michaud a écrit*:
Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances
are class.

Ooops, sorry i didn't notice you were calling type's __new__ (and not
object'sone).
--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 23 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2536
by: jose luis fernandez diaz | last post by:
Hi, I am reading Stroustrup's book 'C++ Programming Language'. In the 10.4.9 section (Nonlocal Store) he says: "A variable defined outside any function (that is global, namespace, and class static variables) is initializated (constructed) before main is invoked . . ." .. . .
2
1453
by: V. de Bellabre | last post by:
Hello all, I'm currently working on a 3D graphic engine but I'm stuck with a small problem on references of pointers. Some of my c++ class are complex and use many pointers so I decided to force initialisation of objects through their static function Create, which has a parameter IN-OUT that will contain the instance of the created object. Here is a sample that speaks better than words :
4
1450
by: pixelbeast | last post by:
hi, In the following code, I would like not to have to declare the constructors in bar ( either the default or the (int a) constructor ). When I remove them, bar has no idea of construction with an int, so I get compile errors. I currently have to declare them for every class inheriting foo, and it would be much nicer just with the init. Is there a nice way of doing this? I am currently using a macro, like CONSTRUCTOR(bar) which feels a...
13
9651
by: Stumped and Confused | last post by:
Hello, I really, really, need some help here - I've spent hours trying to find a solution. In a nutshell, I'm trying to have a user input a value in form's textfield. The value should then be assigned to a variable and output using document.write. (Note, there is no submit button or other form elements. Basically
11
26327
by: Randell D. | last post by:
Folks, I have seven text boxes which will contain measurements - I would like the user to input their values in the order that I have listed the boxes. How can I therefore make an input type=text name=box2 a readonly while type=text name=box1 has a length of zero? This is for an intranet based application and I understand all the arguements and points that one has to consider in such that my server
5
3736
by: Dennis Fazekas | last post by:
Greetings, I am creating a web form which will all the user to add an unlimited number of email addresses. Basically I have 3 buttons, "Add Another Email", "-" to remove, and a "Save" button. When the user clicks the "Add another email" it will call a client side JavaScript function, add_email, which will dynamically add a new set of controls to the webpage using the innerHTML method. It appears to work perfectly fine in the browser. The...
5
1872
by: Arpan | last post by:
In order to populate any server control with data dynamically, is it ALWAYS NECESSARY to either BIND the DataSource to that server control or call the DataBind method of that server control? For e.g. consider the following code: <script runat="server"> Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs) If Not (Page.IsPostBack) Then 'create an array of colors
6
3681
by: semkaa | last post by:
Can you explain why using ref keyword for passing parameters works slower that passing parameters by values itself. I wrote 2 examples to test it: //using ref static void Main(string args) { List<TimeSpantimes = new List<TimeSpan>(); DateTime start; DateTime end; for (int j = 0; j < 1000; j++)
10
1604
by: cppquester | last post by:
I got an app where a bunch of values are set before the calculation is fired up. I need an elegant way to check if all variables have been set. So for example for double I am thinking about a class Double { private;
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10100
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.