I maintain a Python module that wraps and exposes the functionality of a DLL (also maintained by me). The interfacing with the DLL uses ctypes.
This all works wonderfully thanks to the wonders of ctypes. However, as I am by no means a Python expert, there are some parts of the Python that I feel are not idiomatic.
In particular I offer control of the DLL location to the user of the module. The DLL is loaded during the import of the module. I do this because I want to switch behaviour based on the capability of the DLL, and I need to load the DLL in order to query its behaviour.
By default, the DLL load relies of the DLL search path to locate the DLL. I would like to be able to allow the user to specify a full path to th开发者_StackOverflow中文版e DLL, should they wish to pick out a particular version.
At the moment I do this by using an environment variable but I recognise that this is a rather grotesque way to do it. What I'm looking for is a canonical or idiomatic Python way for the module importer to pass some information to the module which can be accessed at module import time.
You should defer loading the DLL to the point where it's actually used for the first time, and offer an optional function initialize:
_initialized=False
def initialize(path=None):
if _initialized:
if path:
raise ValueError, "initialize called after first use"
return
if path is None:
path = default_path
load_dll(path)
determine_features()
Then, call initialized()
in all API you offer. This gives the user a chance to override it, but if they don't, it will continue to work as it does today (you can even preserve support for the environment variable).
If you are willing to change the API, use classes:
class DLLAPI:
def __init__(self, path=None):
...
Users would have to create a DLLAPI instance, and may or may not pass a DLL path. That should allow to even use different DLLs simultaneously.
This code is taken from this page http://code.google.com/p/modwsgi/wiki/VirtualEnvironments It adds some paths to explores :
ALLDIRS = ['usr/local/pythonenv/PYLONS-1/lib/python2.5/site-packages']
import sys
import site
# Remember original sys.path.
prev_sys_path = list(sys.path)
# Add each new site-packages directory.
for directory in ALLDIRS:
site.addsitedir(directory)
# Reorder sys.path so new directories at the front.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
精彩评论