Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pkgutil.walk_packages not returning subpackages

I have a package layout:

scenarios/
    __init__.py
    X/
        __init__.py
        Y/
            __init__.py
    Z/
        __init__.py 

I have executed

import scenarios
pkgutil.walk_packages(scenarios.__path__, scenarios.__name__ + '.')

But this generates a list only including the packages X and Z, Y is missing. What can I use to get all the sub directories?

Thanks

like image 872
user2357484 Avatar asked Jun 10 '13 13:06

user2357484


People also ask

How do I show subpackages in Python?

Python subpackages To access subpackages, we use the dot operator. This is the __init__.py file in the constants directory. We import the names tuple. This is the data.py module in the constants directory.

What is Pkgutil in Python?

Source code: Lib/pkgutil.py. This module provides utilities for the import system, in particular package support.

What is __ PATH __ in Python?

Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.


1 Answers

Here is a theory: The walk_packages function attempts to import each module listed. When it gets to the sub-package "Y" it attempts to import it, but there is an error. By default, this error is suppressed. A sideeffect is that the walk_packages function doesn't recurse into Y. You can test this theory using the "onerror" keyword argument. For example:

import sys, pkgutil
from traceback import print_tb

def onerror(name):
    print("Error importing module %s" % name)
    type, value, traceback = sys.exc_info()
    print_tb(traceback)

import scenarios
pkgutil.walk_packages(scenarios.__path__, scenarios.__name__ + '.', onerror=onerror)
like image 197
jdg Avatar answered Sep 21 '22 18:09

jdg