473,809 Members | 2,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why are so many built-in types inheritable?

Hi folks!

For debugging purposes I tried this:

--- snip ---
def foo(): pass
function = type(foo)

class PrintingFunctio n(function):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print args, kwargs
return function.__call __(self, args, kwargs)

class DebugMeta(type) :
def __new__(self, name, bases, dict):
for name in dict:
if type(dict[name]) is function:
dict[name] = PrintingFunctio n(dict[name])

--- snap ---

Now I tought I were able to let all maethod of classes with DebugMeta as
metaclass print out their arguments. But I got the following sad error:

TypeError: Error when calling the metaclass bases
type 'function' is not an acceptable base type

That's awful, isn't it?
What could I do to get the above code working? (No, I disliked to re-
implement <type 'function'> without this unpleasant behaviour in Python.)

Greetings,
F. Sidler

Mar 18 '06 #1
17 1215
Hello? Or, is there any obvious reason for this behaviour I don't see?

Mar 25 '06 #2
Fabiano Sidler wrote:
Hi folks!

For debugging purposes I tried this:

--- snip ---
def foo(): pass
function = type(foo)

class PrintingFunctio n(function):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print args, kwargs
return function.__call __(self, args, kwargs)

class DebugMeta(type) :
def __new__(self, name, bases, dict):
for name in dict:
if type(dict[name]) is function:
dict[name] = PrintingFunctio n(dict[name])

--- snap ---

Now I tought I were able to let all maethod of classes with DebugMeta as
metaclass print out their arguments. But I got the following sad error:

TypeError: Error when calling the metaclass bases
type 'function' is not an acceptable base type

That's awful, isn't it?
What could I do to get the above code working? (No, I disliked to re-
implement <type 'function'> without this unpleasant behaviour in Python.)


You could do this with a simple decorator:
http://wiki.python.org/moin/PythonDe...fec0ff4b3653f4

or I think your class PrintingFunctio n would work as
class PrintingFunctio n(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print args, kwargs
return self.func(*args , **kwargs)

Kent
Mar 25 '06 #3
Kent Johnson <ke**@kentsjohn son.com> wrote:
You could do this with a simple decorator:
http://wiki.python.org/moin/PythonDe...fec0ff4b3653f4

or I think your class PrintingFunctio n would work as
class PrintingFunctio n(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print args, kwargs
return self.func(*args , **kwargs)


The problem with this is that the func_code attribute would contain
the code of PrintingFunctio n instead of func. What I wanted to do, is
to keep the original behaviour, i.e. set the variable __metaclass__ to
DebugMeta and so get debug output, without changing a function and
getting the original function's code object by the func_code
attribute, not PrintigFunction 's one. That's why I *must* inherit from
<type 'function'>.

Greetings,
F. Sidler
Mar 25 '06 #4
Fabiano Sidler wrote:

[snipped]
The problem with this is that the func_code attribute would contain
the code of PrintingFunctio n instead of func. What I wanted to do, is
to keep the original behaviour, i.e. set the variable __metaclass__ to
DebugMeta and so get debug output, without changing a function and
getting the original function's code object by the func_code
attribute, not PrintigFunction 's one. That's why I *must* inherit from
<type 'function'>.
No, you don't have to:
import new
import types
class DebugFunction(o bject): .... def __init__(self, func):
.... object.__setatt r__(self, 'func', func)
.... def __get__(self, obj, objtype):
.... return new.instancemet hod(self, obj, objtype)
.... def __call__(self, *args, **namedargs):
.... print args, namedargs
.... func = object.__getatt ribute__(self, 'func')
.... return func(*args, **namedargs)
.... def __getattribute_ _(self, name):
.... func = object.__getatt ribute__(self, 'func')
.... return getattr(func, name)
.... def __setattr__(sel f, name, value):
.... func = object.__getatt ribute__(self, 'func')
.... setattr(func, name, value)
.... def __delattr__(sel f, name):
.... func = object.__getatt ribute__(self, 'func')
.... delattr(func, name)
.... class DebugMeta(type) : .... def __new__(meta, name, bases, dict):
.... for name, obj in dict.iteritems( ):
.... if isinstance(obj, types.FunctionT ype):
.... dict[name] = DebugFunction(o bj)
.... return type.__new__(me ta, name, bases, dict)
.... class Example(object) : .... __metaclass__ = DebugMeta
.... def spam(self, *args, **namedargs):
.... """Spam spam spam spam. Lovely spam! Wonderful spam!"""
.... pass
.... e = Example()
e.spam('eggs', anwser=42) (<__main__.spa m object at ...>, 'eggs') {'anwser': 42} e.spam.__doc__ 'Spam spam spam spam. Lovely spam! Wonderful spam!' e.spam.im_func. func_code

<code object spam at ..., file "<stdin>", line 3>

Greetings,
F. Sidler


Ziga

Mar 25 '06 #5
25 Mar 2006 13:58:17 -0800, Ziga Seilnacht <zi************ @gmail.com>:
No, you don't have to:
Okay, but I'd prefer! ;)
[a lot of python code]


That's what I wanted to avoid. Additionally, the possibility to do it
this way doesn't make it reasonable that <type 'function'> is
inheritable. Are there any reasons for that?

Greetings,
F.Sidler
Mar 26 '06 #6
I really wanted to learn the reason for this, nothing else! ;)

Greetings,
F. Sidler
Mar 28 '06 #7
Fabiano Sidler wrote:
I really wanted to learn the reason for this, nothing else! ;)


I suspect performance reasons. Can't give you details but function
is used so often that it deserves special treatment.

Georg
Mar 28 '06 #8
Op 2006-03-28, Georg Brandl schreef <g.************ *@gmx.net>:
Fabiano Sidler wrote:
I really wanted to learn the reason for this, nothing else! ;)


I suspect performance reasons. Can't give you details but function
is used so often that it deserves special treatment.


I would find this a bit odd. I think integers, tuples and lists
are used just as often if not more and they aren't treated special.

I for one would gladly treat some performance for the ability
to subclass slices.

class islice(slice):
...

doesn't work
And if I just write

class islice:

def __init__(self, start, stop, step):
self.start = start
self.stop = stop
self.step = step

then the following doesn't work:

lst = range(20)
sl = islice(2,6,None )
lst[sl]
So much for ducktyping.

--
Antoon Pardon
Mar 30 '06 #9
Antoon Pardon wrote:
Op 2006-03-28, Georg Brandl schreef <g.************ *@gmx.net>:
Fabiano Sidler wrote:
I really wanted to learn the reason for this, nothing else! ;)


I suspect performance reasons. Can't give you details but function
is used so often that it deserves special treatment.


I would find this a bit odd. I think integers, tuples and lists
are used just as often if not more and they aren't treated special.


Well, for integers, tuples and lists you can at least give useful
use cases for subclassing.

I now looked in the code, and the ability to subclass is given by a
flag in the type object. This is there in list or int, but not in function.

A little performance is saved by the fact that PyFunction_Chec k, which
verifies that an object is indeed a function, doesn't have to check for
subtypes.

So, if you want to make functions or slices subclassable, ask on python-dev!

Georg
Mar 30 '06 #10

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

Similar topics

1
3121
by: Alex Elbert | last post by:
Hi I have built dynamic HTMLTable. Now I want to attach it directly to the Email Body - it is already built, so why not to use a ready table. However, I cannot find the way of getting plain HTML text out of dynamically built control. I tried to put my table between div and read div.innerHTML then - HTTP exception has been thrown. Any thoughts, ladies and gentelmen
1
2111
by: William | last post by:
Looking for a pre built dotnet corporate or small business website template.
1
246
by: William | last post by:
Looking for a pre built dotnet corporate or small business website template.
48
4965
by: meyer | last post by:
Hi everyone, which compiler will Python 2.5 on Windows (Intel) be built with? I notice that Python 2.4 apparently has been built with the VS2003 toolkit compiler, and I read a post from Scott David Daniels where he said that probably the VS2003 toolkit will be used for Python 2.5 again. However, even before the release of Python 2.5, I cannot seem to find many retailers around here that still carry Visual Studio 2003, and some were a...
3
1798
by: drewj840 | last post by:
I built a Windows service that sweeps a set of folders every 60 seconds and puts the files into a SQL Server database. I am creating a second service that will delete this set of folders and recreate them each night based on a list of active customers. I need to be able to stop the first service before starting the second service and then when the second service completes restart the first service. I haven't the slightest idea how to proceed.
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10379
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
10115
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
9199
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
6881
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
5550
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
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3014
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.