R
R
Relrin2016-01-10 14:48:44
Python
Relrin, 2016-01-10 14:48:44

Are all dependent libraries used when imported into Python?

Now I am writing my own library for Python, which will be compatible with Django/SQLAlchemy ORM. At the moment, the structure inside the library/package is as follows:

MyProject
  |-- db
    |-- orm
      |-- django 
      |-- sqlalchemy

Accordingly, in the sqlaclhemy directory, some *.py files are implemented that ensure compatibility with SQLAlchemy ORM, and django is an implementation for Django ORM. The question is the following: if a programmer has installed only this package + Django, will he not have an ImportError when he works only with the Django ORM, without explicitly importing anything for SQLAlchemy (if there is an explicit call for this ORM, it’s clear, the error is will occur)? If it does, how can it be avoided?
Perhaps someone can suggest the so-called "best practice" to do something better in this regard?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nirvimel, 2016-01-10
@Relrin

In Python, imports are completely dynamic and happen at runtime. You can write:

if moon_phase == 42:
      import sqlalchemy

Then ImportErrorit will fly out at a certain phase of the moon.
Package dependencies in setuptools have nothing to do with this.
As for best practice, the abstraction from the ORM or any other layer is often implemented like this:
  • The general functionality, which does not depend on the implementation, is taken out to the core, which is packaged as a separate mylibrary_core.
  • Links to a specific implementation are packaged as plugins in separate packages ( mylibrary_django, for example).
  • Each such plugin has a dependency on the core and on a specific implementation ( django, for example).
  • The end user starts the installation immediately with mylibrary_django, which automatically pulls up mylibrary_core, which the user does not have to worry about.

S
sim3x, 2016-01-10
@sim3x

is_user_install_anything_useful = False

try:
    import django
    is_user_install_anything_useful = True
except ImportError:
    pass

try:
    import sqlalchemy
    is_user_install_anything_useful = True
except ImportError:
    pass

if not is_user_import_anything_useful: 
     raise ImportError('Install django or SQLalchemy')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question