<?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>scienceoss.com &#187; Python modules</title>
	<atom:link href="http://scienceoss.com/categories/python/python-modules/feed/" rel="self" type="application/rss+xml" />
	<link>http://scienceoss.com</link>
	<description>useful tidbits for using open source software in science</description>
	<lastBuildDate>Wed, 26 May 2010 03:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Calculate sunrise and sunset with PyEphem</title>
		<link>http://scienceoss.com/calculate-sunrise-and-sunset-with-pyephem/</link>
		<comments>http://scienceoss.com/calculate-sunrise-and-sunset-with-pyephem/#comments</comments>
		<pubDate>Sat, 26 Apr 2008 03:14:22 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python modules]]></category>
		<category><![CDATA[pyephem]]></category>
		<category><![CDATA[sunrise]]></category>
		<category><![CDATA[sunset]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=121</guid>
		<description><![CDATA[PyEphem (from the Greek word ephemeris) is the way to calculate the positions of all sorts of astronomical bodies in Python. I used it recently to calculate a year&#8217;s worth of sunrise and sunset times. Using something as advanced as PyEphem for something this astronomically simple might be overkill, but it works well. Here&#8217;s how [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://rhodesmill.org/pyephem/">PyEphem</a> (from the Greek word <a href="http://http://en.wikipedia.org/wiki/Ephemeris">ephemeris</a>) is the way to calculate the positions of all sorts of astronomical bodies in Python. <span id="more-121"></span></p>
<p>I used it recently to calculate a year&#8217;s worth of sunrise and sunset times.  Using something as advanced as PyEphem for something this astronomically simple might be overkill, but it works well.  Here&#8217;s how I did it:</p>
<pre class="brush: python; title: ; notranslate">
import ephem
import datetime

obs = ephem.Observer()
obs.lat = '38.8'
obs.long= '-75.2'

start_date = datetime.datetime(2008, 1, 1)
end_date = datetime.datetime(2008, 12, 31)
td = datetime.timedelta(days=1)

sun = ephem.Sun()

sunrises = []
sunsets = []
dates = []

date = start_date
while date &lt; end_date:
    date += td
    dates.append(date)
    obs.date = date

    rise_time = obs.next_rising(sun).datetime()
    sunrises.append(rise_time)

    set_time = obs.next_setting(sun).datetime()
    sunsets.append(set_time)
</pre>
<p>To plot day length in hours over the course of a year, first run the above code.  Then (assuming you have <a href="http://matplotlib.sourceforge.net/">matplotlib</a>):</p>
<pre class="brush: python; title: ; notranslate">
from pylab import *
daylens = []
for i in range(len(sunrises)):
    timediff = sunsets[i] - sunrises[i]
    hours = timediff.seconds / 60. / 60.  # to get it in hours
    daylens.append(hours)

plot(dates, daylens)

# if you have an older version of matplotlib, you may need
# to convert dates into numbers before plotting:
# dates = [date2num(i) for i in dates]

xlabel('Date')
ylabel('Hours')
title('Day length in 2008')
show()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/calculate-sunrise-and-sunset-with-pyephem/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Modules in Python</title>
		<link>http://scienceoss.com/modules-in-python/</link>
		<comments>http://scienceoss.com/modules-in-python/#comments</comments>
		<pubDate>Sat, 03 Nov 2007 18:33:26 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Python modules]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=13</guid>
		<description><![CDATA[What is a Python module? A module in Python is a collection of code that can be used in other programs. You can think of a module as being like a toolbox, where another program can import all or just a few of the tools found in the module. Here are some reasons to use [...]]]></description>
			<content:encoded><![CDATA[<h2>What is a Python module?</h2>
<p>A module in Python is a collection of code that can be used in other programs.  You can think of a module as being like a toolbox, where another program can import all or just a few of the tools found in the module.  Here are some reasons to use modules, and some examples of their use.<br />
<span id="more-13"></span></p>
<h2>Why use modules?</h2>
<p>One reason is organization.  Modules organize code the same way folders organize files.  If you&#8217;re writing only small snippets of code you probably don&#8217;t need a module, just like you probably don&#8217;t need a folder to organize only a few files you&#8217;re working with on your computer.  But once a program starts to get big, modules are a good way to organize code.</p>
<p>Another reason is convenience.  If you have many programs that will use the same function, it&#8217;s best to put that shared function in a module.  That way, if you want to change anything in the way that function works, you only have to change it once (in the module) as opposed to changing it in every program you ever used it in (if you didn&#8217;t use a module).</p>
<h2>How do you make a module?</h2>
<p>Any Python script can act as a module.  You don&#8217;t have to do anything special.</p>
<h2>How do you use a module?</h2>
<p>To use a module in another script, you have to import the module into the script.  There are a couple of ways you can do this, and the way you choose depends on how you want to refer to the contents of the module.</p>
<h2>How about an example?</h2>
<p>OK.</p>
<p>Say we have some Python code saved as the file &#8220;usefulStuff.py&#8221; in our current working directory, and usefulStuff.py has three extremely useful functions in it:</p>
<ul>
<li><code>winningLotteryNumbers</code></li>
<li><code>whatToMakeForDinner</code></li>
<li><code>doSomethingToHardDrive</code></li>
</ul>
<p>It looks something like this:</p>
<h3>usefultStuff.py &nbsp;&nbsp;&nbsp;&nbsp; <-- <em>the module</em></h3>
<pre class = "prettyprint"><code class = "code">
"""A module full of useful stuff."""

num = 5  # just a variable created now, to make a point later...

def winningLotteryNumbers();
    # some code here

def whatToMakeForDinner():
    # some code here

def doSomethingToHardDrive();
    # some code here
</code></pre>
<p>OK, so let&#8217;s write a new script in the same directory as <code>usefulStuff.py</code> is saved in.  For our new script, we only want to use two of those functions. To use them, we need to import them using one of the following methods:</p>
<h2>Importing a module: Method 1 (best)</h2>
<h3>script1.py</h3>
<pre class = "prettyprint"><code class = "code">
import usefulStuff
x = usefulStuff.winningLotteryNumbers()
y = usefulStuff.whatToMakeForDinner()
numberFive = usefulStuff.num
</code></pre>
<p>Note that in order to access the functions, you have to specify where they are coming from: the <code>usefulStuff</code> module.  We imported these two functions into the <code>usefulStuff</code> <em><strong>namespace</strong></em> of this script.  The last line shows that we can access the variable <code>num</code> that was created in <code>usefulStuff.py</code>.  That is, <code>numberFive</code> will now point to the number 5.</p>
<p>This is probably the best method to use.  It keeps things organized and is unambiguous.  The downside?  Lots of typing.</p>
<h2>Importing a module: Method 2</h2>
<h3>script2.py</h3>
<pre class = "prettyprint"><code class = "code">
import usefulStuff as u
x = u.winningLotteryNumbers()
y = u.whatToMakeForDinner()
numberFive = u.num
</code></pre>
<p>This is similar to above, since to access the functions you still have to specify from which namespace they are coming from.  But in this case, the namespace has been renamed to <code>u</code>.  Why? Simply to make it easier to type.</p>
<h2>Importing a module: Method 3</h2>
<h3>script3.py</h3>
<pre class = "prettyprint"><code class = "code">
from usefulStuff import winningLotteryNumbers, whatToMakeForDinner
x = winningLotteryNumbers()
y = whatToMakeForDinner()
numberFive = num   # see <a href="#warning1">warning 1</a>
</code></pre>
<p>Here, the only things imported are the items specified in the import statement.  What namespace do they occur in?  The namespace of the script, <code>script1.py</code>.  The advantage? Less typing!  For small scripts, this is probably the way to go.  But if this script gets very large, and we want to make our own functions or variables with similar names within it, we might need the tighter organization of keeping namespaces separate.</p>
<p>By the way, if we wanted to access the doSomethingToHardDrive module, we&#8217;d have to add it to the list of things to import on the first line.</p>
<p><a name="warning1">Warning 1: </a>What does <code>numberFive</code> point to?  Remember, we didn&#8217;t import the variable <code>num</code> from <code>usefulStuff</code>, so this script doesn&#8217;t know it exists.  the result is that we&#8217;d get a NameError saying that <code>num</code> doesn&#8217;t exist.</p>
<h2>Importing a module: Method 4</h2>
<h3>script4.py</h3>
<pre class = "prettyprint"><code class = "code">
from usefulStuff import *
x = winningLotteryNumbers()
y = whatToMakeForDinner()
</code></pre>
<p>Using this method, EVERYTHING from <code>usefulStuff</code> was imported into this script&#8217;s namespace, including the <code>doSomethingToHardDrive</code> function.  For a script this small, it&#8217;s not really an issue, but for larger programs, this can introduce all kinds of annoying bugs, not to mention cluttering the namespace with unused functions and variables.  Probably best to stay away from this method of importing.</p>
<h2>Comparison to Matlab</h2>
<p>If you&#8217;ve used Matlab before, you know that you use functions by naming the m-file after the name of the function.  Then, as long as the function is in your path, Matlab will find it.  This works well for small scripts.  But as you start writing larger programs, you keep creating unique function names to avoid name conflicts.  The Python method of using modules is to keep things organized, and is really helpful in larger programs.</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/modules-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

