[Python-ideas] Inline Functions - idea
Chris Angelico
rosuav at gmail.com
Wed Feb 5 15:45:10 CET 2014
On Thu, Feb 6, 2014 at 1:32 AM, Alex Rodrigues <lemiant at hotmail.com> wrote:
> An inline function would run in it's parent's namespace instead of creating
> a new one.
Does it have to be able to be called from different parents and use
their different namespaces, or is it local to one specific parent
function? Your example is the latter, and Python already supports
this: closures.
def main():
file = open('file.txt')
counter = 0
def saveLine():
nonlocal counter
slipL = abs(frontL - backL)
slipR = abs(frontR - backR)
file.write('Speeds: ('+frontL+', '+frontR+', '+backL+',
'+backR+'), \n Slip: '+slipL+', '+slipR)
counter = 0
while True:
counter += 1
frontL, frontR, backL, backR = getWheelSpeeds()
if counter > 100: # Log every 10 seconds no matter what
saveLine()
elif abs(frontR-backR) > 1 or abs(frontL-backL) > 1: # Also
log if the wheels are slipping
saveLine()
elif average([frontL, frontR, backL, backR]) > 60: # Also log
if we're going really fast
saveLine()
time.sleep(.1)
It'll happily read anything in the parent's namespace (whether they're
globals or locals in the parent), which includes calling methods (like
your file.write() there); to change anything, you just have to declare
it as 'nonlocal', as you see with counter. (The way I've written it,
slipL and slipR are local to saveLine(). You could alternatively
declare them to be nonlocal too, but there doesn't seem to be any need
to, here.)
Though in this case, you have three 'if' branches that do exactly the
same thing. It might be easier to do your conditions differently, such
that there really is just one inline block of code. But in a more
complex scenario, you could perhaps parameterize the inner function,
or call it in several different contexts, etcetera, etcetera,
etcetera. It's a function, like any other, and it cheerfully
references the parent's namespace.
Note though that it's the parent by the function's definition, not by
where it's called. That's why I dropped the question at the top. In
your example it makes no difference, of course.
ChrisA
More information about the Python-ideas
mailing list