Skip to content

Commit 4623a13

Browse files
committed
Added some helper functions
1 parent e77d770 commit 4623a13

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

ellar/helper/importer.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import re
12
import typing as t
23

4+
_module_import_regex = re.compile("(((\\w+)?(\\.<\\w+>)?(\\.\\w+))+)", re.IGNORECASE)
5+
36

47
class ImportFromStringError(Exception):
58
pass
@@ -49,3 +52,21 @@ def module_import(module_str: str) -> t.Any:
4952
raise exc from None
5053
message = 'Could not import module "{module_str}".'
5154
raise ImportFromStringError(message.format(module_str=module_str))
55+
56+
57+
@t.no_type_check
58+
def get_class_import(klass: t.Union[t.Type, t.Any]) -> str:
59+
"""
60+
Generates String to import a class object
61+
:param klass:
62+
:return: string
63+
"""
64+
if hasattr(klass, "__class__") and not isinstance(klass, type):
65+
klass = klass.__class__
66+
67+
regex_path = _module_import_regex.search(str(klass))
68+
result = regex_path.group()
69+
split_result = result.rsplit(".", maxsplit=1)
70+
if len(split_result) == 2:
71+
return f"{split_result[0]}:{split_result[1]}"
72+
return result

0 commit comments

Comments
 (0)