473,376 Members | 1,086 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,376 software developers and data experts.

MethodType/FunctionType and decorators

Hi all!

I am pretty new to Python, so please excuse me if I am missing
something. Lately, I've been playing with decorators and I am a bit
confused about some behavior. Here is the code that puzzles me:

in python shell:

def function():
pass

class A(object):
def method(self):
pass

from types import MethodType
from types import FunctionType

if type(function) is FunctionType:
print "this is what I expect"

if type(A.method) is MethodType:
print "this is what I expect"

so far so good... everything seems logical.

But if a decorator is declared things are becoming different:

def deco(function):
if type(function) is MethodType:
print "MethodType"
elif type(function) is FunctionType:
print "FunctionType"

@deco
def function2():
pass

# ==this prints out FunctionType (oke)

class A(object):
@deco
def method(self):
pass

# ==this prints out FunctionType (???)

Can somebody shed some light on why I am seeing this?

(Using Python 2.5.1 on Win XP).

TIA,

../alex
--
..w( the_mindstorm )p.

Jul 4 '07 #1
11 4714
On Jul 5, 1:52 am, Alex Popescu <the.mindstorm.mailingl...@gmail.com>
wrote:
Hi all!

I am pretty new to Python, so please excuse me if I am missing
something. Lately, I've been playing with decorators and I am a bit
confused about some behavior. Here is the code that puzzles me:

in python shell:

def function():
pass

class A(object):
def method(self):
pass

from types import MethodType
from types import FunctionType

if type(function) is FunctionType:
print "this is what I expect"

if type(A.method) is MethodType:
print "this is what I expect"

so far so good... everything seems logical.

But if a decorator is declared things are becoming different:

def deco(function):
if type(function) is MethodType:
print "MethodType"
elif type(function) is FunctionType:
print "FunctionType"

@deco
def function2():
pass

# ==this prints out FunctionType (oke)

class A(object):
@deco
def method(self):
pass

# ==this prints out FunctionType (???)

Can somebody shed some light on why I am seeing this?

(Using Python 2.5.1 on Win XP).

TIA,

./alex
--
.w( the_mindstorm )p.
First of all I should correct my example to use
isinstance(function_or_method, builtin_factory_function).

Secondly, I guess what is happening is the following:

- when testing from outside the class definition, the function is
already attached to the class instance and this is the reason why its
type is instancemethod
- for decorators, my test is executed before the class is defined and
so at that moment the function is still a function; it will become a
methodinstance only after the class definition is closed

Is this correct or am I just fabulating here?

TIA,

../alex
--
..w( the_mindstorm )p.
Jul 4 '07 #2
Alex Popescu <th***********************@gmail.comwrote:
...
- when testing from outside the class definition, the function is
already attached to the class instance and this is the reason why its
type is instancemethod
To be more precise: when you access any attribute of a class (or
instance thereof), Python checks if that attribute is a descriptor (i.e.
the attribute's type has a __get__ method -- there are finer
distinctions based on whether it also has a __set__ method, i.e. is or
isn't a "data descriptor", but they don't come into play here).

A function does have in its type a __get__ method, IOW every
(Python-coded) function is a descriptor (a non-data one, btw).

So, when you access C.f where C is a class and f's type is Python-coded
function, you get the results of calling __get__ on that f object
itself. Those results are... the envelope, please!... ta-da: a newly
minted method object (whose im_func is f).

- for decorators, my test is executed before the class is defined and
so at that moment the function is still a function; it will become a
methodinstance only after the class definition is closed
The function object will never become a method object; it will remain a
function object (and you can get at it with C.__dict__['f'] for
example); but if you access that name as an attribute of C (or of an
instance of C), e.g. as C.f or getattr(C, 'f'), f.__get__ will be called
(and return a freshly minted method object whose im_func is f).
Is this correct or am I just fabulating here?
You have roughly the right idea (as far as decorators are concerned),
just a slightly skewed vision of the rapport between function objects
and method objects, which I hoped I helped clarify.

Here are a few toy-level examples of what I've been saying, I hope they
can further help your understanding of function vs method issues:
>>def f(): pass
....
>>class C(object): pass
....
>>a=C.f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'f'
>>C.f = f
a=C.f
b=C.f
a == b
True
>>a is b
False
>>type(a), type(b)
(<type 'instancemethod'>, <type 'instancemethod'>)
>>a.im_func, b.im_func
(<function f at 0x66030>, <function f at 0x66030>)
>>a.im_func is f is b.im_func
True
>>c=f.__get__(C)
type(c)
<type 'instancemethod'>
>>c.im_func
<function f at 0x66030>
>>c.im_func is C.__dict__['f'] is f
True
Alex
Jul 5 '07 #3
Alex Popescu wrote:
- for decorators, my test is executed before the class is defined and
so at that moment the function is still a function; it will become a
methodinstance only after the class definition is closed
Closer, but still not quite right. Even after the class
is defined, the function sitting inside it is still
just an ordinary function. You can see this by looking
at

A.__dict__['method']

An instancemethod is only created when you look the
method up in an instance, i.e.

a = A()
a.method

The instancemethod encapsulates a value for 'self' and
a reference to the underlying function. This is known
as a "bound method".

(You also get an instancemethod if you look the method
up in the class, i.e.

A.method

but in that case the instancemethod doesn't contain
a value for 'self', and is known as an "unbound
method".)

--
Greg
Jul 5 '07 #4
On Jul 5, 3:41 am, a...@mac.com (Alex Martelli) wrote:
<snip>
Alex already explained everything beautifully. I will just add a link
to
the definite guide to descriptors: http://users.rcn.com/python/download/Descriptor.htm

Michele Simionato

(who spent lot of brain cycles studying descriptors *before* that
guide was written :-()

Jul 5 '07 #5
On Jul 5, 11:17 am, Michele Simionato <michele.simion...@gmail.com>
wrote:
On Jul 5, 3:41 am, a...@mac.com (Alex Martelli) wrote:
<snip>

Alex already explained everything beautifully. I will just add a link
to
the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm

Michele Simionato

(who spent lot of brain cycles studying descriptors *before* that
guide was written :-()
Guys, I appreciate a lot your help and explanations. It looks like I
have to read/play a bit more as some of the terms/ideas are pretty new
to me (coming to Python with a 10 years Java bag, and only with a
small dynlang bag - Ruby, Perl).

Once again thanks,

../alex
--
..w( the_mindstorm )p.
Jul 5 '07 #6
Alex Popescu wrote:
On Jul 5, 11:17 am, Michele Simionato <michele.simion...@gmail.com>
wrote:
>On Jul 5, 3:41 am, a...@mac.com (Alex Martelli) wrote:
>><snip>
Alex already explained everything beautifully. I will just add a link
to
the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm

Michele Simionato

(who spent lot of brain cycles studying descriptors *before* that
guide was written :-()

Guys, I appreciate a lot your help and explanations. It looks like I
have to read/play a bit more as some of the terms/ideas are pretty new
to me (coming to Python with a 10 years Java bag, and only with a
small dynlang bag - Ruby, Perl).

Once again thanks,
Please also realise that for someone new to the language you have dived
right into the nitty gritty. This isn't necessarily a bad way to learn,
but it does mean that there's a lot of background to assimilate as you
go along.

Good luck with your studies.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Jul 5 '07 #7
On Jul 5, 3:32 pm, Steve Holden <s...@holdenweb.comwrote:
Alex Popescu wrote:
On Jul 5, 11:17 am, Michele Simionato <michele.simion...@gmail.com>
wrote:
On Jul 5, 3:41 am, a...@mac.com (Alex Martelli) wrote:
><snip>
Alex already explained everything beautifully. I will just add a link
to
the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm
Michele Simionato
(who spent lot of brain cycles studying descriptors *before* that
guide was written :-()
Guys, I appreciate a lot your help and explanations. It looks like I
have to read/play a bit more as some of the terms/ideas are pretty new
to me (coming to Python with a 10 years Java bag, and only with a
small dynlang bag - Ruby, Perl).
Once again thanks,

Please also realise that for someone new to the language you have dived
right into the nitty gritty. This isn't necessarily a bad way to learn,
but it does mean that there's a lot of background to assimilate as you
go along.

Good luck with your studies.
I am starting to realize this on my own :-). The true story is that
while working on Groovy (I am a committer on this dynlang meant to run
on the Java VM: http://groovy.codehaus.org) and reading some Python
materials, my interest grew exponentially. And now I have decided to
see how other succesfull java project I have co-created (TestNG:
http://testng.org) would look like in Python (this giving me the
opportunity to explore Python in more depth).

Thanks for the encouragement.

../alex
--
..w( the_mindstorm )p.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Jul 5 '07 #8
On Jul 5, 3:17 pm, Alex Popescu <the.mindstorm.mailingl...@gmail.com>
wrote:
The true story is that
while working on Groovy (I am a committer on this dynlang meant to run
on the Java VM:http://groovy.codehaus.org) and reading some Python
materials, my interest grew exponentially. And now I have decided to
see how other succesfull java project I have co-created (TestNG:http://testng.org) would look like in Python (this giving me the
opportunity to explore Python in more depth).
If you are interested in testing, you should give a look at 1)
doctest; 2) py.test
(Python unittest framework should be old hat to you and not worth
looking at).

Michele Simionato

Jul 5 '07 #9
On Jul 5, 5:01 pm, Michele Simionato <michele.simion...@gmail.com>
wrote:
On Jul 5, 3:17 pm, Alex Popescu <the.mindstorm.mailingl...@gmail.com>
wrote:
The true story is that
while working on Groovy (I am a committer on this dynlang meant to run
on the Java VM:http://groovy.codehaus.org) and reading some Python
materials, my interest grew exponentially. And now I have decided to
see how other succesfull java project I have co-created (TestNG:http://testng.org) would look like in Python (this giving me the
opportunity to explore Python in more depth).

If you are interested in testing, you should give a look at 1)
doctest; 2) py.test
(Python unittest framework should be old hat to you and not worth
looking at).

Michele Simionato

Thanks for the pointers Michele. I have heard about those and their
are on my todo list. However, the features of TestNG
are very advanced and I don't think they are available in other
frameworks (TestNG is not a unit testing framework,
but a full flavored testing framework that fits perfectly functional
testing, integration testing, and with some of the
very advanced features even performance and load testing).
But I will make sure I am taking a look at the ones you pointed me to
(and I think I have a longer list available around).

bests,

../alex
--
..w( the_mindstorm )p.
Jul 5 '07 #10
Alex Popescu <th***********************@gmail.comwrote:
...
frameworks (TestNG is not a unit testing framework,
but a full flavored testing framework that fits perfectly functional
testing, integration testing, and with some of the
very advanced features even performance and load testing).
Nice! Does it have any integration/interoperability with FIT/Fitnesse,
btw? For certain kinds of "functional testing" (where the specs are to
be mostly written by people with no programming skills but strong
business, accounting, &c, i.e., people _used_ to thinking in terms of
tables and spreadsheets) I find that approach very interesting...
Alex
Jul 6 '07 #11
On Jul 6, 6:19 am, a...@mac.com (Alex Martelli) wrote:
Alex Popescu <the.mindstorm.mailingl...@gmail.comwrote:

...
frameworks (TestNG is not a unit testing framework,
but a full flavored testing framework that fits perfectly functional
testing, integration testing, and with some of the
very advanced features even performance and load testing).

Nice! Does it have any integration/interoperability with FIT/Fitnesse,
btw? For certain kinds of "functional testing" (where the specs are to
be mostly written by people with no programming skills but strong
business, accounting, &c, i.e., people _used_ to thinking in terms of
tables and spreadsheets) I find that approach very interesting...

Alex
That's an interesting idea! We never tried that before but I will
definitely look into it. Thanks for the suggestion Alex.

../alex
--
..w( the_mindstorm )p.
Jul 6 '07 #12

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

Similar topics

16
by: Michele Simionato | last post by:
I have read with interest the recent thread about closures. The funny thing is that the authors are arguing one against the other but I actually agree with all of them and I have a proposal that...
4
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...
17
by: daishi | last post by:
For what it's worth: As far as I know, the proposed @decorator syntax will be the first time that two logical lines of python with the same indentation will not be independent of one another....
4
by: RebelGeekz | last post by:
Just my humble opinion: def bar(low,high): meta: accepts(int,int) returns(float) #more code Use a metadata section, no need to introduce new messy symbols, or mangling our beloved visual...
2
by: Guido van Rossum | last post by:
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason...
0
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
0
by: George Sakkis | last post by:
Hi all, I wonder why types.MethodType fails under python 2.2: Python 2.2.2 (#1, Jun 25 2003, 18:52:43) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>...
11
by: Helmut Jarausch | last post by:
Hi, are decorators more than just syntactic sugar in python 2.x and what about python 3k ? How can I find out the predefined decorators? Many thanks for your help, Helmut Jarausch
2
by: Andrew West | last post by:
Probably a bit of weird question. I realise decorators shouldn't be executed until the function they are defined with are called, but is there anyway for me to find all the decorates declared in a...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
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,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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 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.