473,597 Members | 2,749 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to get a unique id for bound methods?

I have several situations in my code where I want a unique identifier
for a method of some object (I think this is called a bound method). I
want this id to be both unique to that method and also stable (so I can
regenerate it later if necessary).

I thought the id function was the obvious choice, but it doesn't seem to
work. The id of two different methods of the same object seems to be the
same, and it may not be stable either. For instance:

class cls(object):
def __init__(self):
print id(self.meth1)
print id(self.meth2)
def meth1(self):
pass
def meth2(self):
pass

c = cls()
3741536
3741536
print id(c.meth1)
3616240
print id(c.meth2)
3616240

I guess that just means bound methods aren't objects in their own right,
but it surprised me.

The "hash" function looks promising -- it prints out consistent values
if I use it instead of "id" in the code above. Is it stable and unique?
The documentation talks about "objects" again, which given the behavior
of id makes me pretty nervous.

Any advice would be much appreciated.

-- Russell
Aug 19 '05 #1
12 2690
Russell E. Owen wrote:
The id of two different methods of the same object seems to be the
same, and it may not be stable either.
Two facts you're (apparently) unaware of are conspiring against you:

1) the "id" of an object is consistent for the lifetime of the object,
but may be reused after the object goes away

2) methods are bound on an as-needed basis and then normally discarded
(unless you do something to keep them around)

An illustration:

class cls(object):
def meth1(self):
pass
def meth2(self):
pass

c = cls()
m1 = c.meth1
print id(m1)
-1209779308
m2 = c.meth1
print id(m2)
-1209652732
I guess that just means bound methods aren't objects in their own right,
but it surprised me.
Nope, they're objects, they just don't tend to be around very long.
The "hash" function looks promising -- it prints out consistent values
if I use it instead of "id" in the code above. Is it stable and unique?
The documentation talks about "objects" again, which given the behavior
of id makes me pretty nervous.

Any advice would be much appreciated.


I think you'll get the best advice from this group if you tell us what
the larger problem is that you're trying to solve.
--
Benji York

Aug 19 '05 #2
On Fri, 19 Aug 2005 13:29:19 -0700, "Russell E. Owen" <ro***@cesmail. net> wrote:
I have several situations in my code where I want a unique identifier
for a method of some object (I think this is called a bound method). I
want this id to be both unique to that method and also stable (so I can
regenerate it later if necessary).
I thought the id function was the obvious choice, but it doesn't seem to
work. The id of two different methods of the same object seems to be the
same, and it may not be stable either. For instance:
The id function works, but you are applying it to transient objects, which
is what bound methods are unless you cause them to persist one way or another.
class cls(object):
def __init__(self):
print id(self.meth1)
print id(self.meth2)
def meth1(self):
pass
def meth2(self):
pass

c = cls()
3741536
3741536 This means that self.meth1 only existed long enough to be passed to id,
and when id was done with determining its id, self.meth1 was freed.
Then self.meth2 was created, and happened to use a representation space
with the same id as was used for self.meth1. If the two objects (bound methods
here) existed at the same time, they would be guaranteed not to have the same id
unless they were actually the same object.
print id(c.meth1)
3616240
print id(c.meth2)
3616240 This happened to re-use a representation space with another id.
I guess that just means bound methods aren't objects in their own right,
but it surprised me. No, they are objects in their own right. You were surprised by your
[mis]interpretation of the above results ;-)
The "hash" function looks promising -- it prints out consistent values
if I use it instead of "id" in the code above. Is it stable and unique?
The documentation talks about "objects" again, which given the behavior
of id makes me pretty nervous.

Any advice would be much appreciated.

If you want a particular bound method to have a stable and persistent id,
make it persist, e.g.,
class cls(object): ... def __init__(self):
... print id(self.meth1)
... print id(self.meth2)
... def meth1(self):
... pass
... def meth2(self):
... pass
... c = cls() 49219060
49219060 print id(c.meth1) 49219020 print id(c.meth2) 49219020

Ok, those were transient, now nail a couple of bound methods down: cm1 = c.meth1
cm2 = c.meth2
And you can look at their id's all you like:
print id(cm1) 49219020 print id(cm2) 49219060 print id(cm1) 49219020 print id(cm2) 49219060

But every time you just evaluate the attribute expression c.meth1 or c.meth2
you will get a new transient bound method object, with a new id:
print id(c.meth1) 49219180 print id(c.meth2) 49219180

But the ones we forced to persist by binding the expression values to cm1 and cm2
above still have the same ids as before:
print id(cm1) 49219020 print id(cm2)

49219060

So the question would be, why do you (think you ;-) need ids for
these bound methods as such? I.e., what is the "situation" in your code?

Regards,
Bengt Richter
Aug 19 '05 #3
Russell E. Owen wrote:
The "hash" function looks promising -- it prints out consistent values
if I use it instead of "id" in the code above. Is it stable and unique?
The documentation talks about "objects" again, which given the behavior
of id makes me pretty nervous.

I dont know how the hash of a bound method is calculated,but as the
function of the method is a stable and referenced object and as
instances lives are in your hands,then an id(self)^id(sel f.meth.im_func)
should be a chance for that 'hash' function.

def methodId(boundM ethod):
return id(boundMethod. im_self)^id(bou ndMethod.im_fun c)

class cls(object):
def __init__(self):
print methodId(self.m eth1)
print methodId(self.m eth2)
def meth1(self):
pass
def meth2(self):
pass

c = cls()
print methodId(c.meth 1)
print methodId(c.meth 2)

I think this is giving what you expected.

Regards Paolino

_______________ _______________ _____
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it
Aug 19 '05 #4
In article <ma************ *************** ************@py thon.org>,
Benji York <be***@benjiyor k.com> wrote:
Russell E. Owen wrote:
The id of two different methods of the same object seems to be the
same, and it may not be stable either.


Two facts you're (apparently) unaware of are conspiring against you:

1) the "id" of an object is consistent for the lifetime of the object,
but may be reused after the object goes away

2) methods are bound on an as-needed basis and then normally discarded
(unless you do something to keep them around)


Thank you and Bengt Richter. You both explained it very well.

The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python "function" (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
"function". A hash-like name would be perfect, meaning a name that is
always the same for a particular python "function" and always different
for a different python "function". That would save a lot of housekeeping.

Does the built-in hash function actually do the job?

If I centralize all tk callback management and keep objects that
represent the tk callback around then I can avoid the whole issue. I was
hoping to avoid that, because it complicates housekeeping and adds a
risk of memory leaks (at least I think so; right now tk deallocates its
callback functions in the few cases I care about so I don't worry about
it.)

-- Russell

P.S. Paolino: thank you also for your kind reply. Your suggestion sounds
very useful if I only want a hash for a bound function, but in this case
since I want a hash for any callable entity I'm not sure it'll work.
Aug 19 '05 #5
On Fri, 19 Aug 2005 16:33:22 -0700, "Russell E. Owen" <ro***@cesmail. net> wrote:
[...]

The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python "function" (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
"function". A hash-like name would be perfect, meaning a name that is
always the same for a particular python "function" and always different
for a different python "function". That would save a lot of housekeeping.

Why do you need a name? Can you post an example snippet that shows
a callback function being used with Tkinter as you would wish?
I have a feeling there is a much simpler solution than you are imagining ;-)

Regards,
Bengt Richter
Aug 20 '05 #6
In article <43************ *****@news.oz.n et>,
bo**@oz.net (Bengt Richter) wrote:
On Fri, 19 Aug 2005 16:33:22 -0700, "Russell E. Owen" <ro***@cesmail. net>
wrote:
[...]

The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python "function" (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
"function". A hash-like name would be perfect, meaning a name that is
always the same for a particular python "function" and always different
for a different python "function". That would save a lot of housekeeping.

Why do you need a name? Can you post an example snippet that shows
a callback function being used with Tkinter as you would wish?
I have a feeling there is a much simpler solution than you are imagining ;-)


Here is an example (simplified from my real code; I may have introduced
an error in the process). I could switch to the twisted framework, but
this code has been working very well and it saves my users from having
to install a 3rd party package.

-- Russell

def addTkCallback(t k, func):
tkName = "cb%d" % hash(func)
tk.createcomman d(tkNname, func)
return tkName

class TkSocket(TkBase Socket):
def __init__(self,
addr,
port,
binary=False,
readCallback = None,
stateCallback = None,
tkSock = None,
):
...
try:
# create the socket and configure it
self._sock = self._tk.call(" socket", ...)
self._tk.call(" fconfigure", self._sock, ...)

# add callbacks; the write callback is just used to detect
state
readName =addTkCallback( self._tk, self._doRead)
self._tk.call(' fileevent', self._sock, "readable",
readName)
connName = addTkCallback(s elf._tk, self._doConnect )
self._tk.call(' fileevent', self._sock, "writable", connName
except Tkinter.TclErro r, e:
raise RuntimeError(e)
Aug 22 '05 #7
Russell E. Owen wrote:
The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python "function" (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
"function" . A hash-like name would be perfect, meaning a name that is
always the same for a particular python "function" and always different
for a different python "function". That would save a lot of housekeeping.
have you tried Tkinter's built-in _register method?
import Tkinter
w = Tkinter.Tk()
help(w._registe r) Help on method _register in module Tkinter:

_register(self, func, subst=None, needcleanup=1) method of Tkinter.Tk
instance
Return a newly created Tcl function. If this
function is called, the Python function FUNC will
be executed. An optional function SUBST can
be given which will be executed before FUNC.
def func(): .... print "Hello"
.... name = w._register(fun c)
name '10768336func'
w.tk.call(name)

Hello
'None'

</F>

Aug 22 '05 #8
Russell E. Owen wrote:
I have several situations in my code where I want a unique identifier
for a method of some object (I think this is called a bound method). I
want this id to be both unique to that method and also stable (so I can
regenerate it later if necessary).

def persistent_boun d_method(m): .... return m.im_self.__dic t__.setdefault( m.im_func.func_ name, m)
.... class A: .... def x(self):
.... return
.... a=A()
a.x is a.x False persistent_boun d_method(a.x) is persistent_boun d_method(a.x) True


Aug 23 '05 #9
In article <ma************ *************** ************@py thon.org>,
"Fredrik Lundh" <fr*****@python ware.com> wrote:
Russell E. Owen wrote:
The current issue is associated with Tkinter. I'm trying to create a tk
callback function that calls a python "function" (any python callable
entity).

To do that, I have to create a name for tk that is unique to my python
"function ". A hash-like name would be perfect, meaning a name that is
always the same for a particular python "function" and always different
for a different python "function". That would save a lot of housekeeping.
have you tried Tkinter's built-in _register method?
import Tkinter
w = Tkinter.Tk()
help(w._registe r)

Help on method _register in module Tkinter:

_register(self , func, subst=None, needcleanup=1) method of Tkinter.Tk
instance
Return a newly created Tcl function. If this
function is called, the Python function FUNC will
be executed. An optional function SUBST can
be given which will be executed before FUNC.


Thanks. That looks like just the thing. I think I had seen it but was
deterred by the leading underscore (suggesting an internal method whose
interface might change). Still, I guess if it gets modified I can just
change my code.

-- Russell
Aug 23 '05 #10

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

Similar topics

3
21129
by: Kylotan | last post by:
Although I see lots of references to them in various documentation, I can't find a decent explanation of exactly what they are. I'm guessing that it's a reference to a method that remembers which object it came from, and that when it's called, it passes that object as the first parameter (which would conventionally be 'self'). Is this correct? -- Ben Sizer
0
749
by: August1 | last post by:
This is a follow up to using these functions to produce lottery numbers to an outfile, then read the numbers from the file to the screen. Although other methods are certainly available. #include <iostream> #include <fstream>//for declaring objects of the ofstream and ifstream #include <time.h> #include <stdlib.h> using namespace std;
8
2935
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or after the class was modified. I need this to work for both old ('classic') and new style classes, at both 2.3 and 2.4. I of course want to avoid side effects, and to make the solution as light-weight as possible.
18
1983
by: Neil | last post by:
I am using SQL 7 with an MS Access 2000 MDB front end, using bound forms with ODBC linked tables. In one form, the user needs to be able to check a box to select one or more records. This is accomplished with a local table containing two fields: the primary key value of the SQL table and a boolean field used for the check box. Since the local table used to contain the boolean field is local to the MDB file, the result is a heterogeneous...
3
4569
by: Phil | last post by:
I am looking to set up a hyperlink control on a form to retrieve letters that correspond to a record on a form. That is, there may be 100 form records, and I would like each of those form records to have a hyperlink button or control on it. that when pushed, pulls up the unique Word document associated with that form record. In this example, there would 100 unique letters associated with 100 unique form records. I tried working with...
19
4083
by: James Fortune | last post by:
I have a lot of respect for David Fenton and Allen Browne, but I don't understand why people who know how to write code to completely replace a front end do not write something that will automate the code that implements managing unbound controls on forms given the superior performance of unbound controls in a client/server environment. I can easily understand a newbie using bound controls or someone with a tight deadline. I guess I need...
3
8457
by: Richard Albrecht | last post by:
I have been trying to figure out for days on how to read values from a Bound ListBox. The listBox gets the values from an Access Table. I can read values fine for Non-Bound ListBoxes, But the same code doesn't work for Bound, see below: Any one of these work for a non-bound listbox. Code:
18
7321
by: JJ | last post by:
Now I know this question has been asked many times, but I cannot seem to find a good site which summarises the methods possible in vb .net. I am after a way of producing a unique serial number for my app. The program would produce a unique identifier for the computer, then I would psovide the user with a serial number unique to their machine. In other words I would like to check for things like: i) Hard disk (not volume) serial number...
1
274
by: srinivasan srinivas | last post by:
HI Peter, It works will for instance and class methods. But it doesn't work for static methods. Can you tel me how to pickle static methods as well?? Thanks, Srini ----- Original Message ---- From: Peter Otten <__peter__@web.de> To: python-list@python.org Sent: Wednesday, 2 July, 2008 12:53:19 PM
0
7969
marktang
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...
0
7886
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
8381
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
8035
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
8258
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
6688
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
3886
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
2404
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
0
1238
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.