473,503 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding the public callables of self

Is there any better way to get a list of the public callables of self
other than this?

myCallables = []
classDir = dir(self)
for s in classDir:
attr = self.__getattribute__(s)
if callable(attr) and (not s.startswith("_")):
myCallables.append(s) #collect the names (not funcs)

I don't mean a shorter list comprehension or something that just drops
the line count, but whether or not I need to go at it through dir and
__getattribute__. This seems a bit convoluted and with python it often
seems there's something already canned to do stuff like this when I do
it. At first I thought self.__dict__ would do it, but callable methods
seem to be excluded so I had to resort to dir, and deal with the
strings it gives me.

Thanks,
Russ

Feb 9 '06 #1
6 1341
import inspect
myCallables = [name for name, value in inspect.getmembers(self) if not
name.startswith('_') and callable(value)]
Instance methods aren't in self.__dict__ because they're a part of the
class. To made a comprehensive list of all the attributes available to
an instance, you have to traverse the attribute dictionaries of the
instance, its class, and all of the base classes in the right order.
(inspect.getmro returns the base classes in method resolution order)

Feb 9 '06 #2
Russell Warren wrote:
Is there any better way to get a list of the public callables of self
other than this?

myCallables = []
classDir = dir(self)
for s in classDir:
attr = self.__getattribute__(s)
if callable(attr) and (not s.startswith("_")):
myCallables.append(s) #collect the names (not funcs)
I don't mean a shorter list comprehension or something that just drops
the line count, but whether or not I need to go at it through dir and
__getattribute__. This seems a bit convoluted and with python it often
seems there's something already canned to do stuff like this when I do
it.
Use getattr(self, s) instead of self.__getattribute__(s).

You could streamline it a bit with a list comprehension:
myCallables = [ s for s in dir(self) if not s.startswith('_') and
callable(getattr(self, s)) ]

At first I thought self.__dict__ would do it, but callable methods seem to be excluded so I had to resort to dir, and deal with the
strings it gives me.


The callables are attributes of the class and its base classes, not of
self. self.__dict__ just contains instance attributes.

Kent
Feb 9 '06 #3
Russell Warren <ru************@gmail.com> wrote:
Is there any better way to get a list of the public callables of self
other than this?

myCallables = []
classDir = dir(self)
for s in classDir:
attr = self.__getattribute__(s)
if callable(attr) and (not s.startswith("_")):
myCallables.append(s) #collect the names (not funcs)

I don't mean a shorter list comprehension or something that just drops
the line count, but whether or not I need to go at it through dir and
__getattribute__. This seems a bit convoluted and with python it often
seems there's something already canned to do stuff like this when I do
it. At first I thought self.__dict__ would do it, but callable methods
seem to be excluded so I had to resort to dir, and deal with the
strings it gives me.


This last sentence suggests to me something like:

attrs = set(s for s in dir(self) if not s.startswith('_'))
myCallables = attrs.difference(a.__dict__)
return list(myCallables)

(which you can get down to one line if you want).

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Feb 9 '06 #4
Sion Arrowsmith wrote:
Russell Warren <ru************@gmail.com> wrote: (snip) At first I thought self.__dict__ would do it, but callable methods
seem to be excluded so I had to resort to dir, and deal with the
strings it gives me.
This last sentence suggests to me something like:

attrs = set(s for s in dir(self) if not s.startswith('_'))
myCallables = attrs.difference(a.__dict__)

err... s/a.__dict__/self.__dict__/
return list(myCallables)

Won't work as expected:
class Tricky(object): .... class_attrib = 42
.... def __init__(self, attr):
.... self.attr = attr
.... def doit(self):
.... if callable(self.attr):
.... return self.attr(self)
.... t = Tricky(lambda obj: obj.__class__.__name__)
t <__main__.Tricky object at 0x2aaaaab28ed0> def getcallables(obj): .... attrs = set(s for s in dir(obj) if not s.startswith('_'))
.... callables = attrs.difference(obj.__dict__)
.... return list(callables)
.... getcallables(t) ['doit', 'class_attrib'] t.attr(t) 'Tricky' t.class_attrib()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'int' object is not callable
There are 2 reliable ways to know if an object is callable:
- using callable()
- trying to call it
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 9 '06 #5
> import inspect
myCallables = [name for name, value in inspect.getmembers(self) if not
name.startswith('_') and callable(value)]


Thanks. I forgot about the inspect module. Interestingly, you've also
answered my question more than I suspect you know! Check out the code
for inspect.getmembers():

def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by
name.
Optionally, only return members that satisfy a given predicate."""
results = []
for key in dir(object):
value = getattr(object, key)
if not predicate or predicate(value):
results.append((key, value))
results.sort()
return results

Seems familiar! The fact that this is using dir(), getattr(), and
callable() seems to tell me there is no better way to do it. I guess
my method wasn't as indirect as I thought!

And thanks for the reminder about getattr() instead of
__getattribute__() and other streamlining tips.

Russ

Feb 9 '06 #6
Ha! I didn't realize that was getmembers' implementation. What a hack
;-)

In fact, your way is faster, since getmembers is taking the time to
sort its results (presumably so that repeated calls to the same object
will yield the same list; I don't think dir has a guaranteed ordering)

Feb 9 '06 #7

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

Similar topics

17
23140
by: Sean Ross | last post by:
Hi. Recently I made a small script to do some file transferring (among other things). I wanted to monitor the progress of the file transfer, so I needed to know the size of the files I was...
2
1484
by: lcaamano | last post by:
We have a tracing decorator that automatically logs enter/exits to/from functions and methods and it also figures out by itself the function call arguments values and the class or module the...
0
904
by: Lloyd Weehuizen | last post by:
Hey I'm trying to set up a WeakrefValueDictionary of callables however as soon as my method that adds the callable to the dictionary exits the value is removed? Is there any way around this? ...
5
2057
by: pythoncurious | last post by:
Hi python experts In C++ I can do something like this: class Base { public: void f() { this->f_(); } private: virtual void f_() = 0; };
1
1486
by: t.mitchell | last post by:
Hi, I have a python gtk app that allows users to have one project open at a time. I have recently discovered that projects are not being freed when they are closed - the refcount is not hitting...
0
2142
by: U S Contractors Offering Service A Non-profit | last post by:
This Sunday the 26th 2006 there will be Music @ Tue Nov Inbox Reply Craig Somerford to me show details 9:54 pm (26 minutes ago) #1St "CLICK" HeAt frOm A blanket...
1
1094
by: seanacais | last post by:
I want to create a class derived from a Borg class that can instantiated as part of a script or be contained in other classes. When methods from the Borg class are called, I would like to know the...
275
12035
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
1
14187
by: Glenton | last post by:
Hi All Here is a very simple little class for finding a shortest route on a network, following Dijkstra's Algorithm: #!/usr/bin/env python #This is meant to solve a maze with Dijkstra's...
0
7204
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,...
0
7091
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...
1
6998
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...
0
7464
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...
0
5586
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,...
0
3162
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1516
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 ...
1
741
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
391
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...

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.