[Tutor] question about glob.glob() implementation

Bruce Sass bsass@freenet.edmonton.ab.ca
Fri, 16 Feb 2001 01:19:31 -0700 (MST)

On Thu, 15 Feb 2001, Sean 'Shaleh' Perry wrote:

> glob.glob() has a section like:
> if not has_magic(basename):
>         result = []
>         for dirname in list:
>             if basename or os.path.isdir(dirname):
>                 name = os.path.join(dirname, basename)
>                 if os.path.exists(name):
>                     result.append(name)
> else:
> For every iteration of the for loop, basename is tested, yet its value never
> changes.  Am I missing something here or is this wasteful like i think it is?

Hmmm, it looks like a dual purpose routine.  If basename is an empty
string, result ends up with the paths to the dirs in list that exist
(i.e., where can I look?).  If basename has a value, result ends up
with the paths that end in basename (i.e., is it there?).

I think you're missing the logic of the for loop. If basename is
"true", the action is always performed on dirname; if it is "false",
the action is only performed when dirname is a dir.  If dirname is a
dir, the action is always performed; if dirname is not a dir the
action is performed if basename is true. Since neither basename or
os.path.isdir(dirname) alone can determine what to do it is necessary
to test both for each value taken on by dirname.  Check out the truth
table; b is the basename term, d is the os.path.isdir(dirname) term,
action is what happens.

b d action
- - ------
0 0 skip
0 1 do
1 0 do
1 1 do

Since it can't be simplified, both terms are necessary.

- Bruce