<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Dave Dash</title>
 <link href="http://davedash.com/tag/functions/atom.xml" rel="self"/>
 <link href="http://davedash.com/tag/functions"/>
 <updated>2012-04-07T22:42:44-07:00</updated>
 <id>http://davedash.com/</id>
 <author>
   <name>Dave Dash</name>
   <email>dd+atom1@davedash.com</email>
 </author>

 
 <entry>
   <title>Python, Named arguments: Pure Genius</title>
   <link href="http://davedash.com/2007/12/21/python-named-arguments-pure-genius/"/>
   <updated>2007-12-21T00:00:00-08:00</updated>
   <id>http://davedash.com/2007/12/21/python-named-arguments-pure-genius</id>
   <content type="html">&lt;p&gt;I decided I want to learn python, if only to learn Django and to &quot;get&quot; what all the python hub-bub is about.&lt;/p&gt;

&lt;p&gt;Python's named arguments in function calls is pure genius.  Let me explain.&lt;/p&gt;

&lt;p&gt;In PHP, and many other languages you can define a function as such:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo($a = 2, $b = 2)
{
    return pow($a,$b);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you follow, &lt;code&gt;foo()&lt;/code&gt; will give you &lt;code&gt;4&lt;/code&gt;.  &lt;code&gt;foo(3)&lt;/code&gt; is &lt;code&gt;9&lt;/code&gt; and &lt;code&gt;foo(99,0)&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt;.  In python we can do the same thing, but it'll pay to use some better variable names:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def foo(base=2, exponent=2):
    return base**exponent
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Similarly &lt;code&gt;foo()&lt;/code&gt; will give you &lt;code&gt;4&lt;/code&gt;.  &lt;code&gt;foo(3)&lt;/code&gt; is &lt;code&gt;9&lt;/code&gt; and &lt;code&gt;foo(99,0)&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt;.  But what if we forgot what the order was?  Did base come first or was it exponent?  We can do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo(exponent=99, base=2)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since &lt;code&gt;base&lt;/code&gt; and &lt;code&gt;exponent&lt;/code&gt; both have default values, we can even omit &lt;code&gt;base&lt;/code&gt; and let it use the default:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo(exponent=10)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This means rather than passing an &lt;code&gt;$options&lt;/code&gt; array to my functions and checking whether an option was set or not, I can just specify which options I want in my function call.  Or instead of remembering the order of the arguments, I can use whatever order suits me.  Or instead of calling a function like &lt;code&gt;bar(null, null, null, 2)&lt;/code&gt; I can just skip those first three arguments all together.&lt;/p&gt;

&lt;p&gt;A side effect of this, is now there's a real use, even for simple functions, to give your variables easy to remember names.&lt;/p&gt;
</content>
 </entry>
 

</feed>

