473,696 Members | 1,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order in metaclass

In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?

Thx and regards,
Nicolas
Jul 18 '05 #1
39 2917
On Tue, 12 Oct 2004 15:37:22 -0400, Nicolas Fleury wrote:
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?

Thx and regards,
Nicolas


What order?

Yeah, they are listed in the source in a particular order, but there is
absolutely no difference between the six permutations of that order, in
theory or in fact, since the vars end up in a dict.

If you want a concept of "order", you're going to have do define one
yourself. What do you want to do, exactly?

I'm going to guess you're trying to get the vars out in order upon an
iteration, which may not be right but extends to other cases as well
fairly cleanly.

The easy solution is a list:

class MyClass(object) :
classData = [4, 5, 6]
offsets = {'x': 0, 'y': 1, 'z':2}
def getVarMaker(var ):
def getVar(self):
return self.classData[self.offsets[var]]
return getVar
def setVarMaker(var ):
def setVar(self, value):
self.classData[self.offsets[var]] = value
return setVar
x = property(getVar Maker('x'), setVarMaker('x' ))
y = property(getVar Maker('y'), setVarMaker('y' ))
z = property(getVar Maker('z'), setVarMaker('z' ))
def __iter__(self):
for value in self.classData:
yield value

A metaclass could take classData and offsets and make the access vars for
you.
--------
def getVarMaker(var ):
def getVar(self):
return self.classData[self.offsets[var]]
return getVar

def setVarMaker(var ):
def setVar(self, value):
self.classData[self.offsets[var]] = value
return setVar

class OrderedClassAtt ributes(type):
def __init__(cls, name, bases, dict):
super(OrderedCl assAttributes, cls).__init__(n ame, bases, dict)
for name in cls.offsets:
setattr(cls, name, property(getVar Maker(name),
setVarMaker(nam e)))

class MyClass(object) :
classData = [4, 5, 6]
offsets = {'x': 0, 'y': 1, 'z':2}
__metaclass__ = OrderedClassAtt ributes
def __iter__(self):
for value in self.classData:
yield value

---------
(Assuming the above is copy/pasted into Python:)
m = MyClass()
m.x 4 m.y 5 m.z 6 m.y = 33
m.y 33 list(m)

[4, 33, 6]
---------

Lightly tested but working as I designed.

Is that what you wanted? If not, feel free to ask more. There are
certainly other options but without more data, it is hard to know what you
need.

This is a pretty good metaclass use, I think.
Jul 18 '05 #2
Nicolas Fleury <ni******@yahoo .com_remove_the _> wrote in message news:<Rn******* *************@n ews20.bellgloba l.com>...
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?

Thx and regards,
Nicolas


Short answer: No.

x, y, z are in the class dictionary. dictionaries have no order.

You could use something like

class MyType(MyBaseTy pe):
__mylist__ = [("x", 4), ("y", 5), ("z",6)]

and use the metaclass to set the class attributes x,y and z for you.
Michele Simionato
Jul 18 '05 #3
Nicolas Fleury wrote:
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z
somewhere?


If you want to record the order of these definitions, you need to pass a
custom dictionary that keeps track of assignments in the class generation
code (basically a normal python function comprising the class suite).
Unfortunately that dictionary - which you see later as the classdict
parameter of the metaclass __new__() method - is always a dict created in C,
as was recently discussed on c.l.py (sorry, but all keywords I remember are
'metaclass' and 'martelli' - not very selective :-). Below is my (clumsy)
attempt for a workaround:

import itertools

class OrderedValue(ob ject):
newIndex = itertools.count (1).next
def __init__(self, value):
self.value = value
self.index = self.newIndex()

class Meta(type):
def __new__(mcl, name, bases, classdict):
assert "ordered_na mes" not in classdict

values = []
for (n, v) in classdict.iteri tems():
try:
v, i = v.value, v.index
except AttributeError:
pass
else:
values.append(( i, n, v))
values.sort()

ordered_names = []
for (i, n, v) in values:
ordered_names.a ppend(n)
classdict[n] = v
classdict["ordered_na mes"] = ordered_names

return type.__new__(mc l, name, bases, classdict)
class Base:
__metaclass__ = Meta

class Demo(Base):
alpha = 0
beta = OrderedValue(1)
gamma = OrderedValue(17 )
delta = OrderedValue(3)

print Demo.ordered_na mes
print Demo.alpha, Demo.beta
Peter

Jul 18 '05 #4
On Wed, 13 Oct 2004 09:04:03 +0200, Peter Otten <__*******@web. de> wrote:
Nicolas Fleury wrote:
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z
somewhere?


If you want to record the order of these definitions, you need to pass a
custom dictionary that keeps track of assignments in the class generation
code (basically a normal python function comprising the class suite).
Unfortunatel y that dictionary - which you see later as the classdict
parameter of the metaclass __new__() method - is always a dict created in C,
as was recently discussed on c.l.py (sorry, but all keywords I remember are
'metaclass' and 'martelli' - not very selective :-). Below is my (clumsy)
attempt for a workaround:

import itertools

class OrderedValue(ob ject):
newIndex = itertools.count (1).next
def __init__(self, value):
self.value = value
self.index = self.newIndex()

class Meta(type):
def __new__(mcl, name, bases, classdict):
assert "ordered_na mes" not in classdict

values = []
for (n, v) in classdict.iteri tems():
try:
v, i = v.value, v.index
except AttributeError:
pass
else:
values.append(( i, n, v))
values.sort()

ordered_names = []
for (i, n, v) in values:
ordered_names.a ppend(n)
classdict[n] = v
classdict["ordered_na mes"] = ordered_names

return type.__new__(mc l, name, bases, classdict)
class Base:
__metaclass__ = Meta

class Demo(Base):
alpha = 0
beta = OrderedValue(1)
gamma = OrderedValue(17 )
delta = OrderedValue(3)

print Demo.ordered_na mes
print Demo.alpha, Demo.beta


Or, an ugly hack that might work for a while, depending on how
co_names is really generated. It seems in order of occurrence
(including right hand sides of assignment, but still top down) ...
import sys
def getnames(): return sys._getframe(1 ).f_code.co_nam es ... def MC(cname, cbases, cdict): ... names = cdict.get('ordi c',[])
... names = [name for name in names if name in cdict]
... cdict['ordic'] = dict([(name,i) for i,name in enumerate(names )])
... return type(cname, cbases, cdict)
... class C(object): ... __metaclass__ = MC # really a function shortcut
... x = 123
... y = sys
... z = 0
... ordic = getnames()
... C.ordic {'ordic': 5, '__module__': 0, '__metaclass__' : 1, 'y': 3, 'x': 2, 'z': 4}
class D(object): ... __metaclass__ = MC # really a function shortcut
... x = 123
... def m(self): pass
... def sm(): print getnames()
... sm = staticmethod(sm )
... ordic = getnames()
... D.ordic {'ordic': 5, '__module__': 0, '__metaclass__' : 1, 'm': 3, 'sm': 4, 'x': 2} D.sm <function sm at 0x00906030> D.sm()

('getnames',)

Regards,
Bengt Richter
Jul 18 '05 #5
bo**@oz.net (Bengt Richter) writes:
Nicolas Fleury wrote:
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z
somewhere?

[snip]
Or, an ugly hack that might work for a while, depending on how
co_names is really generated. It seems in order of occurrence
(including right hand sides of assignment, but still top down) ...


I don't know whether to laugh or cry! Nice one.

Cheers,
mwh

--
<lament> Slashdot karma, unfortunately, is not real karma, because
it doesn't involve the death of the people who have it
-- from Twisted.Quotes
Jul 18 '05 #6
Bengt Richter wrote:
Or, an ugly hack that might work for a while, depending on how
co_names is really generated. It seems in order of occurrence
(including right hand sides of assignment, but still top down) ...
¬*import¬*sy s
¬*def¬*getna mes():¬*return¬ *sys._getframe( 1).f_code.co_na mes ...¬*def¬*MC(cn ame,¬*cbases,¬* cdict): ...¬*¬*¬*¬*¬*na mes¬*=¬*cdict.g et('ordic',[])
...¬*¬*¬*¬*¬*na mes¬*=¬*[name¬*for¬*name ¬*in¬*names¬*if ¬*name¬*in¬*cdi ct]
...¬*¬*¬*¬*¬*cd ict['ordic']¬*=¬*dict([(name,i)¬*for¬* i,name¬*in¬*enu merate(names)])
...¬*¬*¬*¬*¬*re turn¬*type(cnam e,¬*cbases,¬*cd ict)
...¬*class¬*C(o bject): ...¬*¬*¬*¬*¬*__ metaclass__¬*=¬ *MC¬*#¬*really¬ *a¬*function¬*s hortcut
...¬*¬*¬*¬*¬*x¬ *=¬*123
...¬*¬*¬*¬*¬*y¬ *=¬*sys
...¬*¬*¬*¬*¬*z¬ *=¬*0
...¬*¬*¬*¬*¬*or dic¬*=¬*getname s()
...¬*C.ordic

{'ordic':¬*5,¬* '__module__':¬* 0,¬*'__metaclas s__':¬*1,¬*'y': ¬*3,¬*'x':¬*2,¬ *'z':¬*4}


A metaclass /function/ and sys._getframe() exercised on a class definition
- I think you have raised the bar for what qualifies as a hack :-)

Peter

Jul 18 '05 #7
On Tue, 12 Oct 2004 15:37:22 -0400, Nicolas Fleury
<ni******@yahoo .com_remove_the _> wrote:
In the following example:

class MyMetaclass(typ e): pass
class MyBaseType(obje ct): __metaclass__ = MyMetaclass
class MyType(MyBaseTy pe):
x = 4
y = 5
z = 6

Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?


Well, some people have already pointed to you about a recent
discussion on this topic. I was the one who started it all :-) What I
have learned is:

-- Due to the way the class statement is handled, it's not possible
(without really black magic) to guarantee ordering in a transparent
way. If you need to put attributes in order, you have either to
provide a list with all attributes in order, or use derive your
attributes from a base class that provide some ordering mechanism of
its own.

-- You have to include an extra member into your class to record the
order. I have chosen to include a list, named "_fields", with all
attribute _names_. Storing the attribute name is guaranteed way to
keep the ordering even when a descendant override an attribute, or
when the user modify its value.

I have written a small package called GenericTemplate s, that works all
the magic needed. It's the basis for a much more ambitious package for
'declarative-style' data structures using class statements. It handles
nested classes also, and keeps the ordering of all attributes that
inherit from a AbstractAttribu te class (it includes nested classes
that inherit from GenericTemplate , and also OrderedAttribut es and
TypedAttributes ). I have a page for it in portuguese only at:

http://www.pythonbrasil.com.br/moin....tesGen%E9ricos

The code is as follows -- still with debug code included, and lots of comments:

"""
metatemplate.py

Template class that can be used to write complex data structures using
nested classes. Template classes can store other template classes (nested)
or user-defined attributes (typed or untyped). The original definition
order information is preserved, allowing for true templating use for
applications such as html templates, data entry forms, and configuration
files.

(c) 2004 Carlos Ribeiro
ca********@gmai l.com
http:///pythonnotes.blogspot.com

"""

import sys
from inspect import isclass, isdatadescripto r
from types import StringType, IntType, FloatType, ListType
import itertools

#----------------------------------------------------------------------
# Debug constants. I don't intend to remove them, even from production
# code, but I intend to use the logging module to print the messages

debug_generic_a ttribute = 0
debug_typed_att ribute = 0
debug_auto_inst antiation = 0

#----------------------------------------------------------------------
# AbstractAttribu te is the ancestor of all classes that can be used
# in the metacontainer framework.

class AbstractAttribu te(object):
pass

#----------------------------------------------------------------------
# GenericAttribut e is the ancestor of all simple elements that are
# used as attributes of user defined Container subclasses
#
# GenericAttribut es are simpler than full containers. They're both
# derived from the same AbstractAttribu te class, but GenericAttribut es
# have only a single value associated with them.
#
# When referred from a instance, the __get__ method returns the value
# associated with the attribute. If called from the class, the __get__
# method returns the property itself.

class GenericAttribut e(AbstractAttri bute):
""" Generic attributes for generic containers """
def __init__(self, default = None):
self._seqno = next_attribute_ id()
self.value = default
def __repr__(self):
return "<Attr '%s'>" % (self.__class__ .__name__)
def __get__(self, instance, owner):
if debug_generic_a ttribute:
print "GET self:[%s], instance:[%s], owner:[%s]" % \
(self, instance, owner)
if instance:
attrdict = instance.__dict __.setdefault(' __attr__', {})
return attrdict.get(se lf.name, self.value)
else:
return owner
def __set__(self, instance, value):
if debug_generic_a ttribute:
print "SET self:[%s], instance:[%s], value:[%s]" % \
(self, instance, value)
attrdict = instance.__dict __.setdefault(' __attr__', {})
attrdict[self.name] = value

class TypedAttribute( GenericAttribut e):
""" Typed attributes for generic containers """
def __init__(self, default = None, mytype = None):
self._seqno = next_attribute_ id()
self.value = default
if mytype:
if isclass(mytype) :
self.mytype = mytype
else:
raise TypeError("Argu ment <mytype> expects None "
"or a valid type/class")
else:
self.mytype = type(default)
def __repr__(self):
return "<TypedAttr '%s':%s>" % \
(self.__class__ .__name__, self.mytype.__n ame__)
def __get__(self, instance, owner):
if debug_typed_att ribute:
print "GET self:[%s], instance:[%s], owner:[%s]" % \
(self, instance, owner)
if instance:
attrdict = instance.__dict __.setdefault(' __attr__', {})
return attrdict.get(se lf.name, self.value)
else:
return self.value
def __set__(self, instance, value):
if debug_typed_att ribute:
print "SET self:[%s], instance:[%s], value:[%s]" % \
(self, instance, value)
if not isinstance(valu e, self.mytype):
# if it's a string, tries to convert to the correct
# target type (this is needed because most things read
# from files will be strings anyway)
if isinstance(valu e, StringType):
value = self.mytype(val ue)
else:
raise TypeError, "Expected %s attribute" % \
self.mytype.__n ame__
attrdict = instance.__dict __.setdefault(' __attr__', {})
attrdict[self.name] = value

#----------------------------------------------------------------------
# auxiliary functions

next_attribute_ id = itertools.count ().next

def getfields(dct):
"""
takes a dictionary of class attributes and returns a decorated list
containing all valid field instances and their relative position.

"""
for fname, fobj in dct.items():
if isinstance(fobj ,GenericAttribu te):
yield (fobj._seqno, (fname, fobj))
elif isclass(fobj) and issubclass(fobj ,AbstractAttrib ute):
yield (fobj._seqno, (fname, fobj))
elif (fname[0] != '_'):
# conventional attributes from basic types are just stored
# as GenericAttribut es, and put at the end of the list,
# in alphabetical order
if (isinstance(fob j,StringType) or
isinstance(fobj ,IntType) or
isinstance(fobj ,FloatType) or
isinstance(fobj ,ListType)):
yield (sys.maxint, (fname, GenericAttribut e(fobj)))
else:
yield (0, (fname, fobj))
else:
yield (0, (fname, fobj))

def makefieldsdict( dct, bases):
# build the field list and sort it
fields = list(getfields( dct))
fields.sort()
# undecorate the list and build a dict that will be returned later
sorted_field_li st = [field[1] for field in fields]
field_dict = dict(sorted_fie ld_list)
# finds all attributes and nested classes that are containers
attribute_list = [field for field in sorted_field_li st
if (isinstance(fie ld[1],AbstractAttrib ute) or
(isclass(field[1]) and
issubclass(fiel d[1],AbstractAttrib ute)
))]
# check baseclasses for attributes inherited but not overriden
# !!WARNING: this code does not checks correctly for multiple
# base classes if there are name clashes between overriden
# members. This is not recommended anyway.
inherited = []
for baseclass in bases:
base_field_list = getattr(basecla ss, '_fields', None)
# looks for a valid _fields attribute in an ancestor
if isinstance(base _field_list, ListType):
fnames = [f[0] for f in attribute_list]
for fname, fobj in base_field_list :
# checks for overriden attributes
if (fname in fnames):
# overriden - inherited list contains the new value
newobj = field_dict[fname]
inherited.appen d((fname, newobj))
# remove attribute and quick check field names list
attribute_list. remove((fname, field_dict[fname]))
fnames.remove(f name)
else:
# copy the original entry into the inherited list
inherited.appen d((fname, fobj))
field_dict['_fields'] = inherited + attribute_list
return field_dict

#----------------------------------------------------------------------
# MetaTemplate metaclass
#
# Most of the hard work is done outside the class by the auxiliary
# functions makefieldsdict( ) and getfields()

class MetaTemplate(ty pe):
def __new__(cls, name, bases, dct):
# creates the class using only the processed field list
newdct = makefieldsdict( dct, bases)
newclass = type.__new__(cl s, name, bases, newdct)
newclass._seqno = next_attribute_ id()
newclass.name = name
return newclass

#----------------------------------------------------------------------
# GenericTemplate superclass

class GenericTemplate (AbstractAttrib ute):
__metaclass__ = MetaTemplate

def __init__(self):
""" instantiates all nested classes upon creation """

# builds a copy of the field list. this is needed to allow
# customizations of the instance not to be reflected in the
# original class field list.
self._fields = list(self.__cla ss__._fields)

# auto instantiates nested classes and attributes
if debug_auto_inst antiation:
print "AutoInstantiat ion <%s>: fieldlist = %s" % \
(self.name, self._fields)
for fname, fobj in self._fields:
if isclass(fobj) and issubclass(fobj ,Container):
# found a nested class
if debug_auto_inst antiation:
print "AutoInstantiat ion <%s>: field[%s] is a "
"Container Subclass" % (self.name, fname)
fobj = fobj()
setattr(self, fname, fobj)
elif isinstance(fobj , AbstractAttribu te):
# found an attribute instance
if debug_auto_inst antiation:
print "AutoInstantiat ion <%s>: field[%s] is an "
"Attribute Instance" % (self.name, fname)
# removed: parent links are still being thought out,
# and I'm not even sure if they're a good idea
# setattr(fobj, 'parent', self)
setattr(fobj, 'name', fname)
else:
if debug_auto_inst antiation:
print "AutoInstantiat ion <%s>: field[%s] is "
"unknown" % (self.name, fname)

def iterfields(self ):
for fname, fobj in self._fields:
yield getattr(self, fname)

def __repr__(self):
return "<%s '%s'>" % (self.__class__ .__name__, self.name,)

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #8
On Wed, 13 Oct 2004 13:50:00 +0200, Peter Otten <__*******@web. de> wrote:
Bengt Richter wrote:
Or, an ugly hack that might work for a while, depending on how
co_names is really generated. It seems in order of occurrence
(including right hand sides of assignment, but still top down) ...
>> import sys
>> def getnames(): return sys._getframe(1 ).f_code.co_nam es

...
>> def MC(cname, cbases, cdict):

... names = cdict.get('ordi c',[])
... names = [name for name in names if name in cdict]
... cdict['ordic'] = dict([(name,i) for i,name in enumerate(names )])
... return type(cname, cbases, cdict)
...
>> class C(object):

... __metaclass__ = MC # really a function shortcut
... x = 123
... y = sys
... z = 0
... ordic = getnames()
...
>> C.ordic

{'ordic': 5, '__module__': 0, '__metaclass__' : 1, 'y': 3, 'x': 2, 'z': 4}


A metaclass /function/ and sys._getframe() exercised on a class definition
- I think you have raised the bar for what qualifies as a hack :-)


Hey, I came first with that a couple of weeks ago :-) but in truth, it
was Alex Martelli that pointed to me that a metaclass function would
work... but not only is it not recommended, it's also said to make
Guido shudder ;-) Seriously, although it works, it's not recommended
practice. Metaclasses are supposed to be classes, not functions.

As for the getframe, I have played with it a little bit also. But in
the end I have chosen to use a simple counter, using
itertools.count (). More pythonic IMHO. And no need for clever hacks,
when all that is needed is to order the elements in the order they are
executed (which count() can guarantee). There are two situations where
the simpler counter works, but the getframe hack doesn't:

-- if I have a loop inside my class that is used to declare bunch of
attributes, all of them will have the same line number... but a
different sequence number if the simpler method is chosen.

-- if a function is called that returns a bunch of attributes (not
common practice, but still possible). All attributes are at the same
line in this case. Example:

class Foo:
a,b,c = myfunc(...)

Of course, we are now getting into corner cases that show how much are
we pushing class statements in Python. The _sane_ way to make it all
work would be to have a hook to provide a user-defined dict to the
class locals() dir; aternatively, the natice dict() could provide a
ordered interface (but then it wouldn't be a simple hash mapping, a
more complex structure such as a tree would be needed). Both are far
from happening in Python 2.x, IMHO... and I really doubt if dicts will
ever be changed to accomodate ordering, even in Python 3.0. Too much
hassle for too little gain. A hook function seems to be more sensible.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #9
Peter Otten wrote:
If you want to record the order of these definitions, you need to pass a
custom dictionary that keeps track of assignments in the class generation
code (basically a normal python function comprising the class suite).
Unfortunately that dictionary - which you see later as the classdict
parameter of the metaclass __new__() method - is always a dict created in C,
as was recently discussed on c.l.py (sorry, but all keywords I remember are
'metaclass' and 'martelli' - not very selective :-). Below is my (clumsy)
attempt for a workaround:

import itertools

class OrderedValue(ob ject):
newIndex = itertools.count (1).next
def __init__(self, value):
self.value = value
self.index = self.newIndex()


That's the solution I finally did after my post (I think I found the
thread you were referring to). In my case, having to create instances
has not been so bad, as I can use them to put other information:

class SomeClass(BinTy pe):
x = Member(Int32)
y = Member(Int16)

class SomeOtherClass( BinType):
a = ArrayMember(Int 16, size=256)
b = Member(SomeClas s)
c = Member(Int32)

This way, I can generate abstract documentation of my binary formats
without instantiating my types and can instantiate them to dump binary data.

Thx and Regards,
Nicolas
Jul 18 '05 #10

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

Similar topics

7
3660
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc. And i have things to offer, and to request. And a lot of ideas, but who needs them.... here's an example (from type_struct.py):
0
1612
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs): super(Metaclass, cls).__init__(cls, name, bases, *args, **kwargs) print 'cls=',cls, cls.__new cls.__new__ = staticmethod(cls.__new) def __new(self,cls,*args):
5
2261
by: Irmen de Jong | last post by:
Hi, I've developed the Metaclass below, because I needed a way to make a bunch of classes thread-safe. I didn't want to change every method of the class by adding lock.aqcuire()..lock.release() around the existing code. So I made a metaclass that essentially replaces every method of a class with a 'wrapper' method, that does the locking, invocation, unlocking. Is this the right approach? It seems to work fine. But I have
33
2520
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
16
1616
by: ironfroggy | last post by:
Hoping this isn't seeming too confusing, but I need to create a metaclass and a class using that metaclass, such that one of the bases of the metaclass is the class created with that metaclass. I can't figure out a way to do this, even after trying to add the class as a base after the classes have been created. Is there some way I can get this to work properly?
14
2028
by: Pedro Werneck | last post by:
Hi I have a class A, with metaclass M_A, and class B, subclass of A, with metaclass M_B, subclass of M_A. A class C, subclass of B must have M_B or a subclass of it as metaclass, but what if I need to 'disable' the code in M_B on C ? The correct way to do that seems to be with a M_C metaclass, subclass of M_B, implementing but not calling parent class methods, or calling 'type' methods.
9
1659
by: Christian Eder | last post by:
Hi, I think I have discovered a problem in context of metaclasses and multiple inheritance in python 2.4, which I could finally reduce to a simple example: Look at following code: class M_A (type) :
4
3312
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a custom metaclass with a __getattribute__ method, the method is used when acessing some attribute directly with the class object, but not when you do it from the instance.
0
8666
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
8597
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
8880
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
7703
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...
0
5857
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
4356
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...
1
3033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2319
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1992
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.