Parameterization of the import statement

I support the Python module, which wraps and provides DLL functionality (also supported by me). Interaction with a DLL uses ctypes.

All this works great thanks to the wonders of ctypes. However, since I'm by no means a Python expert, there are some parts of Python that I feel are not idiomatic.

In particular, I suggest managing the location of the DLL for the user of the module. The DLL is loaded during module import. I do this because I want to switch the behavior based on the capabilities of the DLL, and I need to load the DLL to request its behavior.

By default, loading a DLL depends on the DLL search path to find the DLL. I would like to be able to allow the user to specify the full path to the DLL if they want to select a specific version.

Right now I'm doing this using an environment variable, but I admit that this is a pretty grotesque way to do this. I am looking for the canonical or idiomatic Python method for an importer of a module to transfer some information to a module, which can be accessed while importing the module.

+3
source share
2 answers

You should defer loading the DLL to the point where it is actually used for the first time, and offer an additional initialize function:

_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()

initialized() API. , , , ( ).

API, :

class DLLAPI:
  def __init__(self, path=None):
    ...

DLLAPI DLL. DLL .

+5

http://code.google.com/p/modwsgi/wiki/VirtualEnvironments :

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 
+1

Source: https://habr.com/ru/post/1787106/


All Articles