I
> came up with the following, but it fails:
>
> def make_counter(start_num):
> start = start_num
> def counter():
> start += 1
> return counter
>
> from_ten = make_counter(10)
> from_three = make_counter(3)

In Python, you have stricter scoping rules than Perl. You can't alter a local immutable object from outside your scope. You have "read-only" access to variables in the enclosing scope. You could declare start "global" to allow access. Or in Python 3.0, you could declare it "nonlocal" when accessing it, which will search from the nearest enclosing scope, and find it there (allowing it to be rebound without making it globally available).

But the simplest solution, prior to 3.0, which hasn't been mentioned yet, is to explicitly pass start the start variable as as a default parameter:

def make_counter(start_num):
start = start_num
def counter(start=start):
start += 1
return counter

That will do what you wanted. "Start=start" is simply using your read access to the prior start to initialize the new local start.

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

Reply via email to