Phillip J. Eby wrote:
At 05:09 PM 8/1/2005 -0500, Ian Bicking wrote:
I was thinking some more about WSGI configuration, and much configuration involves some "import a string" routing, that looks like importstring("os.path:sep") or somesuch. But we implement it slightly differently. And maybe there could be a PEP and whatnot, but I don't even know what module that would go into, and it would just have to be backported for a long time anyway... but then it seemed like it would fit nicely into pkg_resources, and just about anywhere I want to import strings I expect pkg_resources to be around as well.
from pkg_resources import EntryPoint
def import_string(s): return EntryPoint.parse("x="+s).load(False)
OK... the error messages will be a little funny due to the appropriation of the functionality from a different feature. It would be nice if this was a separate function. Also, what about evaluating the text after ':' in the scope of the module, instead of using getattr? Though that does open the possibility of security issues (which are still present with getattr, but an actual exploit is rather unlikely). Relatedly, in most places where I want to use this, I now also want to use a entry point spec. But I don't know what entry point specs should look like. So maybe even better would be a combination of the two. This might look like: def import_string(spec, group=None): if group is not None and ' ' in spec: dist, name = spec.split(None, 1) return load_entry_point(dist, group, name) return EntryPoint.parse('x='+spec).load(False) This uses a convention of "PackageName entry_point_name", with the space distinguishing this from other imports. But I think a space is a rather vague way to make the distinction... maybe "PackageName[entry_point_name]"? Then if [ comes before any : it's a entry point, otherwise it's an importable string. If that sounds good I can submit a patch that does more thorough error checking, and separates the importing from EntryPoint. -- Ian Bicking / ianb@colorstudy.com / http://blog.ianbicking.org