Domanda

In runtime, il codice Python ottiene il nome di un sottomodulo da caricare, che non so prima. Ora, voglio controllare, se questo sottomodulo esiste all'interno di un modulo esistente. Considerare questa struttura, dove è possibile specificare foo e bar:

master/
|
|- __init__.py
|
|- foo/
|  |
|  |- __init__.py
|
|- bar/
   |
   |- __init__.py
.

Ora, di solito lo faccio, che funziona per DEFS e Variables:

import master

unknown_submodule = "foo"
if hasattr(master, unknown_submodule):
    pass # all's well
.

o sto catturando l'attributoerror, che funziona allo stesso modo.

Tuttavia, con la struttura di file sopra riportata, non sono in grado di avvicinare questo approccio e lavorare. hasattr() restituisce sempre falso (cioè, c'è sempre un attributoReerror lanciato).

Se guardo dir(master), vedo questa uscita:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
.

e persino specificamente specificamente il __all__ in master/__init__.py non aiuta, ma cambia la dir () su

['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
.

Qualche idea, cosa sto facendo male, o se c'è un modo per raggiungere questi tipi di test? (BTW: Python 2.6 su Win / Cygwin, se questo è di qualsiasi interesse)

È stato utile?

Soluzione

I sottomoduli non sono attributi dei loro moduli genitore se non dichiarati esplicitamente.Basta provare a importare il modulo e catturare ImportError:

try:
    __import__("os.peth", fromlist=[os])
except ImportError:
    pass
.

Altri suggerimenti

you can do

try:
 import module.submodule

except ImportError:
  print 'failed or whatever'

I recently had to check submodule existence and since I'm using python 3.4.1, I'm giving a new answer to the question:

In python 3.4.1 you can use importlib.util.find_spec(name, package=None) (https://docs.python.org/3.4/library/importlib.html#importlib.util.find_spec)

import importlib
module_exists = importlib.util.find_spec('path.to.my.module')

That easy =)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top