New submission from Karthikeyan Singaravelan <[email protected]>:
inspect.getsource uses inspect.findsource that uses a regex to check for class
declaration and starts matching against the regex from the start of the
program. When there is a match it checks for the first character to be 'c' to
return the line number from which getblock is used to get the class definition.
If there are multiple matches and there is no line with 'c' as the first
character in the line then they are sorted based on the number of whitespaces
preceding class keyword. This poses the following problem :
1. When a class definition like string occurs as part of a multiline string
before the actual definition then this causes the function to return the
multiline string instead of actual definition. This occurs both while using the
multiline string also as comment and also using them in variable definition in
other places.
2. When the class is defined inside another class and there is a similar
multiline string inside another class which is indented along the same
indentation level of the class then they are sorted by whitespace where they
are equal and then followed by line number. Since the class definition occurs
after the multiline string it causes the multiline string to be taken up as the
source of the class.
This was last changed in 89f507fe8c4 (Dec 2006) which is also a merge commit. I
searched for issues and relevant test cases but I couldn't find any in the test
suite or issue tracker regarding the same. Hence I am filing a new issue.
# backups/bpo35101.py
import inspect
class Bar:
a = """
class MultilineStringVariable:
...
"""
class MultilineStringVariable:
def foo(self):
pass
'''
class MultilineStringComment:
pass
'''
class MultilineStringComment:
def foo(self):
pass
class NestedClass:
a = '''
class Spam:
...
'''
class Nested:
class Spam:
pass
print(inspect.getsource(MultilineStringVariable))
print(inspect.getsource(MultilineStringComment))
print(inspect.getsource(Nested.Spam))
# Incorrect results
$ ./python.exe ../backups/bpo35101.py
class MultilineStringVariable:
...
class MultilineStringComment:
pass
class Spam:
...
----------
components: Library (Lib)
messages: 328909
nosy: xtreak
priority: normal
severity: normal
status: open
title: inspect.getsource returns incorrect source for classes when class
definition is part of multiline strings
type: behavior
versions: Python 3.6, Python 3.7, Python 3.8
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue35113>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com