0

I have a Python utility library pfacets. This library uses a one-function-per-module structure, with the modules named the same as the function. I want to expose all the functions in this library as attributes of the pfacets module. Currently, pfacets/__init__.py looks like this:

from func1 import func1 from func2 import func2 ... 

Is there a way to automate this so that I don't have to maintain this list? I tried:

for p in glob.glob(os.path.join(os.path.dirname(__file__), '*.py')): if not os.path.basename(p).startswith('__'): name = os.path.basename(x)[:-3] __import__(name, globals(), locals(), [name]) 

I was thinking that having name in the from-list (the 4th arg to __import__) would handle this, but it didn't work-- name was bound to the module, not the function.

4
  • Instead of if not p.startswith('__'): you should either have if not basename(p).startswith('__'): or at least if not p.endswith('__init__.py'):. This is because at that point you have the absolute path to your files and they won't start with '__' (even if they did, it's not what you mean :-)) Commented Jul 7, 2014 at 22:51
  • Why did you write your library this way, anyway? Are you used to a language that requires such a structure? (Matlab, maybe?) Putting all the functions in their own files just amplifies the I/O work needed to import your package. Commented Jul 7, 2014 at 22:59
  • @user2357112 I just prefer this structure. It's modeled on the facets library from Ruby. The way I edit, it is easier to navigate and keep track of. Also I can load individual functions if I need to. If many files has a big performance impact when importing the whole library, then I may change it. Commented Jul 7, 2014 at 23:13
  • @s16h That's correct, I accidentally posted a version of the code before I fixed that. The issue remains though. Commented Jul 7, 2014 at 23:13

1 Answer 1

1

Don't do that. Suppose a file gets deleted or renamed. If that happened, its function would never get imported and you wouldn't know until client code tries to reference it.

Remember the Zen of Python: "Explicit is better than implicit." Be explicit.

Sign up to request clarification or add additional context in comments.

2 Comments

What you say is true if a file is deleted-- not so if it's renamed. If a file were renamed, then the import code in my init.py would break, because the interior function will still have the old name, but the code would try to import the module name (and there would be no corresponding object). In any case, while your advice is noted, I am still looking for an answer to this question.
If it got renamed to something other than '*.py', it wouldn't.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.