I don't KISS, but I like to keep it DRY.

If you didn't get past the disgusting interpretation of that title, then you probably shouldn't be reading this blog ;)
I make elephants out flies and flies out of elephants, after-all, the human genetic code is 40% bananas!

Monday, June 7, 2010

Latter optional arguments evaluating to values of former arguments

Code series: This series has to do with the day-to-day ideas that come up as I code. It is often the case that these ideas are already implemented in a language other then the one used, and sometimes it is even the case that the idea comes from my lack of knowledge or oversight of some feature in a programming language. If you notice such subtleties, please comment, I'm more happy to learn from my mistakes than to keep following false, or already implemented ideas.

I've come across this issue several times, but this is probably the first time I've had the time to formalize it. Sometimes in a function definition you make use optional arguments with default values. In essence I find this to be a shorthand to overloading the function with another signature, and calling that base function from there, however, that is apparently not the case in any known to me implementation of a programming language that actually supports optional arguments in function signatures.

You almost always are able to evaluate some expression as the default value, and while code-blocks would certainly make things look even more complex, I think they should be allowed if one wishes to use them, but that is rarely needed, it just so happens that default values are more often than rather simple to compute. It is therefore sometimes pleasant that one can do the following in e.g. Python:

def nice(a, b = 1 + 2):

My problem lies with the scope, consider this Python code:

def nice (a, b = a)

Unfortunately this is not allowed, yielding the error:

NameError: name 'a' is not defined

From which I deduce that the scope is local to each variable, I wander why this is? As I've most certainly seen uses of the latter case but never the former? 

Would've sure be nice for those variables to be evaluated within the same scope.

No comments:

Post a Comment