Parameterising an import statement
Question: 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 the 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.


Answer: 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.

