473,756 Members | 5,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inspect.findsou rce 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_first lineno - 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.getli nes() (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.clear cache(). Here is the
function (minus doc strings)...

INDENT_SPACES = 4

def get_fn_contents (fn, remove_indents= 1):
# Clear the cache so inspect.getsour celines doesn't try to
# check an older version of the function's module.
linecache.clear cache()
source_lines, n = inspect.getsour celines(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_line s = [remove_indent(l ine, remove_indents) for line
in fn_contents]

return "".join(new_ind ent_lines)
def remove_indent(i n_str, num_indent=1):
s = in_str
for i in range(num_inden t):
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.clear cache() cause me any problems?

Thanks,

- Rafe
Nov 12 '08 #1
3 1731
On Nov 12, 2:22*pm, Rafe <rafesa...@gmai l.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_first lineno - 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.getli nes() (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.clear cache(). Here is the
function (minus doc strings)...

INDENT_SPACES = 4

def get_fn_contents (fn, remove_indents= 1):
* * # Clear the cache so inspect.getsour celines doesn't try to
* * # check an older version of the function's module.
* * linecache.clear cache()
* * source_lines, n = inspect.getsour celines(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_line s = [remove_indent(l ine, remove_indents) for line
in fn_contents]

* * return "".join(new_ind ent_lines)

def remove_indent(i n_str, num_indent=1):
* * s = in_str
* * for i in range(num_inden t):
* * * * 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.clear cache() 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*******@gmai l.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.clear cache() 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.a r>
wrote:
En Wed, 12 Nov 2008 05:22:55 -0200,Rafe<rafes a...@gmail.come scribió:
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.clear cache() 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
1842
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 def call(a,b,c,d,e): s = inspector()
2
1621
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 not been able to find small, reproducible examples to pass on to the devs. But today I got a crash report from a user and I've been able to replicate this crash with a tiny script which does not depend on ipython at all. I'd like to hear from...
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
1
2187
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 about the calling scope. If you look at my function "test" below, I'd ideally like log messages: foo.py:test, "message 1" foo.py:Foo.__init__, "message 2" foo.py:Foo.bar, "message 3"
0
1029
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 causes any problems anywhere else. elif self.indent == 0: raise EndOfBlock, self.last Cheers,
1
4874
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? TIA
0
1003
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
1335
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. .... import inspect
0
2193
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): frame = inspect.currentframe() try: function = inspect.getframeinfo(getframe)
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...
0
9868
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
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
9707
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
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...
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.