Nested Functions in Python :Explained

Nested Functions : This is a common feature present in functional languages like Python, Ruby, Javascript etc. Non-functional languages like C, C++, Java etc dont support it. In some cases the nested functions are also called closures if they meet a certain criteria (they do in python and javascript) but I wont go into detail here because that is mostly academic. You are feeling uncomfortable (and its natural) because any person coming from non-functional background, views functions and variables as separate entities and they are indeed separate in that case. If we talk in very primitive terms, like in assembly language, a function can be described as a set of instructions written somewhere in a program, which may including moving variables from one register to another or shifting their bytes, etc. And variables can be thought of as something actually stored in those registers/memory-locations. So in non-functional language terms, a function is a set of instructions which is a part of the program, and a variable is something which is created, manipulated and destroyed during the execution phase of program. To get comfortable with nested functions, first of all you will need to unlearn that concept. Functional languages blur the line between functions and variables. When a functional language program is being executed, the function itself is a kind of “value” which can be “stored” in a memory. x = 10 ‘x’ is a variable with value 10. y = “Hello World” ‘y’ is a variable with value “Hello World” def someFunction () : print (“Hello World”) ‘someFunction’ is VARIABLE with value : a function which prints hello world. Actually its even more clear if written in terms of javascript, which provides an alternate syntax to write functions : var someFunction = function () { console.log (“Hello World”); } As you can see, javascript EXPLICITLY allows assigning functions as values to variables just like you assign them any numeric or string value. Python doesnt support that syntax (it does, but not a topic of today) but basically does exactly same thing when running the program If you can grasp the above simple concept, then there is nothing more to add to it. You throw variables around, pass them to functions as arguments, return them as results, reassign/modify their values. You do the same with function values. So in functional languages, even the term “nested functions” is slightly outrageous. This term was invented because some non-functional languages allowed it as a “feature”. Functional languages DONT need that term, that term is misleading, it makes them look like some kind of special language feature, which is not the case. A functional programmer will see nested functions no different than declaring few variables and assigning values to them, nothing special or unusual about it AT ALL. This concept is pretty useful when you need to represent a behaviour/task as form of data. For example, consider this piece of code. Note that out of habit I use an empty comment “#” to mark the end of functions/if-blocks/for-loops etc in python, makes it easier to read. Its not a syntax, but I use it as a good practice. def getBehaviour (species) : if species == ‘cat’ : def behave () : print (“*chases mice*”) print (“says : meow”) # elif species == ‘dog’ : def behave () : print (“*chases cats*”) print (“*barks*”) # elif species == ‘human’ : def behave () : print (“*goes to work*”) print (“says : Hello”) # else : def behave () : print (“*unknown species*”) # # return behave # b1 = getBehaviour (“cat”) b1 () Now if you read above program with “non-functional” mindset, you may say “whoa ! nested functions !!”. If you read above program with “functional” mindset, you will see that there is a function getBehaviour, which returns a variable the value of which depends on an if-else on the argument species. The returned variable can then be called as function. Thats it. Compare it with this function : def getSpeciesCode (species) : if species == ‘cat’ : code = 1 elif species == ‘dog’ : code = 2 elif species == ‘human’ : code = 3 else : code = 0 # return code # c1 = getSpeciesCode (“cat”) print (c1) The structure of the above function is EXACTLY same, it returns a variable, whose value depends on the value of species argument, but this time, instead of a function, this value happens to be an integer. In non-functional languages, you can do the above work by making lots of classes. You will make a base class “Species”, and declare few functions, some of them virtual. Then you will create additional classes for every species, inheriting from it, like class Cat, class Dog, class Human, etc.. and define all those virtual functions. That class structure method is good but its very verbose and sometimes it doesnt give a natural representation of the physical world. If all you need is to use that species thing for few lines in a project, your “class files” will take up more lines of code than its actual usage.

Advertisements

Leave a comment

Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s