473,756 Members | 6,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about introspection using inspect module

I'm trying to learn about introspection in Python. my ultimate goal
is to be able to build a module "text database" of all modules that
are in the sys.path, by discovering all candidate modules (I've
already done that), importing all of them, and then introspecting on
each module to discover its functions, globals and classes. But for
now I am having a problem with the latter.

I would like to import a module and figure out the names of its
defined functions, globals, and classes. Here's my attempt, file
foo.py, which has a single function, class, and global defined:

#!/usr/bin/env python

def somefunction(i) :
i = i + 1

class someclass:
def __init__(self):
self.x = 0
self.y = 1

someglobal = 1.2

if __name__ == "__main__": # when run as a script
import foo
import inspect
from inspect import *
isfuncs = filter(lambda x: re.match("^is", x) and x, dir(inspect))
print isfuncs
print filter(lambda x: re.match("some" , x[0]) and x[0], getmembers(foo) )
for f in isfuncs:
exec('print "trying %20s: ",; print getmembers(foo, %s)' % (f, f))

the output of running it as a script is the following:

['isbuiltin', 'isclass', 'iscode', 'isdatadescript or', 'isframe', 'isfunction', 'ismethod', 'ismethoddescri ptor', 'ismodule', 'isroutine', 'istraceback']
[('someclass', <class foo.someclass at 0x40058ddc>), ('somefunction' , <function somefunction at 0x40066a74>), ('someglobal', 1.2)]
trying isbuiltin: []
trying isclass: [('someclass', <class foo.someclass at 0x40058ddc>)]
trying iscode: []
trying isdatadescripto r: []
trying isframe: []
trying isfunction: [('somefunction' , <function somefunction at 0x40066a74>)]
trying ismethod: []
trying ismethoddescrip tor: []
trying ismodule: []
trying isroutine: [('somefunction' , <function somefunction at 0x40066a74>)]
trying istraceback: []

I was trying to use inspect.getmemb ers(foo, <PRED>) with an
appropriate predicate ("is" function). it looks like I am able to
discover that 'someclass' is a class, and that 'somefunction' is a
function (and also a routine, apparently). However, I cannot seem to
discover that 'someglobal' is a global. How to do so? Thanks,
--
Benjamin Rutt
Jul 21 '05 #1
4 2655
Benjamin Rutt wrote:
I'm trying to learn about introspection in Python. my ultimate goal
is to be able to build a module "text database" of all modules that
are in the sys.path, by discovering all candidate modules (I've
already done that), importing all of them, and then introspecting on
each module to discover its functions, globals and classes. But for
now I am having a problem with the latter.


I certainly don't want to discourage you from learning about python
introspection, it's one of the most fun aspects of the language. But just as
an FYI, the pydoc system already does much of what you have in mind, at least
if I'm reading your description correctly:

planck[/tmp]> pydoc -p 12345
pydoc server ready at http://localhost:12345/
Just point your favorite webbrowser to that URL (use any port number you want,
and which isn't already in use).

Cheers,

f

Jul 21 '05 #2
Fernando Perez <fp********@gma il.com> writes:
I certainly don't want to discourage you from learning about python
introspection, it's one of the most fun aspects of the language. But just as
an FYI, the pydoc system already does much of what you have in mind, at least
if I'm reading your description correctly:

planck[/tmp]> pydoc -p 12345
pydoc server ready at http://localhost:12345/


thanks, I'm aware of that actually, and seeing all the information
available there was inspiring to me.

what I am actually trying to do is to build a database of Python
modules. so then later, I can write a tool in my favorite editor
(Emacs) to invoke some forms of completion against this database
(e.g. os.remov<TAB> or socket.<TAB> to see a list of all socket module
definitions).

I was browsing pydoc.py but at first glance was having trouble
separating what in the code what is for the GUI, what is for the Web
server, and what does the introspection. I have actually borrowed the
ModuleScanner class already, to build the list of modules. It is just
inspecting those modules further where I'm having trouble.

thanks,
--
Benjamin Rutt
Jul 21 '05 #3
Benjamin Rutt wrote:
Fernando Perez <fp********@gma il.com> writes:
I certainly don't want to discourage you from learning about python
introspection, it's one of the most fun aspects of the language. But just
as an FYI, the pydoc system already does much of what you have in mind, at
least if I'm reading your description correctly:

planck[/tmp]> pydoc -p 12345
pydoc server ready at http://localhost:12345/
thanks, I'm aware of that actually, and seeing all the information
available there was inspiring to me.


OK, you never know :)
what I am actually trying to do is to build a database of Python
modules. so then later, I can write a tool in my favorite editor
(Emacs) to invoke some forms of completion against this database
(e.g. os.remov<TAB> or socket.<TAB> to see a list of all socket module
definitions).


well, I have no idea if this will be of any use, but it might:

http://cedet.sourceforge.net/

I use their speedbar quite a bit, but it sounds from the description like they
have some other fancier tools. I'd be quite curious to know if they play
nicely with python (they mention C++ explicitly), and how much value they add.
Let me know if you are familiar with them, or if you end up investigating
these further.

Cheers,

f

Jul 21 '05 #4
Benjamin Rutt <ru**@bmi.osu.e du> writes:
what I am actually trying to do is to build a database of Python
modules. so then later, I can write a tool in my favorite editor
(Emacs) to invoke some forms of completion against this database
(e.g. os.remov<TAB> or socket.<TAB> to see a list of all socket module
definitions).


The problem with that is that Python is dynamic, so the list of
completions may change over time. Not very likely, I know, but still...

Have you considered writing this tool in Python, with Pymacs <URL:
http://pymacs.progiciels-bpi.ca/ >? That way, you could get the list
at runtime with a dir(module).

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 21 '05 #5

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

Similar topics

11
3958
by: It's me | last post by:
I discovered the hardway what inspect.isclass() is doing. Consider this no brainer code: ### import inspect class Abc: def Hello(self): return
8
1235
by: mirandacascade | last post by:
Where in the language would one find the intropsection capability to answer the question: what class am I in? Example: class ExistentialCrisis: def __init__(self, text): self.spam = text print 'In the constructor of the %s class' % <whatever>
1
1800
by: Andy Leszczynski | last post by:
Hi, I have a following problem. Let's say there is a module which could be imported or run as __main__. It is going to contain hundreds of classes, something like that: import moduleA from moduleB import * class A: pass
4
1396
by: brad tilley | last post by:
How do I import a module and then ask it to show me its methods or other aspects about itself during execution? I'd like to do something such as this: import win32api print win32api.methods() I'd like to write some test scripts that load modules and probe them for information about themselves.
3
1213
by: Tool69 | last post by:
Hi, I would like to retrieve all the classes, methods and functions of a module. I've used the inspect module for this, but inside a given class (subclass of some other one), I wanted to retrieve only the methods I've written, not the inherited one. How can I do ? Thanks.
12
1321
by: Martin Drautzburg | last post by:
I would like to validate sql strings, which are spread all over the code, i.e. I run ("prepare") them against a database to see if it happy with the statements. Spelling errors in sql have been a major pain for me. The statements will not be assembled from smaller pieces, but they will not neccessarily be defined at module level. I could live with class level, but method level would be best. And I definitely don't want to parse the...
12
2119
by: thomas.guest | last post by:
I'm not making progress with the following and would appreciate any help. Here's an interpreted Python session. .... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'f' is not defined
7
1064
by: yagyala | last post by:
Hi. I would like to be able to tell, at run time, how many parameters a function requires. Ideally I would like to be able to tell which are optional as well. I've tried looking at the functions attributes, but haven't found one that helps in this. How can I do this? Thanks
4
1001
by: Alex K | last post by:
Hi Guys, What would be the simplest way of enumerating all methods and members (including inherited) of a given object? Thank you. Alex
0
9454
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
9271
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
10028
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
9836
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
8709
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...
1
7242
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
6533
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
5139
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
3804
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

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.