EgonDev

March 2, 2010

Python Modules :: Building a little Library

Filed under: What I Did Today — Tags: — egoncasteel @ 9:20 pm

Here is what I did for my little dev library for Python

  • Made a directory in my home folder called /home/egon/pyModules
  • Added an empty file to my home directory, the pyModules director, and inside any sub-directories named __init__.py

So what does that get you?

Well now I can import scripts buy using a statement like this:

import pyModules.easygui.easygui

This will import the easygui module from the /home/egon/pyModules/easygui directory. You can now use functions defined in the easygui module calling them as such:

pyModule.easygui.easygui.msgbox('hello')

don’t worry there is a short cut coming

Now you really don’t want to type pyModules.stuff.stuff every time you want to access a method so here is the shortcut:

egui = pyModule.easygui.easygui
egui.msgbox('hello')

See told you not to worry

Once you assign the module you imported to a new name you can use that name instead of the full reference.

So what is going on here?

Well in Ubuntu your home directory is part of your Python path (where Python gos looking when you try to import a module). By adding the __init__.py files it tells Python to treat those directories as modules. That allows us to you the dot notation to get to the module you want to import.

Why bother?

I just came up with this scheme to organize the modules I would using while learning Python. I didn’t want to just drop them into my home directory or the main Python directory. This seemed like a good way to do it to me, but I would never dare say it is a good idea for everyone. Also this maybe  a really ugly way to do it. I don’t know enough about Python yet to say. Feel free to put a better solution in comments.


Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: