473,795 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

importing a method

hi,

I have an object defined with a number of hardcoded methods.

Class soandso:
def __init__(self):
self.this = 0
self.that = 1
def meth1(self):
...
def meth2(self):
...
def custom(self):
pass

I want to allow the user to write a python module that declares a
function so that myprogram can import it and attribute it to the custom
method of the soandso object. So far so good, that is an easy thing to
do in Python.

import usermodule
a=soandso()
a.custom = usermodule.func tion

But, what if the method had to access the self attributes (self.this
and self.that) of the soandso object?

Can it be done? and if so, what is the most Pythonic way of doing it?

thanks in advance,

Flávio

Nov 27 '05
19 1867
First of all,why do you think the new module is deprecated? (I can't
find anything in the docs to indicate this.)

As for using MethodType in the types module: There's nothing in the
module documentation that suggests that you can call MethodType as a
function as you suggest, only that it is the name of the type of
methods of user-defined class instances.. So, while calling it might
work, it sounds like you are using an undocumented feature...

Lastly, in an earlier post after Ben Finney suggested using the
new.instancemet hod function, you replied:
If you read my original post, I had no intention of atributing the
user's method to the class, but to the instance.
I'd like to point out that the instancemethod( ) function returns a
method object, bound to its *instance* argument if it isn't None --
which sounds like exactly what you want/need.

-Martin
Flavio wrote: Addendum to my last reply:

although the New Method is deprecated,

new.instancemet hod (from Antoon's message) can be replaced by

from types import MethodType

f.show = MethodType(show ,f)

and every thing still works.


Nov 28 '05 #11
I'd like to point out to the OP that using a function's __get__ method
this way only works with new-style classes and their instances...not
with the example in the shown in original post.

-Martin
Alex Martelli wrote:
Flavio <fc******@gmail .com> wrote:
This "new" module sounds pretty cool, too bad its deprecated...

I would not want to add a dependancy to a deprecated module in my code.
But maybe I'll check the code for instancemethod within it and see what
it does.


If you have a function f and want to make an instancemethod out of it,
you can simply call f.__get__(thein stance, theclass) and that will build
and return the new instancemethod you require.
Alex


Nov 28 '05 #12
> First of all,why do you think the new module is deprecated? (I can't
find anything in the docs to indicate this.)
Its in the docs of python 2.4. I dont know about older versions:

Help on module new:

NAME
new - Create new objects of various types. Deprecated.

FILE
/usr/lib/python2.4/new.py

MODULE DOCS
/usr/share/doc/python-docs-2.4.2/html/module-new.html

DESCRIPTION
This module is no longer required except for backward
compatibility.
Objects of most types can now be created by calling the type
object.
As for using MethodType in the types module: There's nothing in the
module documentation that suggests that you can call MethodType as a
function as you suggest, only that it is the name of the type of
methods of user-defined class instances.. So, while calling it might
work, it sounds like you are using an undocumented feature...


If you look at new.py, all it does is import the functions from types
and rename them. For MethodType is goes like this

from types import MethodType as instancemethod

so instance method *is* Methodtype.

Moreover, I tried and it works ;-)

So this solution is perfect once adapted not to depend on "new".

Thanks,

Flávio

Nov 28 '05 #13
> If you have a function f and want to make an instancemethod out of it,
you can simply call f.__get__(thein stance, theclass) and that will build
and return the new instancemethod you require.


I think that

f.show = MethodType(show ,f)

is less cryptic than f.__get__(insta nce, class)

Flávio

Nov 28 '05 #14
On Mon, 28 Nov 2005 08:16:12 -0800, Martin Miller wrote:
First of all,why do you think the new module is deprecated? (I can't
find anything in the docs to indicate this.)


Did you try help(new) from an interactive prompt?
py> new.__doc__.spl itlines()[0]
'Create new objects of various types. Deprecated.'
--
Steven.

Nov 28 '05 #15
Martin Miller <gg************ ****@dfgh.net> wrote:
I'd like to point out to the OP that using a function's __get__ method
this way only works with new-style classes and their instances...not
with the example in the shown in original post.


Uh, why not?
class old: pass .... def f(self): print self .... o=old()
o.z = f.__get__(o, old)
o.z <bound method old.f of <__main__.old instance at 0x53d78>>


There's a million reason to avoid using old-style classes in new code,
but it doesn't seem to me that this is one of them. What am I missing?
Alex
Nov 29 '05 #16
Flavio <fc******@gmail .com> wrote:
If you have a function f and want to make an instancemethod out of it,
you can simply call f.__get__(thein stance, theclass) and that will build
and return the new instancemethod you require.


I think that

f.show = MethodType(show ,f)

is less cryptic than f.__get__(insta nce, class)


Hmmm, we're using different identifiers here for the same purposes,
making direct comparisons difficult. Using clear identifiers in every
case, and avoiding keywords, we'd have something like:

from types import MethodType
instance.show = MethodType(show , instance, aclass)

versus

instance.show = show.__get__(in stance, aclass)

[[you do need to pass the class if you want the repr of instance.show to
look nice, and this applies equally to both cases]].

I guess that instantiating a type (here, instancemethod) by calling it
with appropriate arguments is the "normal" approach, and calling
MethodType has the further advantage of working with different types as
the callable (first argument), not just functions. The advantage of
__get__ is only polymorphism on different descriptor types, but that
looks rather less important. So, "cryptic" apart (an issue on which one
could debate endlessly -- I'd argue that descriptors should be well
familiar by the time one starts generating methods on the fly;-),
calling MethodType does cover a wider range of uses.
Alex
Nov 29 '05 #17
Sorry, I seldom look at the built-in __doc__ strings or use the
'help()' function. Instead I usually refer to the html or winhelp
versions of the documentation, and for Python 2.4.1 there's nothing in
section 3.28 on the 'new' module that mentions that it deprecated -- so
thanks to you and Flávio for the information.

Using help on MethodType gave me the following somewhat surprising
output [truncated here]:
import types
help(types.Meth odType)
Help on class instancemethod in module __builtin__:

class instancemethod( object)
| instancemethod( function, instance, class)
|
| Create an instance method object.
[snip]

Which I take to mean that 'instancemethod ' is no longer [just] a
function in the deprecated 'new' module but is also a built-in class.

However and somewhat confusingly (to me anyway), a search in the help
docs file turns up the following:
7.5.3 Method Objects
There are some useful functions that are useful for working with method objects.

PyTypeObject PyMethod_Type
This instance of PyTypeObject represents the Python method type. This is
exposed to Python programs as types.MethodTyp e.
... [snip]

Which, as you can see, claims that types.MethodTyp e is actually an
instance of a PyTypeObject (not the class instancemethod that
help(types.Meth odType) indicated).

Best,
-Martin

====
Steven D'Aprano wrote: On Mon, 28 Nov 2005 08:16:12 -0800, Martin Miller wrote:
First of all,why do you think the new module is deprecated? (I can't
find anything in the docs to indicate this.)


Did you try help(new) from an interactive prompt?
py> new.__doc__.spl itlines()[0]
'Create new objects of various types. Deprecated.'
--
Steven.

Flávio wrote: First of all,why do you think the new module is deprecated? (I can't
find anything in the docs to indicate this.)


Its in the docs of python 2.4. I dont know about older versions:

Help on module new:

NAME
new - Create new objects of various types. Deprecated.

FILE
/usr/lib/python2.4/new.py

MODULE DOCS
/usr/share/doc/python-docs-2.4.2/html/module-new.html

DESCRIPTION
This module is no longer required except for backward
compatibility.
Objects of most types can now be created by calling the type
object.
As for using MethodType in the types module: There's nothing in the
module documentation that suggests that you can call MethodType as a
function as you suggest, only that it is the name of the type of
methods of user-defined class instances.. So, while calling it might
work, it sounds like you are using an undocumented feature...


If you look at new.py, all it does is import the functions from types
and rename them. For MethodType is goes like this

from types import MethodType as instancemethod

so instance method *is* Methodtype.

Moreover, I tried and it works ;-)

So this solution is perfect once adapted not to depend on "new".

Thanks,

Flávio


Dec 1 '05 #18
You're not missing anything -- it's my own [mis-]understanding that
descriptors would only work with new-style classes, not the old-style
ones used in the OP's example.

However your example certainly proves that is not the case, even if you
go one step further and call the bound method/function:
o.z()
<__main__.old instance at 0x009D5F30>

So I stand corrected -- thank you.

Best,
-Martin

==============
Alex Martelli wrote:
Martin Miller <gg************ ****@dfgh.net> wrote:
I'd like to point out to the OP that using a function's __get__ method
this way only works with new-style classes and their instances...not
with the example in the shown in original post.


Uh, why not?
class old: pass ... def f(self): print self ... o=old()
o.z = f.__get__(o, old)
o.z <bound method old.f of <__main__.old instance at 0x53d78>>


There's a million reason to avoid using old-style classes in new code,
but it doesn't seem to me that this is one of them. What am I missing?
Alex


Dec 1 '05 #19
Martin Miller <gg************ ****@dfgh.net> wrote:
You're not missing anything -- it's my own [mis-]understanding that
descriptors would only work with new-style classes, not the old-style
ones used in the OP's example.

However your example certainly proves that is not the case, even if you
go one step further and call the bound method/function:
o.z()

<__main__.old instance at 0x009D5F30>

So I stand corrected -- thank you.


You're welcome. Your previous misunderstandin g may be due to the fact
that (differently from __get__) the special method __set__ doesn't work
when the descriptor is held in an old-style class... to be more precise,
it's not even given a chance, since assigning to an instance attribute
(where the instance's old-style) just blithely sets the value in the
instance's __dict__, without even checking for the existence of a
descriptor by that name in the class.
Alex
Dec 1 '05 #20

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

Similar topics

11
2236
by: Jeff Wagner | last post by:
I am importing a file which contains a persons name (firstName, middleName, etc). If I define a function to do this, how can I use the variables outside of that function? Here is the code: import string def getName(): data = open("enterName.txt")
2
2040
by: Awah Teh | last post by:
I am working on a project that involves importing IIS Log files into a SQL Server database (and these logfiles are big --> Some up to 2GB in size). Up until now I thought that DTS or the BULK INSERT command was the fastest method out there, but still proves to be long (taking an average of 45mns to an hour to process each log file). Because I have to import the log files from three web heads in my cluster (therefore 2GB log files per...
4
4706
by: Little PussyCat | last post by:
Hello, I nee to write something that will transfer excel data into an SQL Server table. I have for another database application I wrote have it importing Excel spreadsheet data using cell by cell, row by row method. This is fully automated so the user can choose whatever spreadsheet they want to import and press a button which sits on a VB6 frontend. This has been good for that situsation but it can be very slow when there
9
4036
by: Edward S | last post by:
I budget for a Project in an Excel sheet as illustrated below. The months below are usually a 2 year period i.e. 24 months, though it could be over 24 months depending upon a Project. I then need to input this in an Access database, where I do a comparison with the Actual cost. The table “TblBudget” in Access is made of 4 fields, namely: (1) CostElement (2) CostCenter (3) Month (4) Amount$. At the moment this method is very cumbersome....
14
1909
by: MLH | last post by:
GHudson has working procedures posted at http://www.access-programmers.co.uk/forums/showthread.php?t=66320 They work. Relationships, however, and some minor default settings are not preserved. Reestablishing some default settings and settings is a small price to pay for a set of text files that may save your database from total loss #AND# seem to remove the database bloat as well. I was wondering if someone knew how to preserve the...
7
3308
by: Timothy Shih | last post by:
Hi, I am trying to figure out how to use unmanaged code using P/Invoke. I wrote a simple function which takes in 2 buffers (one a byte buffer, one a char buffer) and copies the contents of the byte buffer into the character pointer. The code looks like the following: #include <stdio.h> #include <stdlib.h> #include "stdafx.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call,
0
958
by: Ivan Lam | last post by:
Hi All, Thanks for reading my question. I am a newbie of VC .Net, and I am facing a problem about importing DLL. I have searched from the web and I download a simple sample. And the code is as follow:
3
1765
by: martin | last post by:
Hi, is there a dotnet function (other than the old isnumeric from VB) to check whether an object is numeric or not. also I notice that all the old vb functions such as split / isnumeric / ubound etc are still availible by default in any VB.net web application. is this because the vb library is being imported?? would it be best to totally remove this library (assuming that it is being imported - which I can't see in my references) so...
7
1968
by: hg | last post by:
Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: ..../.../../plugin/name1/name1.py ..... ..../.../../plugin/namen/namen.py
2
1366
by: HMS Surprise | last post by:
Greetings, First I will admit I am new to Python but have experience with C++ and some Tcl/Tk. I am starting to use a tool called MaxQ that uses jython. I have been studying Rossum's tutorial but still am unclear on importing, the use of self, and calling functions with their own name in quotes. In the code below the lines between #Start and #End are generated by browsing web pages. In a large test this section can become quite large....
0
9522
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,...
0
10448
Oralloy
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...
1
10167
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,...
1
7544
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
6784
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
5440
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...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2922
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.