Skip to content

Commit 7440064

Browse files
committed
Added lazy_import to graphene. Fixed #316
1 parent 0e2d9be commit 7440064

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

graphene/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
PageInfo
4444
)
4545
from .utils.resolve_only_args import resolve_only_args
46+
from .utils.module_loading import lazy_import
4647

4748
__all__ = [
4849
'AbstractType',
@@ -72,4 +73,6 @@
7273
'ClientIDMutation',
7374
'Connection',
7475
'ConnectionField',
75-
'PageInfo']
76+
'PageInfo',
77+
'lazy_import',
78+
]

graphene/utils/module_loading.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from functools import partial
2+
from importlib import import_module
3+
4+
5+
def import_string(dotted_path):
6+
"""
7+
Import a dotted module path and return the attribute/class designated by the
8+
last name in the path. Raise ImportError if the import failed.
9+
"""
10+
try:
11+
module_path, class_name = dotted_path.rsplit('.', 1)
12+
except ValueError as err:
13+
raise ImportError("%s doesn't look like a module path" % dotted_path)
14+
15+
module = import_module(module_path)
16+
17+
try:
18+
return getattr(module, class_name)
19+
except AttributeError as err:
20+
raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
21+
module_path, class_name)
22+
)
23+
24+
25+
def lazy_import(dotted_path):
26+
return partial(import_string, dotted_path)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from pytest import raises
2+
3+
from graphene import String
4+
from ..module_loading import lazy_import, import_string
5+
6+
7+
def test_import_string():
8+
MyString = import_string('graphene.String')
9+
assert MyString == String
10+
11+
12+
def test_import_string_module():
13+
with raises(Exception) as exc_info:
14+
import_string('graphenea')
15+
16+
assert str(exc_info.value) == 'graphenea doesn\'t look like a module path'
17+
18+
19+
def test_import_string_class():
20+
with raises(Exception) as exc_info:
21+
import_string('graphene.Stringa')
22+
23+
assert str(exc_info.value) == 'Module "graphene" does not define a "Stringa" attribute/class'
24+
25+
26+
def test_lazy_import():
27+
f = lazy_import('graphene.String')
28+
MyString = f()
29+
assert MyString == String

0 commit comments

Comments
 (0)