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 "FunctionTy pe"
@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. 11 4785
On Jul 5, 1:52 am, Alex Popescu <the.mindstorm. mailingl...@gma il.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 "FunctionTy pe"
@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(func tion_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.
Alex Popescu <th************ ***********@gma il.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
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
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 :-()
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.
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 -------------
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 -------------
On Jul 5, 3:17 pm, Alex Popescu <the.mindstorm. mailingl...@gma il.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
On Jul 5, 5:01 pm, Michele Simionato <michele.simion ...@gmail.com>
wrote:
On Jul 5, 3:17 pm, Alex Popescu <the.mindstorm. mailingl...@gma il.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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 may
be of some interest. To refresh your memory, I report here some
quotation from that thread.
Jacek Generowicz:
> I sumbit to you that read-only closures are rare in Python because
> they are a recent addition to the language.
|
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 looked like about 20:20 split on the
following syntaxes:
1 def func(arg1, arg2, arg3) :
function...
2 def func(arg1, arg2, arg3):
function...
|
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. Previously, when looking at:
some_python(code)
and_some_more = stuff
there was no need to look at the the first line in order to know what
|
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 cleanliness of python.
|
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 to accept it would be to pacify the
supporters of the proposal, and that just isn't a good enough reason
in language design.
However, it got pretty darn close! I'm impressed with how the
community managed to pull together and face the enormous...
| |
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 Methods
Version: $Revision: 1.34 $
Last-Modified: $Date: 2004/09/03 09:32:50 $
Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
|
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.
>>> import types
>>> class X:
.... def f(self,attr): return getattr(self,attr)
|
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
|
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 file when
I import it? Or perhaps anyway to find the decorators by loading the
file by other methods (with out simply parsing it by hand).
Basically what I'm looking for is a way to, given a python file, look
through that file and find all the...
|
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...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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...
|
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...
|
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...
|
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();...
|
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |