> built 2026-09-22 14:40 UTC from 722de15 (master) · focal 0.1.13. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# focal

Data Access Objects for local files.

# Examples

## quick store

```pydocstring
>>> from py2store import QuickStore
>>>
>>> store = QuickStore()  # will print what (tmp) rootdir it is choosing
>>> # Write something and then read it out again
>>> store['foo'] = 'baz'
>>> 'foo' in store  # do you have the key 'foo' in your store?
True
>>> store['foo']  # what is the value for 'foo'?
'baz'
>>>
>>> # Okay, it behaves like a dict, but go have a look in your file system,  
>>> # and see that there is now a file in the rootdir, named 'foo'!
>>> 
>>> # Write something more complicated
>>> store['hello/world'] = [1, 'flew', {'over': 'a', "cuckoo's": map}]
>>> stored_val = store['hello/world']
>>> stored_val == [1, 'flew', {'over': 'a', "cuckoo's": map}]  # was it retrieved correctly?
True
>>>
>>> # how many items do you have now?
>>> assert len(store) >= 2  # can't be sure there were no elements before, so can't assert == 2
>>> 
>>> # delete the stuff you've written
>>> del store['foo']
>>> del store['hello/world']
```

## iterate over files

```pydocstring
>>> import os
>>> filepath = __file__  # path to this module
>>> dirpath = os.path.dirname(__file__)  # path of the directory where I (the module file) am
>>> s = FileCollection(dirpath, max_levels=0)
>>>
>>> files_in_this_dir = list(s)
>>> filepath in files_in_this_dir
True
```

## bytes contents of the file

```pydocstring
>>> import os
>>> filepath = __file__
>>> dirpath = os.path.dirname(__file__)  # path of the directory where I (the module file) am
>>> s = FileBytesReader(dirpath, max_levels=0)
>>>
>>> ####### Get the first 9 characters (as bytes) of this module #####################
>>> s[filepath][:9]
b'import os'
>>>
>>> ####### Test key validation #####################
>>> s['not_a_valid_key']  # this key is not valid since not under the dirpath folder
Traceback (most recent call last):
    ...
filesys.KeyValidationError: 'Key not valid (usually because does not exist or access not permitted): not_a_valid_key'
>>>
>>> ####### Test further exceptions (that should be wrapped in KeyError) #####################
>>> # this key is valid, since under dirpath, but the file itself doesn't exist (hopefully for this test)
>>> non_existing_file = os.path.join(dirpath, 'non_existing_file')
>>> try:
...     s[non_existing_file]
... except KeyError:
...     print("KeyError (not FileNotFoundError) was raised.")
KeyError (not FileNotFoundError) was raised.
```

<p class="epythet-aggregates">This documentation as a single file: <a href="focal.md">focal.md</a> (Markdown, for agents).</p>


# _autosummary/focal.extension_store.html.md

# focal.extension_store

Stores that are extension-aware when reading and writing.

Make a temporary folder

```pycon
>>> import tempfile
>>> temp_dir = tempfile.TemporaryDirectory()
```

Check that it is empty for now

```pycon
>>> from os import  listdir
>>> listdir(temp_dir.name)
[]
```

Instantiate a store, persisting in our local temporary folder

```pycon
>>> d = MultiFileStore(temp_dir.name)
```

Here are a few objects to save into our folder:

```pycon
>>> my_jdict = {'a': 1, 'b': [1, 2, 3], 'c': 'string'}
>>> my_string = 'test_string'
```

Now we can save each of these in a relevant format:

```pycon
>>> d['my_jdict.json'] = my_jdict
>>> d['my_string.txt'] = my_string
```

Our folder now contains those∑ files

```pycon
>>> assert set(listdir(temp_dir.name)) == {'my_jdict.json', 'my_string.txt'}
```

We can retrieve each one of those files and check that the python objects are equal to the originals

```pycon
>>> assert d['my_jdict.json'] == my_jdict
>>> assert d['my_string.txt'] == my_string
```

Finally, we clean up the temporary folder

```pycon
>>> temp_dir.cleanup()
```

### Functions

| `get_extension`(k)                                |    |
|---------------------------------------------------|----|
| `make_conversion_for_obj`(k, v, ...[, func_type]) |    |

### Classes

| [`LocalBinaryStore`](_autosummary/focal.extension_store.html.md#focal.extension_store.LocalBinaryStore)(path_format[, max_levels])   |    |
|------------------------------------------------------------------------------------------------|----|
| [`MultiFileStore`](_autosummary/focal.extension_store.html.md#focal.extension_store.MultiFileStore)                                |    |

### *class* focal.extension_store.LocalBinaryStore(path_format, max_levels=None)

Bases: `Files`

### focal.extension_store.MultiFileStore

alias of [`LocalBinaryStore`](_autosummary/focal.extension_store.html.md#focal.extension_store.LocalBinaryStore)

### focal.extension_store.string_to_bytes(self, , encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding
: The encoding in which to encode the string.

errors
: The error handling scheme to use for encoding errors.
  The default is ‘strict’ meaning that encoding errors raise a
  UnicodeEncodeError.  Other possible values are ‘ignore’, ‘replace’ and
  ‘xmlcharrefreplace’ as well as any other name registered with
  codecs.register_error that can handle UnicodeEncodeErrors.

### focal.extension_store.text_byte_to_string(self, , encoding='utf-8', errors='strict')

Decode the bytes using the codec registered for encoding.

encoding
: The encoding with which to decode the bytes.

errors
: The error handling scheme to use for the handling of decoding errors.
  The default is ‘strict’ meaning that decoding errors raise a
  UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’
  as well as any other name registered with codecs.register_error that
  can handle UnicodeDecodeErrors.


# _autosummary/focal.html.md

# focal

Data Object Layers for local files

### Modules

| [`extension_store`](_autosummary/focal.extension_store.html.md#module-focal.extension_store)   | Stores that are extension-aware when reading and writing.                                    |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|
| [`parse_format`](_autosummary/focal.parse_format.html.md#module-focal.parse_format)         | Modified from [https://github.com/r1chardj0n3s/parse](https://github.com/r1chardj0n3s/parse) |


# _autosummary/focal.parse_format.html.md

# focal.parse_format

Modified from [https://github.com/r1chardj0n3s/parse](https://github.com/r1chardj0n3s/parse)

Parse strings using a specification based on the Python format() syntax.

> `parse()` is the opposite of `format()`

From there it’s a simple thing to parse a string:

```pycon
>>> parse("It's {}, I love it!", "It's spam, I love it!")
<Result ('spam',) {}>
>>> _[0]
'spam'
```

Or to search a string for some pattern:

```pycon
>>> search('Age: {:d}\n', 'Name: Rufus\nAge: 42\nColor: red\n')
<Result (42,) {}>
```

Or find all the occurrences of some pattern in a string:

```pycon
>>> ''.join(r.fixed[0] for r in findall(">{}<", "<p>the <b>bold</b> text</p>"))
'the bold text'
```

If you’re going to use the same pattern to match lots of strings you can
compile it once:

```pycon
>>> p = compile("It's {}, I love it!")
>>> print(p)
<Parser "It's {}, I love it!">
>>> p.parse("It's spam, I love it!")
<Result ('spam',) {}>
```

(“compile” is not exported for `import *` usage as it would override the
built-in `compile()` function)

The default behaviour is to match strings case insensitively. You may match with
case by specifying `case_sensitive=True`:

```pycon
>>> parse('SPAM', 'spam', case_sensitive=True) is None
True
```

## Format Syntax

A basic version of the 

```
`Format String Syntax`_
```

 is supported with anonymous
(fixed-position), named and formatted fields:

```default
{[field name]:[format spec]}
```

Field names must be a valid Python identifiers, including dotted names;
element indexes imply dictionaries (see below for example).

Numbered fields are also not supported: the result of parsing will include
the parsed fields in the order they are parsed.

The conversion of fields to types other than strings is done based on the
type in the format specification, which mirrors the `format()` behaviour.
There are no “!” field conversions like `format()` has.

Some simple parse() format string examples:

```pycon
>>> parse("Bring me a {}", "Bring me a shrubbery")
<Result ('shrubbery',) {}>
>>> r = parse("The {} who say {}", "The knights who say Ni!")
>>> print(r)
<Result ('knights', 'Ni!') {}>
>>> print(r.fixed)
('knights', 'Ni!')
>>> r = parse("Bring out the holy {item}", "Bring out the holy hand grenade")
>>> print(r)
<Result () {'item': 'hand grenade'}>
>>> print(r.named)
{'item': 'hand grenade'}
>>> print(r['item'])
hand grenade
```

Dotted names and indexes are possible though the application must make
additional sense of the result:

```pycon
>>> r = parse("Mmm, {food.type}, I love it!", "Mmm, spam, I love it!")
>>> print(r)
<Result () {'food.type': 'spam'}>
>>> print(r.named)
{'food.type': 'spam'}
>>> print(r['food.type'])
spam
>>> r = parse("My quest is {quest[name]}", "My quest is to seek the holy grail!")
>>> print(r)
<Result () {'quest': {'name': 'to seek the holy grail!'}}>
>>> print(r['quest'])
{'name': 'to seek the holy grail!'}
>>> print(r['quest']['name'])
to seek the holy grail!
```

If the text you’re matching has braces in it you can match those by including
a double-brace `{{` or `}}` in your format string, just like format() does.

## Format Specification

Most often a straight format-less `{}` will suffice where a more complex
format specification might have been used.

Most of `format()`’s 

```
`Format Specification Mini-Language`_
```

 is supported:

> [[fill]align][0][width][.precision][type]

The differences between `parse()` and `format()` are:

- The align operators will cause spaces (or specified fill character) to be
  stripped from the parsed value. The width is not enforced; it just indicates
  there may be whitespace or “0”s to strip.
- Numeric parsing will automatically handle a “0b”, “0o” or “0x” prefix.
  That is, the “#” format character is handled automatically by d, b, o
  and x formats. For “d” any will be accepted, but for the others the correct
  prefix must be present if at all.
- Numeric sign is handled automatically.
- The thousands separator is handled automatically if the “n” type is used.
- The types supported are a slightly different mix to the format() types.  Some
  format() types come directly over: “d”, “n”, “%”, “f”, “e”, “b”, “o” and “x”.
  In addition some regular expression character group types “D”, “w”, “W”, “s”
  and “S” are also available.
- The “e” and “g” types are case-insensitive so there is not need for
  the “E” or “G” types.

| Type   | Characters Matched                                                                 | Output   |
|--------|------------------------------------------------------------------------------------|----------|
| w      | Letters and underscore                                                             | str      |
| W      | Non-letter and underscore                                                          | str      |
| s      | Whitespace                                                                         | str      |
| S      | Non-whitespace                                                                     | str      |
| d      | Digits (effectively integer numbers)                                               | int      |
| D      | Non-digit                                                                          | str      |
| n      | Numbers with thousands separators (, or .)                                         | int      |
| %      | Percentage (converted to value/100.0)                                              | float    |
| f      | Fixed-point numbers                                                                | float    |
| F      | Decimal numbers                                                                    | Decimal  |
| e      | Floating-point numbers with exponent<br/>e.g. 1.1e-10, NAN (all case insensitive)  | float    |
| g      | General number format (either d, f or e)                                           | float    |
| b      | Binary numbers                                                                     | int      |
| o      | Octal numbers                                                                      | int      |
| x      | Hexadecimal numbers (lower and upper case)                                         | int      |
| ti     | ISO 8601 format date/time<br/>e.g. 1972-01-20T10:21:36Z (“T” and “Z”<br/>optional) | datetime |
| te     | RFC2822 e-mail format date/time<br/>e.g. Mon, 20 Jan 1972 10:21:36 +1000           | datetime |
| tg     | Global (day/month) format date/time<br/>e.g. 20/1/1972 10:21:36 AM +1:00           | datetime |
| ta     | US (month/day) format date/time<br/>e.g. 1/20/1972 10:21:36 PM +10:30              | datetime |
| tc     | ctime() format date/time<br/>e.g. Sun Sep 16 01:03:52 1973                         | datetime |
| th     | HTTP log format date/time<br/>e.g. 21/Nov/2011:00:07:11 +0000                      | datetime |
| ts     | Linux system log format date/time<br/>e.g. Nov  9 03:37:44                         | datetime |
| tt     | Time<br/>e.g. 10:21:36 PM -5:30                                                    | time     |

Some examples of typed parsing with `None` returned if the typing
does not match:

```pycon
>>> parse('Our {:d} {:w} are...', 'Our 3 weapons are...')
<Result (3, 'weapons') {}>
>>> parse('Our {:d} {:w} are...', 'Our three weapons are...')
>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')
<Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>
```

And messing about with alignment:

```pycon
>>> parse('with {:>} herring', 'with     a herring')
<Result ('a',) {}>
>>> parse('spam {:^} spam', 'spam    lovely     spam')
<Result ('lovely',) {}>
```

Note that the “center” alignment does not test to make sure the value is
centered - it just strips leading and trailing whitespace.

Width and precision may be used to restrict the size of matched text
from the input. Width specifies a minimum size and precision specifies
a maximum. For example:

```pycon
>>> parse('{:.2}{:.2}', 'look')           # specifying precision
<Result ('lo', 'ok') {}>
>>> parse('{:4}{:4}', 'look at that')     # specifying width
<Result ('look', 'at that') {}>
>>> parse('{:4}{:.4}', 'look at that')    # specifying both
<Result ('look at ', 'that') {}>
>>> parse('{:2d}{:2d}', '0440')           # parsing two contiguous numbers
<Result (4, 40) {}>
```

Some notes for the date and time types:

- the presence of the time part is optional (including ISO 8601, starting
  at the “T”). A full datetime object will always be returned; the time
  will be set to 00:00:00. You may also specify a time without seconds.
- when a seconds amount is present in the input fractions will be parsed
  to give microseconds.
- except in ISO 8601 the day and month digits may be 0-padded.
- the date separator for the tg and ta formats may be “-” or “/”.
- named months (abbreviations or full names) may be used in the ta and tg
  formats in place of numeric months.
- as per RFC 2822 the e-mail format may omit the day (and comma), and the
  seconds but nothing else.
- hours greater than 12 will be happily accepted.
- the AM/PM are optional, and if PM is found then 12 hours will be added
  to the datetime object’s hours amount - even if the hour is greater
  than 12 (for consistency.)
- in ISO 8601 the “Z” (UTC) timezone part may be a numeric offset
- timezones are specified as “+HH:MM” or “-HH:MM”. The hour may be one or two
  digits (0-padded is OK.) Also, the “:” is optional.
- the timezone is optional in all except the e-mail format (it defaults to
  UTC.)
- named timezones are not handled yet.

#### NOTE
attempting to match too many datetime fields in a single parse() will
currently result in a resource allocation issue. A TooManyFields exception
will be raised in this instance. The current limit is about 15. It is hoped
that this limit will be removed one day.

<!-- _`Format String Syntax`::

http://docs.python.org/library/string.html#format-string-syntax -->
<!-- _`Format Specification Mini-Language`::

http://docs.python.org/library/string.html#format-specification-mini-language -->

## Result and Match Objects

The result of a `parse()` and `search()` operation is either `None` (no match), a
`Result` instance or a `Match` instance if `evaluate_result` is False.

The `Result` instance has three attributes:

fixed
: A tuple of the fixed-position, anonymous fields extracted from the input.

named
: A dictionary of the named fields extracted from the input.

spans
: A dictionary mapping the names and fixed position indices matched to a
  2-tuple slice range of where the match occurred in the input.
  The span does not include any stripped padding (alignment or width).

The `Match` instance has one method:

evaluate_result()
: Generates and returns a `Result` instance for this `Match` object.

## Custom Type Conversions

If you wish to have matched fields automatically converted to your own type you
may pass in a dictionary of type conversion information to `parse()` and
`compile()`.

The converter will be passed the field string matched. Whatever it returns
will be substituted in the `Result` instance for that field.

Your custom type conversions may override the builtin types if you supply one
with the same identifier.

```pycon
>>> def shouty(string):
...    return string.upper()
...
>>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))
<Result ('HELLO',) {}>
```

If the type converter has the optional `pattern` attribute, it is used as
regular expression for better pattern matching (instead of the default one).

```pycon
>>> def parse_number(text):
...    return int(text)
>>> parse_number.pattern = r'\d+'
>>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
<Result () {'number': 42}>
>>> _ = parse('Answer: {:Number}', 'Answer: Alice', dict(Number=parse_number))
>>> assert _ is None, "MISMATCH"
```

You can also use the `with_pattern(pattern)` decorator to add this
information to a type converter function:

```pycon
>>> @with_pattern(r'\d+')
... def parse_number(text):
...    return int(text)
>>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
<Result () {'number': 42}>
```

A more complete example of a custom type might be:

```pycon
>>> yesno_mapping = {
...     "yes":  True,   "no":    False,
...     "on":   True,   "off":   False,
...     "true": True,   "false": False,
... }
>>> @with_pattern(r"|".join(yesno_mapping))
... def parse_yesno(text):
...     return yesno_mapping[text.lower()]
```

If the type converter `pattern` uses regex-grouping (with parenthesis),
you should indicate this by using the optional `regex_group_count` parameter
in the `with_pattern()` decorator:

```pycon
>>> @with_pattern(r'((\d+))', regex_group_count=2)
... def parse_number2(text):
...    return int(text)
>>> parse('Answer: {:Number2} {:Number2}', 'Answer: 42 43', dict(Number2=parse_number2))
<Result (42, 43) {}>
```

Otherwise, this may cause parsing problems with unnamed/fixed parameters.

## Potential Gotchas

`parse()` will always match the shortest text necessary (from left to right)
to fulfil the parse pattern, so for example:

```pycon
>>> pattern = '{dir1}/{dir2}'
>>> data = 'root/parent/subdir'
>>> sorted(parse(pattern, data).named.items())
[('dir1', 'root'), ('dir2', 'parent/subdir')]
```

So, even though `{'dir1': 'root/parent', 'dir2': 'subdir'}` would also fit
the pattern, the actual match represents the shortest successful match for
`dir1`.

---

**Version history (in brief)**:

- 1.9.0 We now honor precision and width specifiers when parsing numbers
  and strings, allowing parsing of concatenated elements of fixed width
  (thanks Julia Signell)
- 1.8.4 Add LICENSE file at request of packagers.
  Correct handling of AM/PM to follow most common interpretation.
  Correct parsing of hexadecimal that looks like a binary prefix.
  Add ability to parse case sensitively.
  Add parsing of numbers to Decimal with “F” (thanks John Vandenberg)
- 1.8.3 Add regex_group_count to with_pattern() decorator to support
  user-defined types that contain brackets/parenthesis (thanks Jens Engel)
- 1.8.2 add documentation for including braces in format string
- 1.8.1 ensure bare hexadecimal digits are not matched
- 1.8.0 support manual control over result evaluation (thanks Timo Furrer)
- 1.7.0 parse dict fields (thanks Mark Visser) and adapted to allow
  more than 100 re groups in Python 3.5+ (thanks David King)
- 1.6.6 parse Linux system log dates (thanks Alex Cowan)
- 1.6.5 handle precision in float format (thanks Levi Kilcher)
- 1.6.4 handle pipe “|” characters in parse string (thanks Martijn Pieters)
- 1.6.3 handle repeated instances of named fields, fix bug in PM time
  overflow
- 1.6.2 fix logging to use local, not root logger (thanks Necku)
- 1.6.1 be more flexible regarding matched ISO datetimes and timezones in
  general, fix bug in timezones without “:” and improve docs
- 1.6.0 add support for optional `pattern` attribute in user-defined types
  (thanks Jens Engel)
- 1.5.3 fix handling of question marks
- 1.5.2 fix type conversion error with dotted names (thanks Sebastian Thiel)
- 1.5.1 implement handling of named datetime fields
- 1.5 add handling of dotted field names (thanks Sebastian Thiel)
- 1.4.1 fix parsing of “0” in int conversion (thanks James Rowe)
- 1.4 add \_\_getitem_\_ convenience access on Result.
- 1.3.3 fix Python 2.5 setup.py issue.
- 1.3.2 fix Python 3.2 setup.py issue.
- 1.3.1 fix a couple of Python 3.2 compatibility issues.
- 1.3 added search() and findall(); removed compile() from `import *`
  export as it overwrites builtin.
- 1.2 added ability for custom and override type conversions to be
  provided; some cleanup
- 1.1.9 to keep things simpler number sign is handled automatically;
  significant robustification in the face of edge-case input.
- 1.1.8 allow “d” fields to have number base “0x” etc. prefixes;
  fix up some field type interactions after stress-testing the parser;
  implement “%” type.
- 1.1.7 Python 3 compatibility tweaks (2.5 to 2.7 and 3.2 are supported).
- 1.1.6 add “e” and “g” field types; removed redundant “h” and “X”;
  removed need for explicit “#”.
- 1.1.5 accept textual dates in more places; Result now holds match span
  positions.
- 1.1.4 fixes to some int type conversion; implemented “=” alignment; added
  date/time parsing with a variety of formats handled.
- 1.1.3 type conversion is automatic based on specified field types. Also added
  “f” and “n” types.
- 1.1.2 refactored, added compile() and limited `from parse import *`
- 1.1.1 documentation improvements
- 1.1.0 implemented more of the 

  ```
  `Format Specification Mini-Language`_
  ```


  and removed the restriction on mixing fixed-position and named fields
- 1.0.0 initial release

This code is copyright 2012-2017 Richard Jones <[richard@python.org](mailto:richard@python.org)>
See the end of the source file for the license of use.

### Functions

| [`parse`](_autosummary/focal.parse_format.html.md#focal.parse_format.parse)(format, string[, extra_types, ...])   | Using "format" attempt to pull values from "string".                             |
|----------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`search`](_autosummary/focal.parse_format.html.md#focal.parse_format.search)(format, string[, pos, endpos, ...])  | Search "string" for the first occurrence of "format".                            |
| [`findall`](_autosummary/focal.parse_format.html.md#focal.parse_format.findall)(format, string[, pos, endpos, ...]) | Search "string" for all occurrences of "format".                                 |
| [`with_pattern`](_autosummary/focal.parse_format.html.md#focal.parse_format.with_pattern)(pattern[, regex_group_count])  | Attach a regular expression pattern matcher to a custom type converter function. |

### focal.parse_format.findall(format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True, case_sensitive=False)

Search “string” for all occurrences of “format”.

You will be returned an iterator that holds Result instances
for each format match found.

Optionally start the search at “pos” character index and limit the search
to a maximum index of endpos - equivalent to search(string[:endpos]).

If `evaluate_result` is True each returned Result instance has two attributes:

> .fixed - tuple of fixed-position values from the string
> .named - dict of named values from the string

If `evaluate_result` is False each returned value is a Match instance with one method:

> .evaluate_result() - This will return a Result instance like you would get
> : with `evaluate_result` set to True

The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.

If the format is invalid a ValueError will be raised.

See the module documentation for the use of “extra_types”.

### focal.parse_format.parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False)

Using “format” attempt to pull values from “string”.

The format must match the string contents exactly. If the value
you’re looking for is instead just a part of the string use
search().

If `evaluate_result` is True the return value will be an Result instance with two attributes:

> .fixed - tuple of fixed-position values from the string
> .named - dict of named values from the string

If `evaluate_result` is False the return value will be a Match instance with one method:

> .evaluate_result() - This will return a Result instance like you would get
> : with `evaluate_result` set to True

The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.

If the format is invalid a ValueError will be raised.

See the module documentation for the use of “extra_types”.

In the case there is no match parse() will return None.

### focal.parse_format.search(format, string, pos=0, endpos=None, extra_types=None, evaluate_result=True, case_sensitive=False)

Search “string” for the first occurrence of “format”.

The format may occur anywhere within the string. If
instead you wish for the format to exactly match the string
use parse().

Optionally start the search at “pos” character index and limit the search
to a maximum index of endpos - equivalent to search(string[:endpos]).

If `evaluate_result` is True the return value will be an Result instance with two attributes:

> .fixed - tuple of fixed-position values from the string
> .named - dict of named values from the string

If `evaluate_result` is False the return value will be a Match instance with one method:

> .evaluate_result() - This will return a Result instance like you would get
> : with `evaluate_result` set to True

The default behaviour is to match strings case insensitively. You may match with
case by specifying case_sensitive=True.

If the format is invalid a ValueError will be raised.

See the module documentation for the use of “extra_types”.

In the case there is no match parse() will return None.

### focal.parse_format.with_pattern(pattern, regex_group_count=None)

Attach a regular expression pattern matcher to a custom type converter
function.

This annotates the type converter with the `pattern` attribute.

### Example

```pycon
>>> @with_pattern(r"\d+")
... def parse_number(text):
...     return int(text)
```

is equivalent to:

```pycon
>>> def parse_number(text):
...     return int(text)
>>> parse_number.pattern = r"\d+"
```

* **Parameters:**
  * **pattern** – regular expression pattern (as text)
  * **regex_group_count** – Indicates how many regex-groups are in pattern.
* **Returns:**
  wrapped function


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-09-22 14:40 UTC** from commit <a href="https://github.com/i2mint/focal/commit/722de15b907f616208f6a5f28fa0c796e516e3c2"><code>722de15</code></a> on branch <code>master</code>, for **focal 0.1.13** (from <code>pyproject.toml</code>).

#### WARNING
The documentation and the package may be misaligned:

- The documented version (0.1.13) is behind the latest release on PyPI (0.1.14): `pip install focal` gives newer code than these docs describe.

## Source

|                     |                                                                                                                                                     |
|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/i2mint/focal/commit/722de15b907f616208f6a5f28fa0c796e516e3c2"><code>722de15b907f616208f6a5f28fa0c796e516e3c2</code></a> |
| Branch              | <code>master</code>                                                                                                                                 |
| Tags at this commit | none                                                                                                                                                |
| Working tree        | clean                                                                                                                                               |
| Remote              | <code>https://github.com/i2mint/focal</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>i2mint/focal</code>                                                                  |
| Run          | <a href="https://github.com/i2mint/focal/actions/runs/35740451345">35740451345</a>         |
| Ref          | <code>refs/heads/master</code>                                                             |
| Event commit | <code>722de15b907f616208f6a5f28fa0c796e516e3c2</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.12  |
| Sphinx   | 9.1.0   |
| docutils | 0.22.4  |
| Python   | 3.12.14 |

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>shibuya</code>)            |
| accent        | <code>#5f4598</code>                                             |
| api_generator | <code>autosummary</code>                                         |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code> |
| agent_outputs | <code>true</code>                                                |
| aggregates    | <code>md</code>                                                  |
| ai_artifacts  | <code>true</code>                                                |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/focal/0.1.14/">0.1.14</a>, newer than the documented version (0.1.13).

## Reproduce

```bash
git clone https://github.com/i2mint/focal && cd focal
git checkout 722de15b907f616208f6a5f28fa0c796e516e3c2
pip install "epythet==0.2.12"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# api.html.md

# API reference

| [`focal`](_autosummary/focal.html.md#module-focal)   | Data Object Layers for local files   |
|-----------------------------------------------------------------------|--------------------------------------|


