File: utils.py

package info (click to toggle)
python-model-mommy 1.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 164 kB
  • sloc: python: 875; makefile: 4
file content (29 lines) | stat: -rw-r--r-- 728 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-
import importlib

from six import string_types


def import_if_str(import_string_or_obj):
    """
    Import and return an object defined as import string in the form of

        path.to.module.object_name

    or just return the object if it isn't a string.
    """
    if isinstance(import_string_or_obj, string_types):
        return import_from_str(import_string_or_obj)
    return import_string_or_obj


def import_from_str(import_string):
    """
    Import and return an object defined as import string in the form of

        path.to.module.object_name
    """
    path, field_name = import_string.rsplit('.', 1)
    module = importlib.import_module(path)
    return getattr(module, field_name)