473,698 Members | 2,841 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Metaclass with name overloading.

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__ = OverloadingClas s

att = 1
att = 3

def meth(self):
pass

def meth(self, arg):
return arg
I would then like the dictionary received by OverloadingClas s.__new__
to look something like this:

{'att': (1,3),
'meth: (<function meth at 0x4018e56c>, <function meth at 0x4018e80c>) }

IOW, each name bound in the class definition should have associated
with it, a tuple containing all the objects which were bound to that
name, rather merely keeping the most recent binding for any given
name.

I was wondering whether it would be possible to achieve this by
forcing Python to use some dicitonary proxy (which accumulates values,
rather that keeping just the last value to be associated with a key),
instead of dict, when executing the class definiton?

Is something like this at all possible in pure Python? or does in
require fiddling around in the guts of the parser?
Jul 18 '05
33 2522
im*****@aerojoc key.com (Carl Banks) writes:
def alltuple(name,b ases,clsdict):
return tuple(clsdict.v alues()) __metaclass__ = alltuple


WBMSWA12FB !

It never occurred to me that a metaclass didn't have to be a _class_.
Jul 18 '05 #31
Jacek Generowicz <ja************ **@cern.ch> wrote:
al*****@yahoo.c om (Alex Martelli) writes:
Jacek Generowicz <ja************ **@cern.ch> wrote:
...
> No, you can't, and it's not just a parser issue. Python uses
> direct C calls to the native dict type. It's hard coded,

I feared this would be the case.
It's not (not in 2.4 at least)


For what definition of "hard coded" ?


Is there more than one? As I already quoted on this very thread:

if (PyDict_CheckEx act(x))
err = PyDict_SetItem( x, w, v);
else
err = PyObject_SetIte m(x, w, v);

so, the "direct C call to the native dict type" only happens if x is
exactly of that type, otherwise the generic abstract call happens
instead and can deal with dispatching the functionality as needed.

Basically, the PyDict_SetItem is now there, and guarded with a
PyDict_CheckExa ct, only as an optimization: x will be of native dict
type overwhelmingly often.

-- the STORE_NAME is quite ready to find a non-dict as the frame's
f_locals. The problem is getting your object to be used as the
frame's f_locals in the first place -- hard but that only affects a
few spots in ceval.c.


So, from the perspective of trying to code it in pure Python, it _is_
hard coded, IIUC.


For some value of "it", sure, but NOT because of "direct C calls to the
native dict type" spread hither and yon (as used to be the case).
Rather, the issue is strictly with how a frame gets built and handled.

I never claimed nothing at all is hard-coded (even in 2.4), just that
the specific issue with "direct C calls" _isn't_ (in 2.4) for the case
of interest (STORE_NAME opcodes' execution).
(Unfortunately, I cannot afford the luxury of playing with the Python
implementation itself; I must deliver code which works with a
bog-standard Python 2.3.4. I'd love to have the time to play with
ceval.c on my own account ... but that is another luxury I cannot
afford :-( )


If you need to support 2.3.4 and can't even consider extensions, your
options are indeed severely limited -- I don't recall, but it's even
possible that, for THAT release, the "direct C calls" assertion is valid
(which is why I was careful to say "for 2.4 at least" every time). It
matters hugely (to most would-be extenders, who could surely afford to
use extensions for the purpose) whether it is or not, of course: making
some kind of special-purpose frame and getting it used appropriately
might be feasible, but if there are direct C calls hardwired all over
the place then no solution at all is feasible _within the 2.3.*
constraint_.
Alex
Jul 18 '05 #32
Jacek Generowicz <ja************ **@cern.ch> wrote:
im*****@aerojoc key.com (Carl Banks) writes:
def alltuple(name,b ases,clsdict):
return tuple(clsdict.v alues())
__metaclass__ = alltuple


WBMSWA12FB !

It never occurred to me that a metaclass didn't have to be a _class_.


You should have seen Guido's face when he first saw me give a
presentation on "use and abuse of custom metaclasses" -- apparently,
judging from his horrified expression, it hadn't occurred to him,
either, and he didn't like it half a bit... since then I've been quite
careful against actually using this idea in production code.

Actually I believed I showed something more like:

class whatever:
def __metaclass__(c lsname, clsbases, clsdict):
return <I don't remember what>
...etc etc...

i.e., an "anonymous metaclass", so to speak. But that's a minor aspect.
After all, something like:

class yetanother:
class __metaclass__(t ype):
...etc etc...

is just as so-to-speak "anonymous" yet IS nowadays quite an accepted
idiom...!
Alex
Jul 18 '05 #33
Jacek Generowicz <ja************ **@cern.ch> wrote:
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__ = OverloadingClas s
def meth(self):
pass
def meth(self, arg):
return arg


It's not the literal syntax you're asking for, but using my technique
for multiple dispatch in Python achieves the effect you're looking
for. It has nothing to do with metaclass, but it lets you provide
multiple "signatures " for a call. Not just number of arguments, but
also their types (if you want: you can also generically specify a
descendent of object).

See http://www-106.ibm.com/developerwork.../l-pydisp.html
for more details.

Yours, David...
Jul 18 '05 #34

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

Similar topics

2
1815
by: Jp Calderone | last post by:
Due to some bizarre constraints placed on me, I've written the following metaclass: import types def remove(t, o): return tuple() class BizarreMetaclass(type): def __new__(klass, name, bases, attrs):
3
1687
by: Fernando Rodriguez | last post by:
Hi, I'm having trouble with a metaclass suposed to check the method signature of its classes. Here's the metaclass: class MetaChecker(type): def __new__(cls, name, bases, attribs): for name, value in attribs.iteritems():
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):
4
1572
by: Paul Morrow | last post by:
One of the beautiful things about Python is its clear, minimal syntax. So we must resist adding new syntax to the language, especially where there is a reasonable alternative. I believe that Stefen Eischet's suggestion for automatically determining a method's type (class/instance/static) from the name of its first formal parameter is a reasonable alternative to any/all of the decorator syntax proposals. Just as the Python system...
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
2
1941
by: zipher | last post by:
After searching through comp.lang.python and the web regarding metaclasses, I could not find an example for customing classes using metaclass parameters. I want to be able to create a class at runtime by calling some function or 'meta-constructor' which returns a customized class and sets a class attribute according a given parameter. Ideally, I'd be able to do something like:
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
8683
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
8609
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
8901
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
8871
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...
1
6528
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
5862
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
4371
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...
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.