How to determine if a line of python code is a continuation of the line above it
Hans Georg Krauthaeuser
hgk at et.uni-magdeburg.de
Sun Apr 9 06:09:48 EDT 2006
Sandra-24 wrote:
> I'm not sure how complex this is, I've been brainstorming a little, and
> I've come up with:
>
> If the previous line ended with a comma or a \ (before an optional
> comment)
>
> That's easy to cover with a regex
>
> But that doesn't cover everything, because this is legal:
>
> l = [
> 1,
> 2,
> 3
> ]
>
> and with dictionaries and tuples as well.
>
> Not sure how I would check for that programmatically yet.
>
> Is there any others I'm missing?
>
> Thanks,
> -Sandra
>
Sandra,
in a similar situation I used 'inspect' and 'compile' like so:
import inspect
def func(*arg, **kwarg):
return get_cmd()
def get_cmd():
frame = inspect.currentframe()
outerframes = inspect.getouterframes(frame)
caller = outerframes[1][0]
ccframe = outerframes[2][0]
ccfname = outerframes[2][1]
ccmodule = inspect.getmodule(ccframe)
slines, start = inspect.getsourcelines(ccmodule)
clen = len(slines)
finfo = inspect.getframeinfo(ccframe, clen)
theindex = finfo[4]
lines = finfo[3]
theline = lines[theindex]
cmd = theline
for i in range(theindex-1, 0, -1):
line = lines[i]
try:
compile (cmd.lstrip(), '<string>', 'exec')
except SyntaxError:
cmd = line + cmd
else:
break
return cmd
if __name__ == '__main__':
a=0
b="test"
c=42
cmd=func(a)
print cmd
cmd=func(a,
b,
c)
print cmd
output:
cmd=func(a)
cmd=func(a,
b,
c)
Regards
Hans Georg
More information about the Python-list
mailing list