Please forgive my ignorance but forever I've been in the habit of building a library of useful subroutines which I call from an application I am building.

Recently the language has been python - a distinct departure from my experience. I've been unable to create a reasonable library. Here's the tree (an example)

mkfs a directory
subs a directory in which I keep my subroutines
__init__.py a file I got from DiveIntoPython
file1.py contains subroutine sub1
file2.py contains subroutine sub2
app.py needs to call sub1 and sub2

The only way I can make this work is
in __init__.py to import file1 and file 2 and
in app to import sub1 from subs and
when I want to call sub1, I have to subs.file1.sub1()


Surely there must be a better way. Perhaps a Pythonic way that has escaped me so far?

Help, please?

Purgatoryred, whose education is composed largely of assembly language where the forgoing would have been trivial.

You could put this in __init__.py

# __init__.py
def _load():
    from glob import glob
    from os.path import join, dirname, splitext, basename

    for path in glob(join(dirname(__file__),'[!_]*.py')):
        name = splitext(basename(path))[0]
        exec "from %s import *" % name in globals()
_load()

Note that all the submodules will be loaded when you load subs. Also you should put a __all__ variable in your submodules to import only the names you need. For example

# file1.py
__all__ = ["useful_function",] # list of functions to export

def useful_function():
    pass

def helper_function(): # not in __all__ --> not exported
    pass

Also, a simpler solution is to write

# app.py
from subs.file1 import func1
func1()

With the above code, you can write

# app.py
from subs import func1
func1()

Should have told you, I'm using python3. Had to change a few things. No sweat. But I could not figure out what you intended with "name in globals()" in the exec statement.

Tried to wire some stuff just to see if I could get anything to work. Not much luck. I'll continue on Monday.

Still, I thank you for your thoughtful reply.

Solved. In the end the trouble evolved from the dichotomy between decades of assembly language and this new, much higher level, stuff.

Tks for the assistance.

Purgatoryred

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.