473,498 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inspect.findsource problem with llinecache

Hi,

I think I have discovered two bugs with the inspect module and I would
like to know if anyone can spot any traps in my workaround.

I needed a function which takes a function or method and returns the
code inside it (it also adjusts the indent because I have to paste the
to a text string without indents, which is parsed later...long story).
At first this seemed trivial but then I started getting an error on
line 510 of inspect.py:
504 if iscode(object):
505 if not hasattr(object, 'co_firstlineno'):
506 raise IOError('could not find function definition')
507 lnum = object.co_firstlineno - 1
508 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^
(\s*@)')
509 while lnum 0:
510 if pat.match(lines[lnum]): break
511 lnum = lnum - 1
512 return lines, lnum

I finally figured out that there was a caching problem. The function I
passed was changed, but the code lines (strings) retrieved by
linecache.getlines() (on lines 464 and 466) didn't update with the new
module contents. The resulting error I was getting occurred when real
module had less lines than the cached module (or the other way around,
whatever.)

To get around this, I invoke linecache.clearcache(). Here is the
function (minus doc strings)...

INDENT_SPACES = 4

def get_fn_contents(fn, remove_indents=1):
# Clear the cache so inspect.getsourcelines doesn't try to
# check an older version of the function's module.
linecache.clearcache()
source_lines, n = inspect.getsourcelines(fn)

# Skip the first line which contains the function definition.
# Only want the code inside the function is needed.
fn_contents = source_lines[1:]

# Remove indents
new_indent_lines = [remove_indent(line, remove_indents) for line
in fn_contents]

return "".join(new_indent_lines)
def remove_indent(in_str, num_indent=1):
s = in_str
for i in range(num_indent):
if s[:INDENT_SPACES] == " ": # Whitespace indents
s = s[INDENT_SPACES:]
elif s[:1] == "\t": # Tab characters indents
s = s[1:]

return s

[END CODE]

The second issue is that the last line in the passed function's module
seems to be ignored. So, if the last line of the module is also the
last line of the function, the function is returned one line too
short.

I welcome comments on the bugs or optimization pointers for my code. I
am still quite new to Python. My primary question though is: will
linecache.clearcache() cause me any problems?

Thanks,

- Rafe
Nov 12 '08 #1
3 1718
On Nov 12, 2:22*pm, Rafe <rafesa...@gmail.comwrote:
Hi,

I think I have discovered two bugs with the inspect module and I would
like to know if anyone can spot any traps in my workaround.

I needed a function which takes a function or method and returns the
code inside it (it also adjusts the indent because I have to paste the
to a text string without indents, which is parsed later...long story).
At first this seemed trivial but then I started getting an error on
line 510 of inspect.py:
504 * *if iscode(object):
505 * * * *if not hasattr(object, 'co_firstlineno'):
506 * * * * * *raise IOError('could not find function definition')
507 * * * *lnum = object.co_firstlineno - 1
508 * * * *pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^
(\s*@)')
509 * * * *while lnum 0:
510 * * * * * *if pat.match(lines[lnum]): break
511 * * * * * *lnum = lnum - 1
512 * * * *return lines, lnum

I finally figured out that there was a caching problem. The function I
passed was changed, but the code lines (strings) retrieved by
linecache.getlines() (on lines 464 and 466) didn't update with the new
module contents. The resulting error I was getting occurred when real
module had less lines than the cached module (or the other way around,
whatever.)

To get around this, I invoke linecache.clearcache(). Here is the
function (minus doc strings)...

INDENT_SPACES = 4

def get_fn_contents(fn, remove_indents=1):
* * # Clear the cache so inspect.getsourcelines doesn't try to
* * # check an older version of the function's module.
* * linecache.clearcache()
* * source_lines, n = inspect.getsourcelines(fn)

* * # Skip the first line which contains the function definition.
* * # Only want the code inside the function is needed.
* * fn_contents = source_lines[1:]

* * # Remove indents
* * new_indent_lines = [remove_indent(line, remove_indents) for line
in fn_contents]

* * return "".join(new_indent_lines)

def remove_indent(in_str, num_indent=1):
* * s = in_str
* * for i in range(num_indent):
* * * * if s[:INDENT_SPACES] == " * *": * # Whitespace indents
* * * * * * s = s[INDENT_SPACES:]
* * * * elif s[:1] == "\t": * # Tab characters indents
* * * * * * *s = s[1:]

* * return s

[END CODE]

The second issue is that the last line in the passed function's module
seems to be ignored. So, if the last line of the module is also the
last line of the function, the function is returned one line too
short.

I welcome comments on the bugs or optimization pointers for my code. I
am still quite new to Python. My primary question though is: will
linecache.clearcache() cause me any problems?

Thanks,

- Rafe

I forgot to add that while inspect uses the cached module to get the
text, the line number used to find the block of source lines is
retrieved from the passed object. So, if I pass a function which
reports that it starts on line 50, but in the cache it starts on line
40 an error isn't raised but the lines of code returned are wrong. The
error only occurs when the line number is higher than the number of
lines in the cached module.

- Rafe
Nov 12 '08 #2
En Wed, 12 Nov 2008 05:22:55 -0200, Rafe <ra*******@gmail.comescribió:
I think I have discovered two bugs with the inspect module and I would
like to know if anyone can spot any traps in my workaround.
They look like real bugs - please report them at http://bugs.python.org
else this will be forgotten.
I welcome comments on the bugs or optimization pointers for my code. I
am still quite new to Python. My primary question though is: will
linecache.clearcache() cause me any problems?
I don't think so, apart from performance degradation (but good performance
with bad results isn't good at all!)

--
Gabriel Genellina

Nov 15 '08 #3
On Nov 15, 1:29*pm, "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Wed, 12 Nov 2008 05:22:55 -0200,Rafe<rafesa...@gmail.comescribió:
I think I have discovered two bugs with the inspect module and I would
like to know if anyone can spot any traps in my workaround.

They look like real bugs - please report them athttp://bugs.python.org*
else this will be forgotten.
I welcome comments on the bugs or optimization pointers for my code. I
am still quite new to Python. My primary question though is: will
linecache.clearcache() cause me any problems?

I don't think so, apart from performance degradation (but good performance *
with bad results isn't good at all!)

--
Gabriel Genellina
Thank you for replying Gabriel. I'll report it now.

- Rafe
Nov 17 '08 #4

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

Similar topics

4
1818
by: Hans Georg Krauthaeuser | last post by:
Dear all, I have a problem to get the command that has called a function if the command was given on multiple lines. E.g.: ################################################### import inspect ...
2
1606
by: Fernando Perez | last post by:
Hi all, IPython has suffered quite a few problems with the inspect module in python 2.3. For these, unfortunately all I've been able to do is guard with overreaching except clauses, as I had...
11
3929
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
1
2173
by: Darran Edmundson | last post by:
I was playing around with the inspect module the other day trying to write a quick and dirty "smart" logger. By this I mean that writing a message to the global log would also yield some info...
0
1015
by: Ron Adam | last post by:
While playing around with the inspect module I found that the Blockfinder doesn't recognize single line function definitions. Adding the following two lines to it fixes it, but I'm not sure if it...
1
4840
by: aj | last post by:
What is the difference (if any) between inspect check database and db2dart ??? Do they both find the same potential problems? Does one provide more comprehensive checking than the other? ...
0
984
by: castironpi | last post by:
-----the code: class A: b=2 import inspect print inspect.getsource(A) class A: c=2 print inspect.getsource(A)
8
1325
by: Aaron \Castironpi\ Brady | last post by:
Hello, The 'inspect' module has this method: inspect.getargvalues(frame) It takes a frame and returns the parameters used to call it, including the locals as defined in the frame, as shown....
0
2182
by: rajasankar | last post by:
Hi, I am using Jython based application and trying to use inspect.py in the python files. Here is my code import inspect,os,sys,pprint,imp def handle_stackframe_without_leak(getframe): ...
0
7126
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
7005
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
7210
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...
0
7381
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
5465
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
4595
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...
0
3096
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...
1
659
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
293
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.