From 9d4ab2cb8985be1aef71d2e003effabd369f2360 Mon Sep 17 00:00:00 2001 From: dawncold Date: Sat, 24 May 2014 21:02:10 +0800 Subject: [PATCH] same name of function and package, import job handler will encounter ImportError, see tests for details --- .gitignore | 1 + pyres/__init__.py | 13 +++++++++++++ tests/__init__.py | 4 ++++ tests/a/__init__.py | 4 ++++ tests/a/a.py | 13 +++++++++++++ 5 files changed, 35 insertions(+) create mode 100644 tests/a/__init__.py create mode 100644 tests/a/a.py diff --git a/.gitignore b/.gitignore index e3a0b9e..79201f7 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ dist/ *.swp *.swo .tox/ +.idea/ \ No newline at end of file diff --git a/pyres/__init__.py b/pyres/__init__.py index 53bc6ec..04072a1 100644 --- a/pyres/__init__.py +++ b/pyres/__init__.py @@ -96,6 +96,19 @@ def safe_str_to_class(s): else: raise ImportError('') +def safe_str_to_class_v2(s): + """Helper function to map string class names to module classes.""" + lst = s.split(".") + klass = lst[-1] + mod_list = lst[:-1] + module = ".".join(mod_list) + import sys + mod = sys.modules.get(module) + if hasattr(mod, klass): + return getattr(mod, klass) + else: + raise ImportError('') + def str_to_class(s): """Alternate helper function to map string class names to module classes.""" lst = s.split(".") diff --git a/tests/__init__.py b/tests/__init__.py index d75c866..eb360c5 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -108,9 +108,13 @@ def test_str_to_class(): class ImportTest(unittest.TestCase): def test_safe_str_to_class(self): from pyres import safe_str_to_class + from pyres import safe_str_to_class_v2 + from tests.a import b assert safe_str_to_class('tests.Basic') == Basic self.assertRaises(ImportError, safe_str_to_class, 'test.Mine') self.assertRaises(ImportError, safe_str_to_class, 'tests.World') + self.assertRaises(ImportError, safe_str_to_class, '{}.{}'.format(b.__module__, b.__name__)) + self.assertEqual(safe_str_to_class_v2('{}.{}'.format(b.__module__, b.__name__)), b) class PyResTests(unittest.TestCase): diff --git a/tests/a/__init__.py b/tests/a/__init__.py new file mode 100644 index 0000000..c07ed29 --- /dev/null +++ b/tests/a/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, print_function, division +from .a import a +from .a import b \ No newline at end of file diff --git a/tests/a/a.py b/tests/a/a.py new file mode 100644 index 0000000..0ee893b --- /dev/null +++ b/tests/a/a.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals, print_function, division + + +def a(): + pass + + +def b(): + pass + +a.perform = lambda x: x +b.perform = lambda x: x \ No newline at end of file