GithubHelp home page GithubHelp logo

rochacbruno-archive / import_string Goto Github PK

View Code? Open in Web Editor NEW
11.0 1.0 1.0 22 KB

Imports an object based on a string import_string('package.module:function_name')() - Based on werkzeug.utils

License: ISC License

Makefile 18.53% Python 81.47%
import importer metaprogramming

import_string's Introduction

DEPRECATED don't use it. Please do:

import importlib
foopath = 'src.apis.foo.Foo'

module_name = '.'.join(foopath.split('.')[:-1]) # to get src.apis.foo
foo_module = importlib.import_module(module_name)
clazz_name = foopath.split('.')[-1] # to get Foo
Foo = getattr(module_name, clazz_name)
print Foo()

import_string

Documentation Status Updates

Imports an object based on a string

Features

Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (.) or with a colon as object delimiter (:). If silent is True the return value will be None if the import fails.

Usage

import import_string

module = import_string('my_system.my_package.my_module')

function = import_string('my_system.my_module:some_function')

Class = import_string('my_system.my_module:SomeClass', silent=True)
# If path doesn't exist Class = None

Live demo

See it in action here: https://repl.it/EGdS/0

Credits

import_string's People

Contributors

rochacbruno avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

carlosruperez

import_string's Issues

Sharing some experience

Hi @rochacbruno, nice work exporting this code to a new library, it's really usefull :)

I've done done this kind of import in some projects, but using this approach:

import importlib
foopath = 'src.apis.foo.Foo'

module_name = '.'.join(foopath.split('.')[:-1]) # to get src.apis.foo
foo_module = importlib.import_module(module_name)
clazz_name = foopath.split('.')[-1] # to get Foo
Foo = getattr(module_name, clazz_name)
print Foo()

It's almost the same thing, but using importlib instead of import directly. Actually, importlib uses the import function as well. Anyway, just creating this issue to share some alternatives to the same goal.

Thank you!

Initial Update

Hi 👊

This is my first visit to this fine repo, but it seems you have been working hard to keep all dependencies updated so far.

Once you have closed this issue, I'll create seperate pull requests for every update as soon as I find one.

That's it for now!

Happy merging! 🤖

Improve error message

Using it from manage when some file has missing library import inside it the error message is not clear.

# robottelo.decorators.func_locker

from pytest_services.locks import file_lock  

# pytest_services x is not installed
# so the following error message should be more clear about it.
@localhost(rob63) :~/P/robottelo|master⚡?
➤ manage shell                                                                                                                                                            12:41:26
Traceback (most recent call last):
  File "/home/brocha/.virtualenvs/rob63/bin/manage", line 11, in <module>
    sys.exit(main())
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/manage/cli.py", line 235, in main
    return manager()
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/click/core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/manage/cli.py", line 196, in shell
    MANAGE_DICT
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/manage/cli.py", line 108, in create_shell
    auto_imported = import_objects(manage_dict)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/manage/auto_import.py", line 57, in import_objects
    import_submodules(name)
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/manage/auto_import.py", line 21, in import_submodules
    import_string('{0}.{1}'.format(name, item[1]))
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/import_string/base.py", line 61, in import_string
    sys.exc_info()[2])
  File "/home/brocha/.virtualenvs/rob63/lib/python2.7/site-packages/import_string/base.py", line 54, in import_string
    raise ImportError(e)
import_string.base.ImportStringError: import_string() failed for 'robottelo.decorators.func_locker'. Possible reasons are:
 
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
 
Debugged import:
 
- 'robottelo' found in './robottelo/__init__.py'.
- 'robottelo.decorators' found in './robottelo/decorators/__init__.py'.
- 'robottelo.decorators.func_locker' not found.
 
Original exception:
 
ImportError: 'module' object has no attribute 'func_locker'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.