I've just started learning Python and wondered if anyone could tell me how to code this memoized function so that it doesn't used an external mem. In javascript this would be done with a closure, can something similar be done in python?
Unfortunately variables passed as arguments to functions are non-mutable in python. If you change an argument inside a function it becomes a new variable; the original, passed, variable is not changed outside of the function scope.
Possibly the more 'pythonic' way to do it would be as a class and have fib() as a method working on class data.
PHP is a mish-mash of languages and the 'static' keyword is a holdover from C where static local variables are actually stored in the .data or .bss sections just like a global variable (i.e. not on the stack like a true local variable). In python all variables are objects but their scope is either local or global.
>>24337 This is slightly misleading as it's only immutable types of arguments which trigger that behaviour. The rest are essentially passed by reference and can be modified within a function.
Strings and ints are "immutable" by this wonky definition, I'd definitely be interested in knowing what types aren't. Perhaps python 3 behaves differently.
>>24342 > Strings and ints are "immutable" by this wonky definition
Strings and ints are immutable in python, examples of mutable types are lists (but not tuples) and dicts. You can ignore that as an implementation detail most of the time, but this is one situation where it matters for example.
Yep, you're absolutely right. Mostly I've had ex-C programmers bug me about this while trying to update ints by reference and the idea of suggesting passing them as single-element lists never even crossed my mind. Thanks lad, I've learned something today and I'm only on my first cup of tea.
You need to think differently about objects in Python, because the language lacks prototypal inheritance. Objects are used very liberally in Javascript, because anything can inherit properties from anything else via the prototype chain; You can add methods as and when you need them, which isn't the case in Python, where you really need to define your classes up front.
The closest thing Python has to an object literal is the dictionary object, but it's much less flexible and shouldn't be thought of as equivalent. Trying to write Python as if it were just Javascript with different syntax is a disaster waiting to happen.
>>24348 Could you shed some light on why you want to do that? There's almost never a good reason to create an empty object like that in python (the only exception I've come across so far was when having to write something compatible with optparse and argparse) and as >>24350 points out, trying to force a fundamentally different language's constructs into python will only end in tears.