Pattern resolver
pattern_resolver
#
MissingPlaceholderValueError
#
Bases: imgtools.pattern_parser.pattern_resolver.PatternResolverError
Raised when a required placeholder value is missing in the context.
Source code in src/imgtools/pattern_parser/pattern_resolver.py
PatternResolver
dataclass
#
Handles parsing and validating filename patterns.
By default, this class uses the following pattern parser:
DEFAULT_PATTERN: re.Pattern = re.compile( ... r"%(\w+)|{(\w+)}" ... )
This will match placeholders of the form {key}
or %(key)s
.
Example
Given a filename format like "{subject_id}_{date}/{disease}.txt"
, the pattern parser
will extract the following keys:
pattern_resolver.keys
And the following formatted pattern:
pattern_resolver.formatted_pattern %(subject_id)s_%(date)s/%(disease)s.txt
So you could resolve the pattern like this:
data_dict = { ... "subject_id": "JohnDoe", ... "date": "January-01-2025", ... "disease": "cancer", ... }
pattern_resolver.formatted_pattern % data_dict 'JohnDoe_01-01-2025/cancer.txt'
A more convenient way to resolve the pattern is to use the resolve
method:
pattern_resolver.resolve(data_dict)) 'JohnDoe_01-01-2025/cancer.txt'
Methods:
Name | Description |
---|---|
parse |
Parse and validate the pattern. |
resolve |
Resolve the pattern using the provided context dictionary. |
Source code in src/imgtools/pattern_parser/pattern_resolver.py
parse
#
Parse and validate the pattern.
Returns:
Type | Description |
---|---|
typing.Tuple[str, List[str]]
|
The formatted pattern string and a list of extracted keys. |
Source code in src/imgtools/pattern_parser/pattern_resolver.py
resolve
#
resolve(context: typing.Dict[str, typing.Any]) -> str
Resolve the pattern using the provided context dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
typing.Dict[str, typing.Any]
|
Dictionary containing key-value pairs to substitute in the pattern. |
required |
Returns:
Type | Description |
---|---|
str
|
The resolved pattern string with placeholders replaced by values. |
Source code in src/imgtools/pattern_parser/pattern_resolver.py
PatternResolverError
#
Bases: Exception
Base exception for errors in pattern resolution.