Hi,
I am wondering if someone could help me understand some of the
details of using metaclasses.
I am trying to use metaclasses to auto-generate some attributes
and methods in a class definition. I am attaching a simplified
example of the kind of code I am considering below, and I have
the following questions:
1. Is the code in NamedType.__new__ the "right" way to have a
class which has NamedType as its metaclass inherit from
NamedClass? Are the semantics different from if the class with
NamedType as its metaclass explicitly listed NamedClass as a
superclass in the standard way?
2. Is the try/except clause in NameType.__init__ the "right"
way to prevent KeyErrors for subclasses of classes with
NamedType as its metaclass?
Thanks in advance,
d
---
class NamedClass(object):
def __init__(self, name):
self.name = name
class NamedType(type):
def __new__(mcl, name, bases, dictionary):
bases = tuple(list(bases)+[NamedClass])
return super(NamedType, mcl).__new__(mcl, name, bases, dictionary)
def __init__(cls, name, bases, dictionary):
try:
name = dictionary['NAME']
except KeyError:
return
def is_a(self):
return self.name == name
setattr(cls, 'is_a_'+name, is_a)
def init(self):
super(cls, self).__init__(name)
setattr(cls, '__init__', init)
class PrintNamedType(NamedType):
def __init__(cls, name, bases, dictionary):
super(PrintNamedType, cls).__init__(name, bases, dictionary)
def print_name(self):
print self.name
setattr(cls, 'print_name', print_name)
class NamedFoo:
__metaclass__ = NamedType
NAME = 'foo'
class SubNamedFoo(NamedFoo):
pass
class NamedBar:
__metaclass__ = PrintNamedType
NAME = 'bar' 3 1554 go****@daishi.fastmail.fm (daishi) writes: Hi,
I am wondering if someone could help me understand some of the details of using metaclasses.
I am trying to use metaclasses to auto-generate some attributes and methods in a class definition. I am attaching a simplified example of the kind of code I am considering below, and I have the following questions:
1. Is the code in NamedType.__new__ the "right" way to have a class which has NamedType as its metaclass inherit from NamedClass?
Apart from the fact that tuple(list(bases)+[NamedClass]) is a strange
way of spelling bases + (NamedClass,), yes.
Are the semantics different from if the class with NamedType as its metaclass explicitly listed NamedClass as a superclass in the standard way?
Well, potentially, depending on where in the bases list you put
NamedClass. In general, it might be wise to not add NamedClass to the
bases list unless you need to (to avoid MRO calculation errors).
2. Is the try/except clause in NameType.__init__ the "right" way to prevent KeyErrors for subclasses of classes with NamedType as its metaclass?
I'd say so, but I'm not totally sure what you're trying to achieve...
Cheers,
mwh
--
The Internet is full. Go away.
-- http://www.disobey.com/devilshat/ds011101.htm
Hi Michael,
Thanks for the response. Some followup inline.
Michael Hudson <mw*@python.net> wrote in message news:<m3************@pc150.maths.bris.ac.uk>... go****@daishi.fastmail.fm (daishi) writes:
Hi,
I am wondering if someone could help me understand some of the details of using metaclasses.
I am trying to use metaclasses to auto-generate some attributes and methods in a class definition. I am attaching a simplified example of the kind of code I am considering below, and I have the following questions:
1. Is the code in NamedType.__new__ the "right" way to have a class which has NamedType as its metaclass inherit from NamedClass? Apart from the fact that tuple(list(bases)+[NamedClass]) is a strange way of spelling bases + (NamedClass,), yes.
Thanks; I had forgotten about being able to do that w/ tuples. Are the semantics different from if the class with NamedType as its metaclass explicitly listed NamedClass as a superclass in the standard way? Well, potentially, depending on where in the bases list you put NamedClass. In general, it might be wise to not add NamedClass to the bases list unless you need to (to avoid MRO calculation errors).
I was/am having some difficulties understanding what happens here.
E.g., in the example code that I gave if I make the class definition
of NamedFoo to have an explicit superclass:
class NamedFoo(object):
I obtain the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "meta2.py", line 28, in ?
class NamedFoo(object):
File "meta2.py", line 8, in __new__
return super(NamedType, mcl).__new__(mcl, name, bases, dictionary)
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, NamedClass
If I add NamedClass to the beginning by doing:
bases = (NamedClass,) + bases
(instead of appending to the end of bases),
I obtain the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "meta2.py", line 32, in ?
class SubNamedFoo(NamedFoo):
File "meta2.py", line 8, in __new__
return super(NamedType, mcl).__new__(mcl, name, bases, dictionary)
TypeError: Cannot create a consistent method resolution
order (MRO) for bases NamedFoo, NamedClass
(Note that the error is now for class SubNamedFoo instead of
NamedFoo.)
Now based on http://www.python.org/2.3/mro.html I believe this has to
do with the fact that in the first case of NamedFoo we have
merge([object], [NamedClass, object], [object, NamedClass])
(as opposed to
merge([NamedClass, object], [object], [NamedClass, object])
when the modification to bases is changed)
And the SubNamedFoo error arises because of
merge([NamedClass, object], [NamedFoo, NamedClass, object],
[NamedClass, NamedFoo, object])
Is this correct?
(I just want to make sure that I am understanding what's going on
correctly.) 2. Is the try/except clause in NameType.__init__ the "right" way to prevent KeyErrors for subclasses of classes with NamedType as its metaclass?
I'd say so, but I'm not totally sure what you're trying to achieve...
The basic idea of what I'm trying to do is (I think) fairly simple.
I have several fairly similar class definitions that I want, and I
was hoping to use metaclasses to make their definition more compact.
(As comparison, I would use a #define in C or a defmacro in Lisp).
I would like to use these classes once defined as if they were
regularly defined classes, included subclassing. My initial attempt
at subclassing with subclass class SubNamedFoo(NamedFoo) failed
because of the fact that since the metaclass of SubNamedFoo inherits
from NamedFoo and hence becomes NamedType, and the NamedType.__init__
is executed for SubNamedFoo also, which I didn't want - I would like
SubNamedFoo to be oblivious of the fact that NamedFoo was defined
using a customized metaclass. I was wondering what the ideal way to
achieve this might be.
Cheers, mwh
Thanks again,
d go****@daishi.fastmail.fm (daishi) wrote in message news:<d2**************************@posting.google. com>... Now based on http://www.python.org/2.3/mro.html I believe this has to do with the fact that in the first case of NamedFoo we have merge([object], [NamedClass, object], [object, NamedClass]) (as opposed to merge([NamedClass, object], [object], [NamedClass, object]) when the modification to bases is changed)
And the SubNamedFoo error arises because of merge([NamedClass, object], [NamedFoo, NamedClass, object], [NamedClass, NamedFoo, object])
Is this correct? (I just want to make sure that I am understanding what's going on correctly.)
Correct. More specific classes should go first to avoid confusion
about the precedence order.
The basic idea of what I'm trying to do is (I think) fairly simple. I have several fairly similar class definitions that I want, and I was hoping to use metaclasses to make their definition more compact. (As comparison, I would use a #define in C or a defmacro in Lisp). I would like to use these classes once defined as if they were regularly defined classes, included subclassing. My initial attempt at subclassing with subclass class SubNamedFoo(NamedFoo) failed because of the fact that since the metaclass of SubNamedFoo inherits from NamedFoo and hence becomes NamedType, and the NamedType.__init__ is executed for SubNamedFoo also, which I didn't want - I would like SubNamedFoo to be oblivious of the fact that NamedFoo was defined using a customized metaclass. I was wondering what the ideal way to achieve this might be.
Maybe a simple function acting as a class factory? Sometimes the
simplest solutions are the best solutions. So, unless you anticipate
the need to use inheritance of metaclasses, why don't you use a simple
function return a class (created with type(name,bases,dic), the basic
metaclass) ?
Michele This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Cezary |
last post by:
Hello.
I was read PHP manual, but i'm not sure yet. Here is my meta tags in html:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-2">
<META HTTP-EQUIV="Expires"...
|
by: Brian |
last post by:
Hi,
I'm trying to use standard meta tags in an xsl doc and using cocoon as my
processor. The problem is that cocoon changes for example:
<meta name="keywords" content="test, test, test" />
...
|
by: Darren Blackley |
last post by:
Hi there I have documents that I want to automatically add additional meta
tags to. The documents already have some meta tags and I want to keep them
all together, so I want to add my new meta tags...
|
by: Christian Hvid |
last post by:
Hello groups.
I have a series of applet computer games on my homepage:
http://vredungmand.dk/games/erik-spillet/index.html
http://vredungmand.dk/games/nohats/index.html...
|
by: Day Bird Loft |
last post by:
Web Authoring | Meta-Tags
The first thing to understand in regard to Meta Tags is the three most
important tags placed in the head of your html documents. They are the
title, description, and...
|
by: J1C |
last post by:
How can I programatically add meta tags with javascript?
|
by: RodneyDunes |
last post by:
My site did validate and now it doesn't. The error I get is the following:
document type does not allow element "META" here
....nt-type" content="text/html;charset=iso-8859-1">
Can someone...
|
by: Maziar Aflatoun |
last post by:
Hi everyone,
My goal is to modify the contents of my meta tag (html refresh). However,
my code adds a new instance of the meta tag at the bottom of the page. Is
there a way to modify it instead...
|
by: clintonG |
last post by:
Anybody know how to dynamically write the meta tags using code so they are
formatted on a separate line in the HTML source?
Preferred or optimal framework classes that may be used in this regard?
...
|
by: Edward |
last post by:
Hi All,
I am having huge problems with a very simple dotnet framework web page
(www.gbab.net/ztest3.aspx) , it does NOT render correctly under Apple's
Safari. The DIV's do not align amd float as...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
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...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |