glob.glob finds files whose names match
patterns
2023-*.{pdf,txt} matches 2023-01.txt
and 2023-final.pdf but not
draft-2023.docx
[% figure slug=“glob-examples” img=“examples.svg” alt=“Matching examples” caption=“Examples of glob matching.” %]
Early versions of Unix had a tool called
glob
People used pattern matching so often that it was quickly built into the shell
Create matchers for particular cases instead of one big function
Some of those matchers need extra data
So create objects
Use the [%g chain_of_responsibility_pattern “Chain of Responsibility” %] pattern
Each object matches if it can…
…then asks something else to try to match the rest of the text
[% figure slug=“glob-chain” img=“chain.svg” alt=“Chain of Responsibility” caption=“Matching with Chain of Responsibility.” %]
[%inc glob_lit.py %]
chars is the characters to be matchedrest is the rest of the chain (or
None)start is needed when this isn’t the first matcher[%inc test_glob_lit.py mark=tests %]
Try to find flaws in the design as early as possible
So test chaining before writing more matchers
[%inc test_glob_lit.py mark=chain %]
Some people write tests before writing code to clarify the design
Research shows the order doesn’t matter [%b Fucci2016 %]
What does is alternating between short bursts of coding and testing
* can match zero or more characters
If it’s the last matcher, it always succeeds
Otherwise try zero characters, one, two, etc. characters
[%inc glob_any.py %]
[%inc test_glob_any.py mark=tests %]
[%inc glob_either.py %]
[%inc test_glob_either.py mark=tests %]
[%inc test_glob_problem.py mark=keep %] [%inc test_glob_problem.out %]
Either doesn’t handle rest properlyif self.rest is None appears several times
[% figure slug=“glob-refactoring” img=“refactoring.svg” alt=“Refactoring matchers” caption=“Using the Extract Parent Class refactoring.” %]
[%inc glob_null.py mark=parent %]
Assume every child class has a _match
method
This method returns the location to continue searching
So Match.match checks that we’ve reached the end of
the text
[%inc glob_null.py mark=null %]
Must be the last one in the chain
Doesn’t advance the match (i.e., does nothing)
Every other class can now delegate to its next
without checking for None
[%inc glob_null.py mark=lit %]
None for “no match” or whatever
self.rest returns
rest is Null, result will be the index
after this object’s match[%inc glob_null.py mark=any %]
len(text) + 1?”[%inc glob_null.py mark=either %]
Looping over left and right options is simpler than repeating code or writing a helper method
Could easily be extended to any number of alternatives
matchNull[% figure slug=“glob-concept-map” img=“concept_map.svg” alt=“Concept map of globbing” caption=“Concept map.” %]