Re: Understanding closures

2007-08-18 Thread happyriding
On Aug 18, 11:03 pm, Ramashish Baranwal <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I want to use variables passed to a function in an inner defined
> function. Something like-
>
> def fun1(method=None):
> def fun2():
> if not method: method = 'GET'
> print '%s: this is fun2' % method
> return
> fun2()
>
> fun1()
>
> However I get this error-
> UnboundLocalError: local variable 'method' referenced before
> assignment
>
> This however works fine.
>
> def fun1(method=None):
> if not method: method = 'GET'
> def fun2():
> print '%s: this is fun2' % method
> return
> fun2()
>
> fun1()
>
> Is there a simple way I can pass on the variables passed to the outer
> function to the inner one without having to use or refer them in the
> outer function?
>
> Thanks,
> Ramashish

This works error free:


def fun1(x=None):
y = 10
def fun2():
print x
if not x: method = 'GET'
print '%s: this is fun2' % method
fun2()
fun1()


Python reads x from the fun1 scope. But the following produces an
error for the print x line:

def fun1(x=None):
y = 10
def fun2():
print x
if not x: x = 'GET'#CHANGED THIS LINE
print '%s: this is fun2' % method
fun2()
fun1()

Traceback (most recent call last):
  File "3pythontest.py", line 8, in ?
fun1()
  File "3pythontest.py", line 7, in fun1
fun2()
  File "3pythontest.py", line 4, in fun2
print x
UnboundLocalError: local variable 'x' referenced before assignment


It's as if python sees the assignment to x and suddenly decides that
the x it was reading from the fun1 scope is the wrong x.  Apparently,
the assignment to x serves to insert x in the local scope, which makes
the reference to x a few lines earlier an error.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sed to python: replace Q

2008-04-30 Thread happyriding
On Apr 29, 11:27 pm, Raymond <[EMAIL PROTECTED]> wrote:
> For some reason I'm unable to grok Python's string.replace() function.

line = "abc"
line = line.replace("a", "x")
print line

--output:--
xbc

line = "abc"
line = line.replace("[apq]", "x")
print line

--output:--
abc


Does the 5 character substring "[apq]" exist anywhere in the original
string?
--
http://mail.python.org/mailman/listinfo/python-list