<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>No Open Blockers &#187; Python</title>
	<atom:link href="http://noopenblockers.com/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://noopenblockers.com</link>
	<description></description>
	<lastBuildDate>Thu, 01 Jul 2010 14:43:08 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Getting Started with Amazon EC2 using Python</title>
		<link>http://noopenblockers.com/2010/04/27/getting-started-with-amazon-ec2-using-python/</link>
		<comments>http://noopenblockers.com/2010/04/27/getting-started-with-amazon-ec2-using-python/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 12:28:26 +0000</pubDate>
		<dc:creator>Jay</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://noopenblockers.com/?p=922</guid>
		<description><![CDATA[With the announcement of RHEL&#8217;s offering on Amazon Web Services, I wanted to write up some notes from the work I&#8217;ve done with EC2 and python. Amazon provides a capable web console, but (not surprisingly) I&#8217;d rather do most of my work through a programmable API. The rest of this blog covers the steps necessary [...]]]></description>
			<content:encoded><![CDATA[<p>With the <a href="http://www.redhat.com/about/news/prarchive/2010/cloud.html" target="new">announcement of RHEL&#8217;s offering on Amazon Web Services</a>, I wanted to write up some notes from the work I&#8217;ve done with EC2 and python. Amazon provides a capable web console, but (not surprisingly) I&#8217;d rather do most of my work through a programmable API. The rest of this blog covers the steps necessary to launch an instance, along with some other random notes from my experience.</p>
<h2>Boto</h2>
<p>The first step is to grab the <a href="http://code.google.com/p/boto/" target="new">boto</a> library. Boto is a python interface to Amazon&#8217;s web services (not just EC2 but S3 as well). Their site provides downloads, installation instructions, and source, so I won&#8217;t go into any more detail besides saying I use it.</p>
<h2>Gather Amazon Information</h2>
<p>There are a few things needed from your Amazon AWS account in order create and connect to instances, all of which can be retrieved from the AWS web console.</p>
<h3>Account Access Keys</h3>
<p>The account access keys are effectively your username/password when connecting through boto. From the AWS console, click the Account tab at the top and navigate to Security Credentials. In the middle of the page you&#8217;ll find &#8220;Access Key ID&#8221; and &#8220;Secret Access Key&#8221;. Make note of these but be sure to keep them safe; these pretty much give full access to your environment.</p>
<h3>Key Pairs</h3>
<p>The key pairs are used for SSH authentication when connecting to your instances. These are generated through the AWS console itself (the Account tab from the previous section will simply link you back to the AWS console). It&#8217;s pretty self-explanatory how to generate a key pair, just be sure to download and then keep the private key safe; there is no way to retrieve a private key from Amazon other than that initial download link.</p>
<h3>Image ID</h3>
<p>To create an instance, you have to specify which Amazon Machine Image (AMI) to base the instance on. These can be found under the AMIs section of the web console. Determine which image you want based on what it provides and make a note of the ID. It will look something like &#8220;ami-12345678&#8243;.</p>
<p>Existing Red Hat customers can find more information <a href="http://www.redhat.com/solutions/cloud/access/" target="new">on Red Hat&#8217;s Cloud Access</a> page.</p>
<h2>Connect to Amazon</h2>
<p>There are two ways of passing your AWS Key and Secret Key to boto, either through environment variables or as arguments to the connect calls. If you choose the environment variable route, they must be named:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">AWS_ACCESS_KEY_ID</span>=foo
<span style="color: #007800;">AWS_SECRET_ACCESS_KEY</span>=bar</pre></div></div>

<p>Once those are set, create a connection to EC2 in python with the following snippet:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> boto
ec2conn = boto.<span style="color: black;">connect_ec2</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>If you choose to skip the environment variables, the keys can be passed directly to the connect call:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> boto
ec2conn = boto.<span style="color: black;">connect_ec2</span><span style="color: black;">&#40;</span>aws_access_key_id=<span style="color: #483d8b;">'foo'</span>, aws_secret_access_key=<span style="color: #483d8b;">'bar'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>In either case, it is important to realize that these calls <strong>default to the US east EC2 region.</strong> If you want to make this explicit or, more likely, connect to one of the other two regions, you can pass the optional region argument:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">region = <span style="color: #808080; font-style: italic;"># one of 'us-east', 'us-west', 'eu-west'</span>
ec2conn = boto.<span style="color: black;">connect_ec2</span><span style="color: black;">&#40;</span>region=region<span style="color: black;">&#41;</span></pre></div></div>

<p>That&#8217;s the main connection to EC2 and the one we&#8217;ll use for creating instances. There are others with different purposes, such as connecting to S3, the AWS load balancer features, and so on. They are all named &#8220;connect_&#8221;, so looking through the help for boto will give you a good idea of what&#8217;s available.</p>
<h2>Create a new Security Group</h2>
<p>A security group is basically Amazon&#8217;s firewall to your instances. The default security group is pretty restrictive, so we&#8217;ll create a new one that allows us access to SSH and HTTP:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">name = <span style="color: #483d8b;">'SSH and HTTP Security Group'</span>
description = <span style="color: #483d8b;">'Test security group'</span>
&nbsp;
ec2conn.<span style="color: black;">create_security_group</span><span style="color: black;">&#40;</span>name, description<span style="color: black;">&#41;</span>
group = ec2conn.<span style="color: black;">get_all_security_groups</span><span style="color: black;">&#40;</span>groupnames=<span style="color: black;">&#91;</span>name<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
&nbsp;
group.<span style="color: black;">authorize</span><span style="color: black;">&#40;</span>ip_protocol=<span style="color: #483d8b;">'tcp'</span>, from_port=<span style="color: #483d8b;">'22'</span>, to_port=<span style="color: #483d8b;">'22'</span>, cidr_ip=<span style="color: #483d8b;">'0.0.0.0/0'</span><span style="color: black;">&#41;</span>
group.<span style="color: black;">authorize</span><span style="color: black;">&#40;</span>ip_protocol=<span style="color: #483d8b;">'tcp'</span>, from_port=<span style="color: #483d8b;">'80'</span>, to_port=<span style="color: #483d8b;">'80'</span>, cidr_ip=<span style="color: #483d8b;">'0.0.0.0/0'</span><span style="color: black;">&#41;</span></pre></div></div>

<p><em>Note: The <code>create_security_group</code> call returns a handle to the group, but I wanted to demonstrate retrieving an existing group as well.</em></p>
<p>The above should be pretty self-explanatory. The biggest thing to note is the line where the group is retrieved. Since a list is passed to <code>groupnames</code> we get back a list of matching groups. I can&#8217;t tell you how many times I attempted to act on the returned result without indexing a specific group inside of it. This is a common pattern all over boto, so you&#8217;d think I&#8217;d have learned after the first 30 times.</p>
<p>After this is complete, the web console will show a new security group with the firewall holes we created. This will come in handy when we want to SSH into our instance to, ya know, actually <em>do stuff.</em></p>
<h2>Create the Instance</h2>
<p>We&#8217;re now ready to actually create an instance.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">ami_id = <span style="color: #483d8b;">'ami-12345678'</span>
ami = ec2conn.<span style="color: black;">get_all_images</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>ami_id<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
&nbsp;
ssh_key_name = <span style="color: #808080; font-style: italic;"># name of the key pair created above</span>
security_groups = <span style="color: #808080; font-style: italic;"># name of the security group created above; must be a list</span>
instance_size = <span style="color: #808080; font-style: italic;"># 'm1.large', 'm1.xlarge', etc. see amazon docs for more info</span>
&nbsp;
reservation = ami.<span style="color: black;">run</span><span style="color: black;">&#40;</span>key_name=ssh_key_name, security_groups=security_groups,
                      instance_type=instance_size<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'New instance [%s]'</span> <span style="color: #66cc66;">%</span> reservation.<span style="color: black;">instances</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">public_dns_name</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The call is pretty simple at this point, we just need to pass in the data we&#8217;ve been collecting. Remember the security_groups argument must be a list. Also, keep in mind a reservation is returned from the create call, not the instance itself. The boto documentation can provide more information on the distinction.</p>
<h2>SSH into the Instance</h2>
<p>The above code should have output the public DNS name of the newly created instance. Once it&#8217;s finished starting (you can watch the progress in the web console or there are ways to do it in boto, I just haven&#8217;t included them here) you can SSH into it by passing the SSH key created earlier (substitute in the relevant information):</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ssh</span> <span style="color: #660033;">-i</span> <span style="color: #007800;">$SSH_KEY</span> root<span style="color: #000000; font-weight: bold;">@</span><span style="color: #007800;">$INSTANCE_DNS</span></pre></div></div>

<h2>Conclusion</h2>
<p>As you&#8217;d expect, there is a lot more to boto than just creating instances, such as creating/attaching Elastic Block Storage (EBS) volumes, creating/configuring Elastic Load Balancers (ELB), and adding Autoscaling Groups to load balancers. Many of the APIs look similar to the code used in creating an instance, so it&#8217;s just a matter of figuring out what you want to do.</p>
]]></content:encoded>
			<wfw:commentRss>http://noopenblockers.com/2010/04/27/getting-started-with-amazon-ec2-using-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django &#8220;no such column&#8221; error</title>
		<link>http://noopenblockers.com/2010/02/13/django-no-such-column/</link>
		<comments>http://noopenblockers.com/2010/02/13/django-no-such-column/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 03:46:33 +0000</pubDate>
		<dc:creator>Jay</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://noopenblockers.com/?p=903</guid>
		<description><![CDATA[I&#8217;ve been getting into Django recently. I&#8217;ll go into it more in another entry, but I ran into a small issue where my database seemed to get out of sync with my model. Running syncdb didn&#8217;t throw any errors, but when I tried to access the model from the server I&#8217;d get an error about [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been getting into Django recently. I&#8217;ll go into it more in another entry, but I ran into a small issue where my database seemed to get out of sync with my model. Running syncdb didn&#8217;t throw any errors, but when I tried to access the model from the server I&#8217;d get an error about &#8220;no such column&#8221;, even though I could see it created in the generated DDL.</p>
<p>It took me a bit of digging (in other words, it wasn&#8217;t in the tutorial), but there&#8217;s a manage command to reset the database for a particular app. Running that and re-syncing my database got me moving again.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">python manage.py reset <span style="color: #7a0874; font-weight: bold;">&#91;</span>appname<span style="color: #7a0874; font-weight: bold;">&#93;</span>
python manage.py syncdb</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://noopenblockers.com/2010/02/13/django-no-such-column/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>From Java to Python</title>
		<link>http://noopenblockers.com/2010/01/13/from-java-to-python/</link>
		<comments>http://noopenblockers.com/2010/01/13/from-java-to-python/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 14:10:29 +0000</pubDate>
		<dc:creator>Jay</dc:creator>
				<category><![CDATA[Geek]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://noopenblockers.com/?p=851</guid>
		<description><![CDATA[I&#8217;m not completely sure why, but I&#8217;m a bit embarrassed to admit to Planet Fedora how little my Python experience is; the majority of my experience is in Java. I was able to read and bug fix the Python code in Spacewalk, but I hadn&#8217;t really dug deep into my own project. Now that I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m not completely sure why, but I&#8217;m a bit embarrassed to admit to <a href="http://planet.fedoraproject.org/" target="new">Planet Fedora</a> how little my Python experience is; the majority of my experience is in Java. I was able to read and bug fix the Python code in Spacewalk, but I hadn&#8217;t really dug deep into my own project. Now that I&#8217;m not teaching any longer and have some free time (one of my main reasons for quitting), I can finally sit down and dork around with the language. After spending some time working on <a href="http://inventwithpython.com/" target="new">some basic games</a> and a <a href="http://github.com/jdob/ircbot" target="new">simple IRC bot</a>, I figured I&#8217;d step back and think about what the transition from Java to Python has felt like.</p>
<h2>Don&#8217;t Fear The Whitespace</h2>
<p>I constantly hear people mention the indentation in Python as the first thing when talking about moving to the language. Not only is it not as jarring of an experience as people make it out to be, it&#8217;s downright awesome. I&#8217;ve always been compulsive about my code format anyway, so the biggest difference is the lack of curly braces.</p>
<h2>Collections Are Awesome</h2>
<p>It&#8217;s much lighter-weight to throw things into a list or map (dictionary in Python) than it is in Java. Get out of the mentality that you have to jump through import hoops and rigid notation to create, access, or return collections. In Python, they even let you do cool things like assign multiple variables as a return from a call:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">exceptionType, exceptionValue, exceptionTraceback = <span style="color: #dc143c;">sys</span>.<span style="color: black;">exc_info</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<h2>Looping Feels Weird At First</h2>
<p>I got a little thrown off by this initially. Most loops read really well:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> square <span style="color: #ff7700;font-weight:bold;">in</span> openSquares:</pre></div></div>

<p>However, when looping through a set of numbers, you need to use the <code>range</code> method:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>:</pre></div></div>

<p>Looking at both of those examples brings me to my next point&#8230;</p>
<h2>Don&#8217;t Forget The Colon</h2>
<p>This keeps throwing me off, but after declaring a function*, loop, or if statement, don&#8217;t forget to end the line with a colon. I&#8217;m happy to be rid of curly braces, but I get over-ambitious and forget the colon too.</p>
<h2>Don&#8217;t Over-engineer Configuration</h2>
<p>Depending on what you&#8217;re doing, you can likely just stuff configuration values into a script and import it (not needing to compile really is liberating in this respect). That&#8217;ll also give you the use of lists and maps by default. If you&#8217;re not reading between the lines I&#8217;ll spell it out: no need for XML-based configuration, which is one of the more evil trends in Java.<br />
<br/><br />
There are definitely more things I could mention; don&#8217;t take this to be the only lessons I&#8217;ve learned (any other hints/tips are appreciated). But I do want to avoid a mammoth blog post that causes readers to go into a zombie-like trance, so I&#8217;ll stop it here for now. I do want to thank <a href="http://rm-rf.ca/" target="new">Devan (dgoodwin)</a> and <a href="http://zeusville.wordpress.com/" target="new">Jesus (zeus)</a> for dealing with the Java-veteran-turned-Python-noob and not finding a way to crash my chat client to avoid more questions. </p>
<p>* I haven&#8217;t seen a solid explanation of &#8220;Call them &#8216;functions&#8217; because you&#8217;ll sound like a Java guy calling them &#8216;methods&#8217;&#8221;, but this feels like something where using the wrong term will make me stand out as a Java developer in a Python world. So I&#8217;ve been <a href="http://rm-rf.ca/" target="new">advised</a> to take a militant approach of &#8220;Yes, I&#8217;m a Java guy learning Python, deal with the occasional terminology missteps.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://noopenblockers.com/2010/01/13/from-java-to-python/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Triple-quoted Strings</title>
		<link>http://noopenblockers.com/2009/04/20/triple-quoted-strings/</link>
		<comments>http://noopenblockers.com/2009/04/20/triple-quoted-strings/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 15:38:02 +0000</pubDate>
		<dc:creator>Jay</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://notebook.novasurv.com/?p=450</guid>
		<description><![CDATA[In Python, if you use three double quotes (I know, that just looks weird when written) you don&#8217;t have to escape newlines. For instance, I&#8217;m working with a query (it&#8217;s much longer, I cut out the middle):

1
2
3
4
5
6
7
8
9
10
11
12
_packageStatement_remove = &#34;&#34;&#34;
    select distinct
        pn.name name,
   [...]]]></description>
			<content:encoded><![CDATA[<p>In Python, if you use three double quotes (I know, that just looks weird when written) you don&#8217;t have to escape newlines. For instance, I&#8217;m working with a query (it&#8217;s much longer, I cut out the middle):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">_packageStatement_remove <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #0000ff;">&quot;
    select distinct
        pn.name name,
        pe.epoch epoch,
        pe.version version,
        pe.release release,
        pa.label  arch
    from rhnActionPackage ap,
        rhnPackage p,
[snip]
        and ap.package_arch_id = pa.id(+)
        and p.id = cp.package_id&quot;</span><span style="color: #0000ff;">&quot;&quot;</span></pre></td></tr></table></div>

<p>In Java, that&#8217;d be a lot uglier. I have no desire to convert the entire query, but it&#8217;d look something like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> query <span style="color: #339933;">=</span> 
<span style="color: #0000ff;">&quot;select distinct &quot;</span> <span style="color: #339933;">+</span> 
<span style="color: #0000ff;">&quot;        pn.name name, &quot;</span> <span style="color: #339933;">+</span>
<span style="color: #0000ff;">&quot;        pe.epoch epoch, &quot;</span> <span style="color: #339933;">+</span>
<span style="color: #0000ff;">&quot;        pe.version version, &quot;</span> <span style="color: #339933;">+</span>
<span style="color: #0000ff;">&quot;        pe.release release, &quot;</span> <span style="color: #339933;">+</span>
<span style="color: #0000ff;">&quot;        pa.label  arch &quot;</span> <span style="color: #339933;">+</span>
<span style="color: #009900;">&#91;</span>snip<span style="color: #009900;">&#93;</span></pre></td></tr></table></div>

<p>Also keep in mind that in most cases, you have to be careful to add the space after each line <em>within</em> the quotes. Otherwise, when Java munges this all into a single constant, you&#8217;ll get two words merged into one:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> foo <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;golden&quot;</span> <span style="color: #339933;">+</span>
<span style="color: #0000ff;">&quot;monkey&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The contents of foo is simply <code>"goldenmonkey"</code> without any spaces. Needless to say, that can really screw with your query.</p>
<p>Score one for Python.  <img src='http://noopenblockers.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://noopenblockers.com/2009/04/20/triple-quoted-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Equality &#8211; Part 1</title>
		<link>http://noopenblockers.com/2008/09/14/equality-part-1/</link>
		<comments>http://noopenblockers.com/2008/09/14/equality-part-1/#comments</comments>
		<pubDate>Mon, 15 Sep 2008 00:03:41 +0000</pubDate>
		<dc:creator>Jay</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://notebook.novasurv.com/?p=51</guid>
		<description><![CDATA[What is the proper way to compare two strings to determine if they contain the same text?
One of the hiccups new object-oriented programmers make revolves around comparing two objects for equality. The confusion typically stems from the initial learning of comparing two primitives:

int x = 0;
int y = 0;
boolean xyEqual = (x == y);

For primitives, [...]]]></description>
			<content:encoded><![CDATA[<p>What is the proper way to compare two strings to determine if they contain the same text?</p>
<p>One of the hiccups new object-oriented programmers make revolves around comparing two objects for equality. The confusion typically stems from the initial learning of comparing two primitives:</p>
<blockquote>
<pre>int x = 0;
int y = 0;
boolean xyEqual = (x == y);</pre>
</blockquote>
<p>For primitives, the above code works correctly, in this case returning <code>true</code>. However, the <code>==</code> operator has a significantly different meaning when used to compare two objects. Take, for instance, the following small variation on the code:</p>
<blockquote>
<pre>Person x = new Person("Tyler Durden");
Person y = new Person("Tyler Durden");
boolean xyEqual = (x == y);</pre>
</blockquote>
<p>For simplicity, assume the Person constructor assigns the parameter to an internal attribute used to track the person&#8217;s name.</p>
<p>Based on the primitive example, the typical assumption is that the code would return <code>true</code>. As you might have guessed given the tone of this post, this is incorrect; the above condition will return <code>false</code>.</p>
<p>The reason lies in the polymorphic nature of the <code>==</code> operator. When applied to objects, this operator has a significantly different execution than it does for primitives.</p>
<p>When two objects are passed to the <code>==</code> operator, the result indicates if <em>their object references are equal.</em> In other words, this check will determine if they both point to the exact same object in memory. Since primitives are not objects, it&#8217;s understandable that there would be a different meaning when applied to objects.</p>
<p>Keep in mind that when calling <code>new</code>, a new object is created. In this light, it is clear why the above code evaluates to false. Compare this to the following:</p>
<blockquote>
<pre>Person x = new Person("Marla Singer");
Person y = x;
boolean xyEqual = (x == y);</pre>
</blockquote>
<p>This changes the condition to evaluate to <code>true</code>. The assignment in the second statement does not result in a new object creation, but rather indicates that y should point to the same object as x. Given the above definition of <code>==</code> when applied to objects, it should be clear why the result is true.</p>
<p>So how are two objects compared to see if they are semantically equal? The answer lies in the <code>equals</code> method defined in the base <code>Object</code> class. The signature of this method is as follows:</p>
<blockquote>
<pre>public boolean equals(Object other);</pre>
</blockquote>
<p>Domain objects often need to <em>override</em> this method in their implementations to provide a meaningful equality comparison. One note on the <code>Object</code> implementation, it defaults to <code>==</code> behavior, which is why fleshed out domain objects will override this method. Before we get to a possible implementation of this method for the <code>Person</code> class, let&#8217;s look at the properties this method must honor, as defined by the Java specification:</p>
<ul>
<li>It is <em>reflexive</em>: for any non-null reference value x, <code>x.equals(x)</code> should return <code>true</code>.</li>
<li>It is <em>symmetric</em>: for any non-null reference values x and y, <code>x.equals(y)</code> should return <code>true</code> if and only if <code>y.equals(x)</code> returns <code>true</code>.</li>
<li>It is <em>transitive</em>: for any non-null reference values x, y, and z, if <code>x.equals(y)</code> returns <code>true</code> and <code>y.equals(z)</code> returns <code>true</code>, then <code>x.equals(z)</code> should return <code>true</code>.</li>
<li>It is <em>consistent</em>: for any non-null reference values x and y, multiple invocations of <code>x.equals(y)</code> consistently return <code>true</code> or consistently return <code>false</code>, provided no information used in equals comparisons on the objects is modified.</li>
<li>For any non-null reference value x, <code>x.equals(null)</code> should return <code>false</code>.</li>
</ul>
<p>With that in mind, let&#8217;s assume a person&#8217;s name is enough to identify them for equality. In reality, we&#8217;d probably use something guaranteed to be unique, such as a social security number or student/employee ID. But to stick with the above code snippet which only takes a name, we&#8217;ll use that.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> equals<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> other<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    Person otherPerson <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Person<span style="color: #009900;">&#41;</span>other<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>otherPerson.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Since this method uses the same signature as defined in <code>Object</code>, this implementation will be invoked in all cases where the object is a <code>Person</code>. Instead of simply checking object references, this code will do an equality comparison on the person&#8217;s name, giving us the desired logic.</p>
<p>Note that this further uses the <code>String</code> class implementation of <code>equals</code>, which is the correct mechanism to use when comparing strings.</p>
<p>Keep in mind this is the Java specific mechanism. Other object-oriented languages have a similar construct, however the syntax will vary. For instance, in Python the <code>==</code> operator tests the values of two variables for equality. To do object reference checking in Python, the <code>is</code> operator is used.</p>
<p>There is much more to say on the topic, and will be covered in future blogs. Future installments include:</p>
<ul>
<li>This post makes no mention of the <code>hashCode</code> method in the <code>Object</code> class. In many cases, both of these methods must be overridden at the same time.</li>
<li>The <code>Person</code> class implementation provided above makes a few assumptions. For now, I&#8217;ll leave it as an exercise to the reader to determine in what cases the above method will fail.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://noopenblockers.com/2008/09/14/equality-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
