Skip to content

Instantly share code, notes, and snippets.

@glenfant
Created January 6, 2015 11:46
Show Gist options
  • Save glenfant/ec16f9aa68e33c7b88dc to your computer and use it in GitHub Desktop.
Save glenfant/ec16f9aa68e33c7b88dc to your computer and use it in GitHub Desktop.
Turns a dotted name in a string as 'sys.path' into a Python object
# -*- coding: utf-8 -*-
"""
==========
dottedname
==========
This module may be used when you need to refer to Python objects from non
Python files. For example, in a configuration file.
Resolve a python dotted name (stolen from zope.dottedname)
>>> int(resolve('math.pi'))
3
>>> int(resolve('.e', module='math'))
2
"""
def resolve(name, module=None):
name = name.split('.')
if not name[0]:
if module is None:
raise ValueError("relative name without base module")
module = module.split('.')
name.pop(0)
while not name[0]:
module.pop()
name.pop(0)
name = module + name
used = name.pop(0)
found = __import__(used)
for n in name:
used += '.' + n
try:
found = getattr(found, n)
except AttributeError:
__import__(used)
found = getattr(found, n)
return found
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment