473,395 Members | 1,458 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

xray module

I finally cleaned up the code I've been using for a while now to grab
objects out of modules via dotted-package names (all this work to avoid
using exec! Sheesh!). Feel free to use it, abuse it, or comment on it. I
realize many of you already do this on your own--this is just sugar for
the newbies. I'm releasing/announcing it for three reasons:

1. The ego rush of authorship, :D
2. I continually hear people asking for similar (if not exact)
functionality, especially those coming from a Java/Tomcat background,
and
3. The name is cool. I spent a lot of time on it.

Here 'tis:
# xray.py
"""Load modules, classes, functions, and attributes by dotted package
names.

Usage:

desiredClass = xray.classes("myapp.strtools.alwayslowercase", str)
newInstance = desiredClass()

or

for f in startup_function_names:
func_object = xray.functions(f)
func_object()
Rationale:

I try to create systems that are configurable by deployers; mostly
becase I
hate it when an application forces me to use the database, filesystem,
communication protocol, algorithm, or operating system du jour.
Abstracting
these basic components of an application is its own study (look up the
Gang
of Four "Strategy" pattern for a start); this is often accomplished with
classes which share signatures, often via subclassing. However, the
deployer
then needs to specify the class they wish to use. This module gives them
the ability to specify that with a single string (for example, in a text
configuration file).

"""

import sys

def modules(modulePath):
"""Load a module and retrieve a reference to that module."""
try:
aMod = sys.modules[modulePath]
if aMod is None:
raise KeyError
except KeyError:
# The last [''] is important.
aMod = __import__(modulePath, globals(), locals(), [''])
sys.modules[modulePath] = aMod
return aMod

def attributes(fullAttributeName):
"""Load a module and retrieve an attribute of that module."""

# Parse out the path, module, and attribute
lastDot = fullAttributeName.rfind(u".")
attrName = fullAttributeName[lastDot + 1:]
modPath = fullAttributeName[:lastDot]

aMod = modules(modPath)
# Let an AttributeError propagate outward.
anAttr = getattr(aMod, attrName)

# Return a reference to the attribute.
return anAttr

def functions(fullFuncName):
"""Load a module and retrieve a function object."""

aFunc = attributes(fullFuncName)

# Assert that the function is a *callable* attribute.
if not callable(aFunc):
raise TypeError(u"'%s' is not callable." % fullFuncName)

# Return a reference to the function itself,
# not the results of the function.
return aFunc

def classes(fullClassName, parentClass=None):
"""Load a module and retrieve a class (NOT an instance).

If the parentClass is supplied, className must be of parentClass
or a subclass of parentClass (or None is returned).
"""
aClass = functions(fullClassName)

# Assert that the class is a subclass of parentClass.
if parentClass is not None:
if not issubclass(aClass, parentClass):
raise TypeError(u"'%s' is not a subclass of %s" %
(fullClassName, parentClass.__name__))

# Return a reference to the class itself, not an instantiated
object.
return aClass

# end xray.py
Robert Brewer
MIS
Amor Ministries
fu******@amor.org

Jul 18 '05 #1
0 1182

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Bo Peng | last post by:
Dear list, I am writing a Python extension module that needs a way to expose pieces of a big C array to python. Currently, I am using NumPy like the following: PyObject* res =...
5
by: dody suria wijaya | last post by:
I found this problem when trying to split a module into two. Here's an example: ============== #Module a (a.py): from b import * class Main: pass ============== ==============
3
by: David T. Ashley | last post by:
Hi, Red Hat Enterprise Linux 4.X. I'm writing command-line PHP scripts for the first time. I get the messages below. What do they mean? Are these operating system library modules, or...
10
by: Bonzol | last post by:
vb.net Hey there, could someone just tell me what the differnce is between classes and modules and when each one would be used compared to the other? Any help would be great Thanx in...
21
KevinADC
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Uploading files from a local computer to a remote web server has many useful purposes, the most...
40
by: rjcarr | last post by:
Sorry if this is a completely newbie question ... I was trying to get information about the logging.handlers module, so I imported logging, and tried dir(logging.handlers), but got: ...
4
by: rkmr.em | last post by:
Hi I have a function data, that I need to import from a file data, in the directory data If I do this from python interactive shell (linux fedora core 8) from dir /home/mark it works fine: ...
0
by: Fredrik Lundh | last post by:
Jeff Dyke wrote: so how did that processing use the "mymodulename" name? the calling method has nothing to do with what's considered to be a local variable in the method being called, so...
6
by: dudeja.rajat | last post by:
Hi, I found on the net that there is something called module initialization. Unfortunately, there is not much information for this. However, small the information I found module initialization...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.