Quantcast
Viewing latest article 8
Browse Latest Browse All 10

Python Modules :: Building a little Library

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.



Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 8
Browse Latest Browse All 10

Trending Articles