Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

same name of function and package, import job handler will encounter ImportError #137

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ dist/
*.swp
*.swo
.tox/
.idea/
13 changes: 13 additions & 0 deletions pyres/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(".")
Expand Down
4 changes: 4 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions tests/a/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division
from .a import a
from .a import b
13 changes: 13 additions & 0 deletions tests/a/a.py
Original file line number Diff line number Diff line change
@@ -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