473,385 Members | 2,269 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,385 software developers and data experts.

__dict__ for instances?

While using PyGTK, I want to try and define signal handlers
automagically, without explicitly writing the long dictionary (i.e. I
want to use signal_autoconnect()).

To do this, I need something that will inspect the current "self" and
return a dictionary that looks like:

{
"method_name" : self.method_name
}

Class.__dict__ does something very similar, but when I use it, either
I'm doing something wrong or it doesn't return methods bound to "self",
and python complains a wrong number of arguments is being passed to the
methods (one instead of two).

instance.__dict__ on the other hand returns an empty dictionary.

This looks like it should be easy, but I can't find the solution :(

--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGRlnFldnAQVacBcgRAugIAJ0aqM6ZNKeUZUFCur7ODE bGcMFvCgCgxze2
LCUqdGi4nCvZrwnFru2To6Y=
=+8Zd
-----END PGP SIGNATURE-----

May 13 '07 #1
12 2407
On May 12, 5:20 pm, Ivan Voras <ivoras@__fer.hr__wrote:
While using PyGTK, I want to try and define signal handlers
automagically, without explicitly writing the long dictionary (i.e. I
want to use signal_autoconnect()).

To do this, I need something that will inspect the current "self" and
return a dictionary that looks like:

{
"method_name" : self.method_name

}

Class.__dict__ does something very similar, but when I use it, either
I'm doing something wrong or it doesn't return methods bound to "self",
and python complains a wrong number of arguments is being passed to the
methods (one instead of two).

instance.__dict__ on the other hand returns an empty dictionary.

This looks like it should be easy, but I can't find the solution :(

--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!

signature.asc
1KDownload
I think you want "dir(instance)" __dict__ returns the instance
variables and values as a dictionary, but doesn't return methods.
dir() returns a list of the instance's methods and variables. Then
you'd need to iterate over the list with type() looking for instance
methods

instance = Class.Class()
dict = {}
methods = [f for f in dir(instance) if str(type(instance.f)) == "<type
'instancemethod'>"]
for m in methods:
dict[m.name] = m

The above is untested. I'm sure there is a better way to do this.

~Sean

May 13 '07 #2
ha**********@gmail.com wrote:
I think you want "dir(instance)" __dict__ returns the instance
Part of the problem is that dir(instance) returns a list of strings, so
iterating the dir(instance) gets me strings, not methods. Alternatively,
is there a way to get a "bound" instance by its name - some
introspection function perhaps?
variables and values as a dictionary, but doesn't return methods.
It does on a Class :(

--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGRvbdldnAQVacBcgRAvtoAJ46Z2Tkwo+MS6khyh9UZ4 w2vqbccQCg11yr
SbMsN4ezb8lWw3Yz3evcDAc=
=dxlb
-----END PGP SIGNATURE-----

May 13 '07 #3
Ivan Voras a écrit :
ha**********@gmail.com wrote:

>>I think you want "dir(instance)" __dict__ returns the instance


Part of the problem is that dir(instance) returns a list of strings, so
iterating the dir(instance) gets me strings, not methods. Alternatively,
is there a way to get a "bound" instance by its name - some
introspection function perhaps?
getattr(obj, name)
>
>>variables and values as a dictionary, but doesn't return methods.


It does on a Class :(
Usually, methods are attributes of the class, not of the instance.
May 13 '07 #4
Ivan Voras a écrit :
While using PyGTK, I want to try and define signal handlers
automagically, without explicitly writing the long dictionary (i.e. I
want to use signal_autoconnect()).

To do this, I need something that will inspect the current "self" and
return a dictionary that looks like:

{
"method_name" : self.method_name
}

Class.__dict__ does something very similar, but when I use it, either
I'm doing something wrong or it doesn't return methods bound to "self",
and python complains a wrong number of arguments is being passed to the
methods (one instead of two).
You're not doing anything wrong, that's just how Python works. "methods"
are wrapper objects around function objects attributes. The wrapping
only happens at lookup time, and returns different kind of "method"
wrapper (resp. unbound or bound methods) if the attribute is looked up
on an instance or a class (there are also the staticmethod/classmethod
things, but that's not your problem here).

You can build the dict you're looking for using dir() and getattr():

from types import MethodType

autoconnect_dict = {}
for name in dir(self):
attr = getattr(self, name)
if isinstance(attr, MethodType):
autoconnect_dict[name] = attr
return autoconnect_dict

instance.__dict__ on the other hand returns an empty dictionary.
the instance's __dict__ only stores per-instance attributes. While it's
technically possible to attach methods per-instance, it's definitively a
corner case.
May 13 '07 #5
Ivan Voras <ivoras@__fer.hr__scribis:
While using PyGTK, I want to try and define signal handlers
automagically, without explicitly writing the long dictionary (i.e. I
want to use signal_autoconnect()).

To do this, I need something that will inspect the current "self" and
return a dictionary that looks like:

{
"method_name" : self.method_name
}
Nope, at least for PyGTK 2 :) See below.

[...]
This looks like it should be easy, but I can't find the solution :(
Use the doc, Luke, oops, Ivan :)
Citing the gtk.glade.XML.signal_autoconnect documentation:
def signal_autoconnect(dict)
dict: a mapping or an instance
^^^^^^^^

The signal_autoconnect() method is a variation of the
gtk.glade.XML.signal_connect method. It uses Python's introspective
features to look at the keys (if dict is a mapping) or attributes (if
^^^^^^^^^^^^^^
dict is an instance) and tries to match them with the signal handler
^^^^^^^^^^^^^^^^^^^
names given in the interface description. The callbacks referenced by
each matched key or attribute are connected to their matching signals.
The argument is called dict due to compatibility reasons since
originally only the mapping interface was supported. The instance
variant was introduced in PyGTK 2.0.

So simply using signal_autoconnect(self) should work.

AdiaÅ*, Marc
May 13 '07 #6
On May 13, 4:30 am, Ivan Voras <ivoras@__fer.hr__wrote:
half.ital...@gmail.com wrote:
I think you want "dir(instance)" __dict__ returns the instance

Part of the problem is that dir(instance) returns a list of strings, so
iterating the dir(instance) gets me strings, not methods. Alternatively,
is there a way to get a "bound" instance by its name - some
introspection function perhaps?
variables and values as a dictionary, but doesn't return methods.

It does on a Class :(

--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!

signature.asc
1KDownload
I tried.

~Sean

May 13 '07 #7
Marc Christiansen wrote:
Nope, at least for PyGTK 2 :) See below.
Aaah, but....!
[...]
>This looks like it should be easy, but I can't find the solution :(
Use the doc, Luke, oops, Ivan :)
Citing the gtk.glade.XML.signal_autoconnect documentation:
def signal_autoconnect(dict)
dict: a mapping or an instance
^^^^^^^^
I should have mentioned - I tried it already and it didn't work. The
specific error I get is:

"WARNING: "on_button_clicked" not callable or a tuple"

once for each handler when I call autoconnect. And I've got a recent
version of pyGTK (2.10.4) so it should.
--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGR0jOldnAQVacBcgRAvHqAKCdYJxSmCqvyrBXVTPQMc 50R5KsMwCfULkH
jpSJzgL8qBJRaQIP8xKQrXA=
=SsEg
-----END PGP SIGNATURE-----

May 13 '07 #8
Bruno Desthuilliers wrote:
You're not doing anything wrong, that's just how Python works. "methods"
are wrapper objects around function objects attributes. The wrapping
only happens at lookup time, and returns different kind of "method"
wrapper (resp. unbound or bound methods) if the attribute is looked up
on an instance or a class (there are also the staticmethod/classmethod
things, but that's not your problem here).
Got it, thanks for the explanation!

--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGR0kPldnAQVacBcgRAls/AJ9vyGQG9Hvasr0Qex5gTl+wDD3gTgCeNBo0
GQNo30dEuhwVZaxfHitgBv4=
=8ZXE
-----END PGP SIGNATURE-----

May 13 '07 #9
Ivan Voras a écrit :
Marc Christiansen wrote:

>>Nope, at least for PyGTK 2 :) See below.


Aaah, but....!

>>[...]
>>>This looks like it should be easy, but I can't find the solution :(

Use the doc, Luke, oops, Ivan :)
Citing the gtk.glade.XML.signal_autoconnect documentation:
def signal_autoconnect(dict)
dict: a mapping or an instance
^^^^^^^^


I should have mentioned - I tried it already and it didn't work. The
specific error I get is:

"WARNING: "on_button_clicked" not callable or a tuple"
Please post the relevant code and the full traceback.
May 13 '07 #10
Bruno Desthuilliers wrote:
>"WARNING: "on_button_clicked" not callable or a tuple"
Please post the relevant code and the full traceback.
The code:

Class W:
def __init__(self):
self.xml = gtk.glade.XML("glade/mainwin.glade")
self.window = self.xml.get_widget("mainwin")
self.xml.signal_autoconnect(self)

w = W()
gtk.main()

The error (not an exception, only the message appears and the handler
doesn't work):

** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked'
not callable or a tuple

(the file has some 20 lines, not 7551)
--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGR5XqldnAQVacBcgRAu7xAJ9COrvqgow1O0gcK6F+AS 7rfu/AlwCg3rnI
fVb71HKuapkbaE+cwt+4JT0=
=2of5
-----END PGP SIGNATURE-----

May 13 '07 #11
Ivan Voras a écrit :
Bruno Desthuilliers wrote:
>>"WARNING: "on_button_clicked" not callable or a tuple"
Please post the relevant code and the full traceback.

The code:

Class W:
def __init__(self):
self.xml = gtk.glade.XML("glade/mainwin.glade")
self.window = self.xml.get_widget("mainwin")
self.xml.signal_autoconnect(self)

w = W()
gtk.main()

The error (not an exception, only the message appears and the handler
doesn't work):

** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked'
not callable or a tuple
Is this the full message, or did you skip the preceding lines ?
(the file has some 20 lines, not 7551)
Is "finstall.py" the name of your file ? If yes, I'd suspect something
wrong with your sys.path or like...

May 14 '07 #12
Bruno Desthuilliers wrote:
>The error (not an exception, only the message appears and the handler
doesn't work):

** (finstall.py:7551): WARNING **: handler for 'on_button_next_clicked'
not callable or a tuple
Is this the full message, or did you skip the preceding lines ?
The full message.
>(the file has some 20 lines, not 7551)
Is "finstall.py" the name of your file ? If yes, I'd suspect something
wrong with your sys.path or like...
This is the name of my file - and it IS executed, only the error message
is weird.
--
(\__/)
(O.o)
(< )

This is Bunny.
Copy Bunny into your signature to help him on his way to world domination!
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.4 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGWKULldnAQVacBcgRArdiAKDhp9tGfknLb9xoSFLZeF Mrj3Cq4wCgk8ET
qq91Y8nFcjyC7545MaAtwM4=
=2lug
-----END PGP SIGNATURE-----

May 26 '07 #13

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

Similar topics

4
by: Ed Young | last post by:
Here is an example of the behavior: ------- code start ----------------------------------- #!/usr/bin/python #bugtest - test of class attribute initiation class Config: a = 1 b = 2 c = 3
1
by: anabell | last post by:
I have a code like this: sqlString = 'INSERT INTO ' + self.TableName + ' VALUES (' + self.TableFields + ')' self.cursor.execute(sqlString, self.__dict__) This works correctly. However, I'm...
1
by: Derek Fountain | last post by:
Am I correct in thinking that a Python object which comes from a bit of C code doesn't have a __dict__ attribute? I'm trying to poke around inside the objects which control the expat XML parser,...
5
by: Jean Brouwers | last post by:
Classes using __slots__ seem to be quite a bit smaller and faster to instantiate than regular Python classes using __dict__. Below are the results for the __slots__ and __dict__ version of a...
8
by: Steven Bethard | last post by:
I tried to Google for past discussion on this topic, but without much luck. If this has been discussed before, I'd be grateful for a pointer. Does anyone know why you can't assign a custom...
7
by: Chris | last post by:
hello, I have question about the re.I option for Regular Expressions: >>> import re >>> re.findall('x', '1x2X3', re.I) as expected finds both lower and uppercase x
8
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>>...
7
by: Georg Brandl | last post by:
Hi, can someone please tell me that this is correct and why: >>> class C(object): .... pass .... >>> c = C() >>> c.a = 1 >>> c.__dict__
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
0
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...
0
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,...
0
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...

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.