In today's experiment, I was wondering if I could make the comparison
operators (<,<=,>=,>) work on classes (types) according to inheritance.
The idea is, for example, classes lower in the class hierarchy would be
less than (more specialized) than classes they inherit from.
class A(object):
pass
class B(A):
pass
B < A # should be True
In my first attempt I tried putting __lt__ into the class definition for A
and then assigning it as a staticmethod. This doesn't work, but something
was happening; <,<=,>=,> are still valid as applied to classes.
Because class is to instance as metaclass is to class, I found that the
place to put these methods is in the class' metaclass.
class MetaCMP(type):
def __lt__(cls,other):
for base in cls.__bases__:
if type(base) != cls.__class__:
continue
if base <= other:
return 1
return 0
def __le__(cls,other):
if cls == other:
return 1
for base in cls.__bases__:
if type(base) != cls.__class__:
continue
if base <= other:
return 1
return 0
def __gt__(cls,other):
for base in other.__bases__:
if type(base) != cls.__class__:
continue
if cls >= base:
return 1
return 0
def __ge__(cls,other):
if cls == other:
return 1
for base in other.__bases__:
if type(base) != cls.__class__:
continue
if cls >= base:
return 1
return 0
__metaclass__ = MetaCMP
Now, with the above code, we can replace a call to isinstance.
type( B() ) <= A # True
It seems natural enough to my math trained eye.
But now we have non-comparible objects, which confuses the sorting issue.
class C:
pass
C < A # False
A < C # False
For example, if we wanted a "total" order ( always either X<=Y or Y<=X )
we could remove __ge__ and __gt__ from MetaCMP. It's not clear to me
exactly which comparison methods "list.sort" uses. (The ideal sort here is
the topological sort.)
I also thought about extending this order so that "B() <= A" would behave
the same way. It would be rather more strange. Is it so natural that an
instance is "smaller" than it's type? Perhaps; the instance can have
attributes that override it's type, which is reminiscent of some kinds of
inheritance.
Finally, the feature request. If "type" implemented these semantics for
comparison would it break existing code? Does anyone rely on "1<dict"
being True, or that we have a total order (one of "<","==" or ">" always
True) ? Another quandry is that one could just as naturally argue for the
reverse ordering.
Comments sought (can you guess what + might do to classes?).
Simon Burton. 5 2051
Simon Burton wrote: In today's experiment, I was wondering if I could make the comparison operators (<,<=,>=,>) work on classes (types) according to inheritance.
The idea is, for example, classes lower in the class hierarchy would be less than (more specialized) than classes they inherit from.
class A(object): pass
class B(A): pass
B < A # should be True
Is this an exercise to help you learn about metaclasses, or do you
actually want to be able to check whether B is a subclass of A. If the
latter, then try issubclass(B, A). Otherwise, ignore this comment
David
On Thu, 11 Sep 2003 03:03:02 +0000, David C. Fox wrote:
.... B < A # should be True
Is this an exercise to help you learn about metaclasses, or do you actually want to be able to check whether B is a subclass of A. If the latter, then try issubclass(B, A). Otherwise, ignore this comment
David
Both. Well, aha, "issubclass" makes my implementation
of ge/le and friends a bit silly. Actually i was annoyed
with "isinstance", it seems like it should be part of the syntax
(eg."<="). Look at this: "issubclass". It has 10 chars!!
Lazy when i can be,
Simon Burton.
In article <pa****************************@webone.com.au>,
Simon Burton <si****@webone.com.au> wrote: Both. Well, aha, "issubclass" makes my implementation of ge/le and friends a bit silly. Actually i was annoyed with "isinstance", it seems like it should be part of the syntax (eg."<="). Look at this: "issubclass". It has 10 chars!!
<= is supposed to be a total ordering, so it is not a good idea to use
it for partial orders such as subclass hierarchies.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
On Thu, 11 Sep 2003 11:45:01 -0700, David Eppstein
<ep******@ics.uci.edu> wrote: In article <pa****************************@webone.com.au>, Simon Burton <si****@webone.com.au> wrote:
Both. Well, aha, "issubclass" makes my implementation of ge/le and friends a bit silly. Actually i was annoyed with "isinstance", it seems like it should be part of the syntax (eg."<="). Look at this: "issubclass". It has 10 chars!!
<= is supposed to be a total ordering, so it is not a good idea to use it for partial orders such as subclass hierarchies.
Is it? I never came across such a supposition, which in itself says
nothing because I have very little experience anyway, but what about
set inclusion in the sets module which can be written as <=?
With my best regards,
G. Rodrigues
In article <q6********************************@4ax.com>,
Gon?alo Rodrigues <op*****@mail.telepac.pt> wrote: <= is supposed to be a total ordering, so it is not a good idea to use it for partial orders such as subclass hierarchies.
Is it? I never came across such a supposition, which in itself says nothing because I have very little experience anyway, but what about set inclusion in the sets module which can be written as <=?
I don't have 2.3 yet, so haven't used sets yet, but what happens if you
try to sort a list of sets?
I found a message
< http://mail.python.org/pipermail/pyt...nuary/015454.h
tml> from Guido wondering about this but didn't see what the response
was...
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Stephan Diehl |
last post by:
I have a question about metaclasses:
How would be the best way to "merge" different metaclasses?
Or, more precisely, what is the best way to merge metaclass functionality?
The idea is basicly...
|
by: Simon Burton |
last post by:
It seems this is a more general way to build classes than inheritance.
Is this a reasonable viewpoint?
>>>
>>> def meth1(self):
.... print "i am meth1"
....
>>> def meth2(self):
.... ...
|
by: Mike C. Fletcher |
last post by:
Slides from my PyGTA presentation on Tuesday, focusing mostly on
why/where you would want to use meta-classes, are available in PDF format:
...
|
by: Michele Simionato |
last post by:
> Hello, my name is Skip and I am metaclass-unaware. I've been programming in
> Python for about ten years and I have yet to write a metaclass. At first I
> thought it was just that metaclasses...
|
by: Michael Sparks |
last post by:
Anyway...
At Europython Guido discussed with everyone the outstanding issue with
decorators and there was a clear majority in favour of having them, which
was good. From where I was sitting it...
|
by: Steffen Glückselig |
last post by:
Hello,
I've been experimenting with metaclasses a bit (even though I am quite
a newbie to python) and stumpled over the following problem in my code:
class Meta(type):
def __init__(cls, name,...
|
by: Létezõ |
last post by:
I use Python 2.4.4. Please read the code below:
-----------------------------------------------------------
from new import classobj
def mymeta(name,bases,clsdict):
print 'meta: %s'%name...
|
by: Alan Isaac |
last post by:
Forman's book is out of print.
Is there a good substitute?
Thanks,
Alan Isaac
|
by: Mirko Dziadzka |
last post by:
Hi all
I'm playing around with metaclasses and noticed, that there is small
but mesurable a performance difference in the code shown below. With a
more complex example I get a 5 percent...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
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: 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...
|
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,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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 ...
| |