---
title: Utility functions
description: Utility functions used in the fastai library
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

`doc(fastcore.xtras)` shows an overview instead of listing every symbol.

## File Functions

IO utilities include:

- [`maybe_open`](xtras.md#maybe_open): accept a path or an open file, closing only files it opens.
- [`run`](xtras.md#run): run a command and return stdout; raise `IOError` on failure.
- [`atomic_save`](xtras.md#atomic_save): write a temporary file, then rename it over the destination.
- [`untar_dir`](xtras.md#untar_dir): extract an archive, creating a containing directory when needed.
- [`globtastic`](xtras.md#globtastic): recursively find files with include and exclude filters.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L84)

### walk\_join

```python
def walk_join(
    root, name
):
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L87)

### walk

```python
def walk(
    path:pathlib._local.Path | str, # path to start searching
    symlinks:bool=True, # follow symlinks?
    keep_file:<built-in function callable>=ret_true, # function that returns True for wanted files
    keep_folder:<built-in function callable>=ret_true, # function that returns True for folders to enter
    skip_folder:<built-in function callable>=ret_false, # function that returns True for folders to skip
    func:<built-in function callable>=walk_join, # function applied to each entry; default adds `/` to folders
    ret_folders:bool=False, # include folder entries inline with files?
    sort:bool=True, # sort entries alphabetically within each folder?
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
):
```

*Generator: yields files and (optionally) folders as unified, inline-sorted entries*

[`walk`](xtras.md#walk) yields matching paths inline-sorted across folders; pass `ret_folders=True` to include directory entries (with a trailing `/` from [`walk_join`](xtras.md#walk_join)) and `maxdepth=1` to stop at immediate children:

```python
entries = list(walk('images', maxdepth=1))
assert any(Path(o).name == 'puppy.jpg' for o in entries)
top = list(walk('.', maxdepth=1, ret_folders=True, keep_folder=lambda r,n: n=='images', keep_file=ret_false))
test_eq([Path(o).name for o in top], ['images'])
assert top[0].endswith('/')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L126)

### exttypes

```python
def exttypes(
    types
):
```

*Get exts for comma-separated or list `typ`; if not found in list, return list with just `types`. Supported: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg*

[`exttypes`](xtras.md#exttypes) expands shorthand group names (such as `'py'` or `'doc'`) into file extensions, passing unknown names through unchanged:

```python
print(exttypes('py,doc'))
print(exttypes('zig,txt'))
```

```output
['ipynb', 'py', 'md', 'rst']
['zig', 'txt']
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L132)

### globtastic

```python
def globtastic(
    path:pathlib._local.Path | str='.', # path to start searching
    recursive:bool=True, # search subfolders
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
    symlinks:bool=True, # follow symlinks?
    file_glob:str=None, # Only include files matching glob
    file_re:str=None, # Only include files matching regex
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    skip_file_re:str=None, # Skip files matching regex
    skip_folder_re:str=None, # Skip folders matching regex,
    func:<built-in function callable>=walk_join, # function to apply to each matched file
    ret_folders:bool=False, # return folders, not just files
    sort:bool=True, # sort files by name within each folder
    types:str | list=None, # list or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
    exts:str | list=None, # list or comma-separated str of exts to include
)->fastcore.foundation.L: # Paths to matched files
```

*A more powerful `glob`, including regex matches, symlink handling, and skip parameters*

`path` is the directory to search. `file_glob` and `file_re` match filenames. `path_glob` and `path_re` match each file's full path, including the search directory. These filters do not control directory traversal. `path_glob` uses `fnmatch`: `*` matches directory separators and `**` has no special meaning.

```python
globtastic('.', skip_folder_re='^[_.]', folder_re='core', file_glob='*.*py*', file_re='c')
```

```output
['./01_basics.ipynb', './03c_aio.ipynb', './04_docments.ipynb', './05a_apisurface.ipynb', './06_script.ipynb', './14_funccall.ipynb', './fastcore/apisurface.py', './fastcore/basics.py', './fastcore/dispatch.py', './fastcore/docments.py', './fastcore/docscrape.py', './fastcore/funccall.py', './fastcore/script.py']
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L178)

### pglob

```python
def pglob(
    path:pathlib._local.Path | str='.', # path to start searching
    func:<built-in function callable>=Path, # function to apply to each matched file
    *, recursive:bool=True, maxdepth:int=None, symlinks:bool=True, file_glob:str=None, file_re:str=None,
    path_glob:str=None, path_re:str=None, folder_re:str=None, skip_file_glob:str=None, skip_file_re:str=None,
    skip_folder_re:str=None, ret_folders:bool=False, sort:bool=True, types:str | list=None, exts:str | list=None
)->fastcore.foundation.L: # Paths to matched files
```

*Shortcut for `globtastic(..., call=Path)`*

```python
pglob('..', skip_folder_re='^[_.]', types='doc', skip_file_re='^_')[:6]
```

```output
[Path('../CHANGELOG.md'), Path('../CODE_OF_CONDUCT.md'), Path('../CONTRIBUTING.md'), Path('../README.md')]
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L188)

### maybe\_open

```python
def maybe_open(
    f, mode:str='r', **kwargs
):
```

*Context manager: open `f` if it is a path (and close on exit)*

This is useful for functions where you want to accept a path *or* file. [`maybe_open`](xtras.md#maybe_open) will not close your file handle if you pass one in.

```python
def _f(fn):
    with maybe_open(fn) as f: return f.encoding

fname = '00_test.ipynb'
sys_encoding = 'cp1252' if sys.platform == 'win32' else 'utf-8'
test_eq(_f(fname).lower(), sys_encoding)
with open(fname) as fh: test_eq(_f(fh).lower(), sys_encoding)
```

For example, we can use this to reimplement [`imghdr.what`](https://docs.python.org/3/library/imghdr.html#imghdr.what) from the Python standard library, which is [written in Python 3.9](https://github.com/python/cpython/blob/3.9/Lib/imghdr.py#L11) as:

```python
from fastcore import imghdr
```

```python
def what(file, h=None):  # chkstyle: ignore
    f = None
    try:
        if h is None:
            if isinstance(file, (str,os.PathLike)):
                f = open(file, 'rb')
                h = f.read(32)
            else:
                location = file.tell()
                h = file.read(32)
                file.seek(location)
        for tf in imghdr.tests:
            res = tf(h, f)
            if res: return res
    finally:
        if f: f.close()
    return None
```

Here's an example of the use of this function:

```python
fname = 'images/puppy.jpg'
what(fname)
```

```output
'jpeg'
```

With [`maybe_open`](xtras.md#maybe_open), `Self`, and [`L.map_first`](foundation.md#l.map_first), we can rewrite this in a much more concise and (in our opinion) clear way:

```python
def what(file, h=None):
    if h is None:
        with maybe_open(file, 'rb') as f: h = f.peek(32)
    return L(imghdr.tests).map_first(~Self(h,file))
```

...and we can check that it still works:

```python
test_eq(what(fname), 'jpeg')
```

...along with the version passing a file handle:

```python
with open(fname,'rb') as f: test_eq(what(f), 'jpeg')
```

...along with the `h` parameter version:

```python
with open(fname,'rb') as f: test_eq(what(None, h=f.read(32)), 'jpeg')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L195)

### mkdir

```python
def mkdir(
    path, exist_ok:bool=False, parents:bool=False, overwrite:bool=False, **kwargs
):
```

*Creates and returns a directory defined by `path`, optionally removing previous existing directory if `overwrite` is `True`*

[`mkdir`](xtras.md#mkdir) creates a directory and returns it as a `Path`; pass `overwrite=True` to remove an existing directory first:

```python
with tempfile.TemporaryDirectory() as d:
    path = Path(os.path.join(d, 'new_dir'))
    new_dir = mkdir(path)
    assert new_dir.exists()
    test_eq(new_dir, path)
    with open(new_dir/'test.txt', 'w') as f: f.writelines('test')
    test_eq(len(list(walk(new_dir))), 1)
    new_dir = mkdir(new_dir, overwrite=True)
    test_eq(len(list(walk(new_dir))), 0)
```

```python
from PIL import Image
from IPython.display import Image as IPImage
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L204)

### jpg\_size

```python
def jpg_size(
    fn
):
```

*Tuple of `(w, h)` from a JPEG file path or open binary handle*

[`jpg_size`](xtras.md#jpg_size) scans JPEG frame markers to return `(width, height)` without decoding the image:

```python
test_eq(jpg_size(fname), (1200, 803))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L219)

### gif\_size

```python
def gif_size(
    fn
):
```

*Tuple of `(w, h)` from a GIF file path or open binary handle*

[`gif_size`](xtras.md#gif_size) reads `(width, height)` from a GIF header:

```python
gif_buf = io.BytesIO()
Image.new('RGB', (41, 19), 'red').save(gif_buf, format='GIF')
gif_buf.seek(0)
test_eq(gif_size(gif_buf), (41, 19))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L224)

### png\_size

```python
def png_size(
    fn
):
```

*Tuple of `(w, h)` from a PNG file path or open binary handle*

[`png_size`](xtras.md#png_size) verifies the PNG signature and reads `(width, height)` from the header:

```python
test_eq(png_size('images/mnist3.png'), (28, 28))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L231)

### image\_size

```python
def image_size(
    fn
):
```

*Tuple of `(w, h)` for png, gif, or jpg; `None` otherwise*

[`image_size`](xtras.md#image_size) reads `(width, height)` directly from PNG, GIF, or JPEG headers:

```python
gif_buf.seek(0)
test_eq(image_size(fname), (1200, 803))
test_eq(image_size('images/mnist3.png'), (28, 28))
test_eq(image_size(gif_buf), (41, 19))
test_is(image_size(io.BytesIO(b'not an image')), None)
```

```python
img = Image.new('RGB', (50, 50), color='red')
img
```

![](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDi6KKK+ZP3EKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Z)

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L239)

### img\_bytes

```python
def img_bytes(
    img, fmt:str='PNG'
):
```

*Convert PIL `img` to bytes in format `fmt`*

```python
ib = img_bytes(img)
IPImage(ib)
```

![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAZklEQVR4nM3OMQEAMAyAMIZ/z52B/iUK8oYiSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkSZIkrwO7D0GqAWPcq78HAAAAAElFTkSuQmCC)

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L262)

### detect\_mime

```python
def detect_mime(
    data
):
```

*Get the MIME type for bytes `data`, covering common PDF, audio, video, and image types*

[`detect_mime`](xtras.md#detect_mime) inspects leading magic bytes (falling back to `imghdr`) to infer a MIME type from bytes-like input:

```python
test_eq(detect_mime(img_bytes(img, 'WEBP')), 'image/webp')
test_eq(detect_mime(bytearray(ib)), 'image/png')
detect_mime(ib)
```

```output
'image/png'
```

```python
test_is(detect_mime('this is a non-byte string'),None)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L273)

### to\_data\_url

```python
def to_data_url(
    data:bytes | bytearray | memoryview | pathlib._local.Path, # Raw bytes or file path to encode
    mime:str=None, # Optional MIME type (inferred via `detect_mime` or filename if omitted)
)->str: # Base64 `data:<mime>;base64,...` URL
```

*Encode `data` as a base64 data URL*

[`to_data_url`](xtras.md#to_data_url) encodes raw bytes or a file path as a base64 `data:` URL, inferring the MIME type when omitted:

```python
url = to_data_url(ib)
assert url.startswith('data:image/png;base64,')
test_eq(to_data_url(bytearray(ib)), url)
test_eq(to_data_url(b'hello', 'text/plain'), 'data:text/plain;base64,aGVsbG8=')
assert to_data_url(Path(fname)).startswith('data:image/jpeg;base64,')
test_fail(lambda: to_data_url(b'not a known format'), contains='MIME')
test_fail(lambda: to_data_url('not bytes'), exc=TypeError)
url[:40]
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L289)

### from\_data\_url

```python
def from_data_url(
    url:str, # Base64 `data:<mime>;base64,...` URL to parse
    decode:bool=True, # Base64-decode payload to `bytes` (else return raw base64 `str`)?
)->tuple[bytes | str, str] | None: # `(data, mime)` tuple, or `None` if `url` is not a base64 data URL
```

*Parse a base64 `data:` URL into `(data, mime)`, or `None`*

[`from_data_url`](xtras.md#from_data_url) parses a base64 `data:` URL back into `(bytes, mime)`:

```python
data, mime = from_data_url(url)
test_eq((data, mime), (ib, 'image/png'))
test_eq(to_data_url(*from_data_url(url)), url)
test_eq(from_data_url('data:text/plain;charset=utf-8;base64,aGVsbG8='), (b'hello', 'text/plain'))
test_eq(from_data_url('data:text/plain;base64,aGVsbG8=', decode=False), ('aGVsbG8=', 'text/plain'))
test_eq(from_data_url('data:;base64,aGVsbG8='), (b'hello', 'application/octet-stream'))
test_is(from_data_url('https://example.com/a.png'), None)
test_is(from_data_url('data:text/plain,hello'), None)
test_is(from_data_url('data:image/png;base64,'), None)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L302)

### bunzip

```python
def bunzip(
    fn
):
```

*bunzip `fn`, raising exception if output already exists*

[`bunzip`](xtras.md#bunzip) decompresses a `.bz2` archive beside the source file and raises if the output already exists:

```python
f = Path('files/test.txt')
if f.exists(): f.unlink()
bunzip('files/test.txt.bz2')
t = f.open().readlines()
test_eq(len(t),1)
test_eq(t[0], 'test\n')
f.unlink()
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L313)

### loads

```python
def loads(
    s, **kw
):
```

*Same as `json.loads`, but handles `None`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L319)

### dumps

```python
def dumps(
    obj, **kw
):
```

*Same as `json.dumps`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L324)

### loads\_multi

```python
def loads_multi(
    s:str
):
```

*Generator of \>\=0 decoded json dicts, possibly with non-json ignored text at start and end*

[`loads_multi`](xtras.md#loads_multi) yields JSON objects while ignoring surrounding non-JSON text:

```python
tst = """
# ignored
{ "a":1 }
hello
{
"b":2
}
"""

test_eq(list(loads_multi(tst)), [{'a': 1}, {'b': 2}])
```

[`_unpack`](xtras.md#_unpack) extracts an archive into `out` and unwraps a single top-level entry, or returns `out` when multiple entries exist at the root:

```python
with tempfile.TemporaryDirectory() as d:
    arch = shutil.make_archive(os.path.join(d, 'a'), 'gztar', base_dir='images')
    out = mkdir(Path(d)/'out')
    test_eq(_unpack(arch, out), out/'images')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L343)

### untar\_dir

```python
def untar_dir(
    fname, dest, rename:bool=False, overwrite:bool=False, uid:int=-1, gid:int=-1
):
```

*untar `file` into `dest`, creating a directory if the root contains more than one item; recursively chown if `uid`/`gid` set*

```python
def test_untar(foldername, rename=False, **kwargs):
    with tempfile.TemporaryDirectory() as d:
        nm = os.path.join(d, 'a')
        shutil.make_archive(nm, 'gztar', **kwargs)
        with tempfile.TemporaryDirectory() as d2:
            d2 = Path(d2)
            untar_dir(nm+'.tar.gz', d2, rename=rename)
            test_eq(d2.ls(), [d2/foldername])
```

If `fname` contains a single file or directory (for example using `base_dir` in `make_archive`), [`untar_dir`](xtras.md#untar_dir) places it directly in `dest`:

```python
test_untar('images', base_dir='images')
```

With `uid`/`gid`, ownership is set on every extracted entry, including symlinks themselves (not their targets), so a dangling link inside the archive does not abort the extraction:

```python
if hasattr(os, 'chown'):
    with tempfile.TemporaryDirectory() as d:
        src = Path(d)/'links'
        src.mkdir()
        (src/'dangling').symlink_to('missing-target')
        shutil.make_archive(str(Path(d)/'a'), 'gztar', root_dir=d, base_dir='links')
        out = untar_dir(Path(d)/'a.tar.gz', Path(d)/'out', uid=os.getuid(), gid=os.getgid())
        assert (out/'dangling').is_symlink()
```

If `rename` then the directory created is named based on the archive, without extension:

```python
test_untar('a', base_dir='images', rename=True)
```

If `fname` contains multiple files or directories (for example using `root_dir` in `make_archive`), [`untar_dir`](xtras.md#untar_dir) creates a new folder in `dest` named after `fname` without its extension:

```python
test_untar('a', root_dir='images')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L366)

### repo\_details

```python
def repo_details(
    url
):
```

*Tuple of `owner,name` from ssh or https git repo `url`*

[`repo_details`](xtras.md#repo_details) extracts `[owner, name]` from HTTPS or SSH git URLs:

```python
test_eq(repo_details('https://github.com/fastai/fastai.git'), ['fastai', 'fastai'])
test_eq(repo_details('git@github.com:fastai/nbdev.git\n'), ['fastai', 'nbdev'])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L373)

### shell

```python
def shell(
    *args, **kwargs
):
```

*Shortcut for `subprocess.run(shell=True)`*

[`shell`](xtras.md#shell) runs a shell command string via `subprocess.run(..., shell=True)`:

```python
res = shell('echo hi', capture_output=True, text=True)
test_eq(res.stdout.strip(), 'hi')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L379)

### run

```python
def run(
    cmd, *rest, same_in_win:bool=False, ignore_ex:bool=False, as_bytes:bool=False, stderr:bool=True, inp=None
):
```

*Pass `cmd` (splitting with `shlex` if string) to `subprocess.run`; return `stdout`; raise `IOError` if fails*

You can pass a string (which will be split based on standard shell rules), a list, or pass args directly:

```python
run('echo', same_in_win=True)
run('pip', '--version', same_in_win=True)
run(['pip', '--version'], same_in_win=True)
```

```output
'pip 26.2.1 from /Users/jhoward/aai-ws/.venv/lib/python3.13/site-packages/pip (python 3.13)'
```

```python
if sys.platform == 'win32':
    assert 'ipynb' in run('cmd /c dir /p')
    assert 'ipynb' in run(['cmd', '/c', 'dir', '/p'])
    assert 'ipynb' in run('cmd', '/c', 'dir',  '/p')
else:
    assert 'ipynb' in run('ls -ls')
    assert 'ipynb' in run(['ls', '-l'])
    assert 'ipynb' in run('ls', '-l')
```

Some commands fail in non-error situations, like `grep`. Use `ignore_ex` in those cases, which will return a tuple of stdout and returncode:

```python
if sys.platform == 'win32': test_eq(run('cmd /c findstr asdfds 00_test.ipynb', ignore_ex=True)[0], 1)
else: test_eq(run('grep asdfds 00_test.ipynb', ignore_ex=True)[0], 1)
```

[`run`](xtras.md#run) automatically decodes returned bytes to a `str`. Use `as_bytes` to skip that:

```python
if sys.platform == 'win32': test_eq(run('cmd /c echo hi'), 'hi')
else: test_eq(run('echo hi', as_bytes=True), b'hi\n')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L398)

### ssh

```python
def ssh(
    host, args:str='', user:str='ubuntu', sock=None
):
```

*Run SSH command with given arguments*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L404)

### rsync\_multi

```python
def rsync_multi(
    ip, files, user:str='ubuntu', persist:str='5m'
):
```

*Transfer multiple files with rename using persistent SSH connection*

[`rsync_multi`](xtras.md#rsync_multi) opens a persistent SSH control socket via [`ssh`](xtras.md#ssh) and transfers `(src, dst)` pairs to a remote host:

```python
rsync_multi('10.0.0.1', [('local.txt', '/tmp/remote.txt')])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L411)

### open\_file

```python
def open_file(
    fn, mode:str='r', **kwargs
):
```

*Open a file, with optional compression if gz or bz2 suffix*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L422)

### save\_pickle

```python
def save_pickle(
    fn, o
):
```

*Save a pickle file, to a file name or opened file*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L428)

### load\_pickle

```python
def load_pickle(
    fn
):
```

*Load a pickle file from a file name or opened file*

[`load_pickle`](xtras.md#load_pickle) (paired with [`save_pickle`](xtras.md#save_pickle)) round-trips objects across plain, `.gz`, and `.bz2` files:

```python
with tempfile.TemporaryDirectory() as d:
    for suf in '.pkl','.bz2','.gz':
        fn = Path(d)/f't{suf}'
        save_pickle(fn, 't')
        test_eq(load_pickle(fn), 't')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L434)

### parse\_env

```python
def parse_env(
    s:str=None, fn:Union[str, pathlib._local.Path]=None
)->dict:
```

*Parse a shell-style environment string or file*

[`parse_env`](xtras.md#parse_env) parses shell-style `KEY=VALUE` assignments from a string or file, ignoring comments and optional `export` prefixes:

```python
testf = """# comment
   # another comment
 export FOO="bar#baz"
BAR=thing # comment "ok"
  baz='thong'
QUX=quux
export ZAP = "zip" # more comments
   FOOBAR = 42   # trailing space and comment"""

exp = dict(FOO='bar#baz', BAR='thing', baz='thong', QUX='quux', ZAP='zip', FOOBAR='42')

test_eq(parse_env(testf),  exp)
```

[`_expand_import`](xtras.md#_expand_import) resolves a wildcard import node to the names actually referenced in the AST, and [`_replace_node`](xtras.md#_replace_node) splices the rewritten statement back into source:

```python
import ast, math
```

```python
_src = "from math import *\ny = sin(pi)"
_t = ast.parse(_src)
test_eq(_replace_node(_src, _t.body[0], _expand_import(_t, _t.body[0], math, set())), "from math import pi, sin\ny = sin(pi)")
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L463)

### expand\_wildcards

```python
def expand_wildcards(
    code
):
```

*Expand all wildcard imports in the given code string.*

[`expand_wildcards`](xtras.md#expand_wildcards) replaces `from mod import *` statements in Python source with explicit imports of the referenced names:

```python
inp = """from math import *
from os import *
from random import *
def func(): return sin(pi) + path.join('a', 'b') + randint(1, 10)"""

exp = """from math import pi, sin
from os import path
from random import randint
def func(): return sin(pi) + path.join('a', 'b') + randint(1, 10)"""

test_eq(expand_wildcards(inp), exp)

inp = """from itertools import *
def func(): pass"""
test_eq(expand_wildcards(inp), inp)

inp = """def outer():
    from math import *
    def inner():
        from os import *
        return sin(pi) + path.join('a', 'b')"""

exp = """def outer():
    from math import pi, sin
    def inner():
        from os import path
        return sin(pi) + path.join('a', 'b')"""

test_eq(expand_wildcards(inp), exp)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L477)

### Path.mkdir\_perms

```python
def mkdir_perms(
    mode:int=511, parents:bool=False, exist_ok:bool=False, uid:int=-1, gid:int=-1
):
```

*Create directory like Path.mkdir but optionally set uid/gid on newly created dirs*

[`Path.mkdir_perms`](xtras.md#path.mkdir_perms) wraps `Path.mkdir` with optional `mode`, `uid`, and `gid`:

```python
with tempfile.TemporaryDirectory() as tmpdir:
    p1, p2 = Path(tmpdir)/'test1', Path(tmpdir)/'a'/'b'/'c'
    p1.mkdir_perms()
    assert p1.is_dir()
    p2.mkdir_perms(parents=True)
    assert p2.is_dir()
    p1.mkdir_perms(exist_ok=True)
    with expect_fail(FileExistsError): p1.mkdir_perms()
    with expect_fail(FileNotFoundError): (Path(tmpdir)/'missing'/'child').mkdir_perms()
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L495)

### atomic\_save

```python
def atomic_save(
    fn, mode:str='wb', uid:int=-1, gid:int=-1, **kwargs
):
```

*Context manager for writing a file atomically via a temp file that is renamed on close*

[`atomic_save`](xtras.md#atomic_save) writes a temporary file in the destination directory, then renames it on success. Readers never see a partial write. If writing fails, the original file is unchanged:

```python
with tempfile.TemporaryDirectory() as d:
    fn = Path(d)/'test.txt'
    fn.write_text('original')
    with atomic_save(fn) as f: f.write(b'new')
    test_eq(fn.read_text(), 'new')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L510)

### load\_mod

```python
def load_mod(
    name, path
):
```

*Load module `name` from file `path`*

We can get a module spec from a module name:

```python
import importlib.util
```

```python
spec = importlib.util.find_spec('fastcore.basics')
spec
```

```output
ModuleSpec(name='fastcore.basics', loader=<_frozen_importlib_external.SourceFileLoader object>, origin='/Users/jhoward/aai-ws/fastcore/fastcore/basics.py')
```

...then we can load it, using the origin path:

```python
m = load_mod('fastcore.basics', spec.origin)
test_eq(m.__name__, 'fastcore.basics')
assert hasattr(m, 'store_attr')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L519)

### import\_no\_init

```python
def import_no_init(
    name
):
```

*Import dotted `name` without running any `__init__.py`*

```python
m = import_no_init('fastcore.basics')
test_eq(m.__name__, 'fastcore.basics')
assert hasattr(m, 'store_attr')

m = import_no_init('fastcore')
assert hasattr(m, '__file__')
with expect_fail(): import_no_init('nonexistent_xyz')
```

## Config

[`Config`](xtras.md#config) reads and writes an ini file with one `DEFAULT` section. Access keys as attributes, items, or with `.get(key, default)`. Use `create=` to supply initial contents for a missing file.

`types=` converts values on read. `Path` values resolve relative to the config file's directory. `Config.find(name)` searches a directory and its parents for the file.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L528)

### save\_config\_file

```python
def save_config_file(
    file, d, **kwargs
):
```

*Write settings dict to a new config file, or overwrite the existing one.*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L536)

### read\_config\_file

```python
def read_config_file(
    file, **kwargs
):
```

Config files are saved and read using Python's `configparser.ConfigParser`, inside the `DEFAULT` section.

```python
_d = dict(user='fastai', lib_name='fastcore', some_path='test', some_bool=True, some_num=3)
try:
    save_config_file('tmp.ini', _d)
    res = read_config_file('tmp.ini')
finally: os.unlink('tmp.ini')
dict(res)
```

```output
{'user': 'fastai',
 'lib_name': 'fastcore',
 'some_path': 'test',
 'some_bool': 'True',
 'some_num': '3'}
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L543)

### find\_file\_parents

```python
def find_file_parents(
    fname, # Filename to search for in `frompath` and its parents
    frompath=None, # Starting directory or file (defaults to current working directory)
    pred:<built-in function callable>=None, # Optional predicate `(Path) -> bool` on each candidate file
):
```

*Find nearest parent directory containing `fname` (matching `pred` if given), else `None`*

[`find_file_parents`](xtras.md#find_file_parents) walks up from a file or directory until it finds `fname` matching `pred`, returning `None` if absent:

```python
save_config_file('../tmp.ini', _d)
try:
    found = find_file_parents('tmp.ini')
    test_is(find_file_parents('tmp.ini', pred=lambda p: False), None)
finally: os.unlink('../tmp.ini')
found
```

```output
Path('/Users/jhoward/aai-ws/fastcore')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L554)

### Config

```python
def Config(
    cfg_path, cfg_name, create=None, save:bool=True, extra_files=None, types=None, **cfg_kwargs
):
```

*Reading and writing `ConfigParser` ini files*

[`Config`](xtras.md#config) is a convenient wrapper around `ConfigParser` ini files with a single section (`DEFAULT`).

Instantiate a [`Config`](xtras.md#config) from an ini file at `cfg_path/cfg_name`:

```python
save_config_file('../tmp.ini', _d)
try: cfg = Config('..', 'tmp.ini')
finally: os.unlink('../tmp.ini')
cfg
```

```output
{'user': 'fastai', 'lib_name': 'fastcore', 'some_path': 'test', 'some_bool': 'True', 'some_num': '3'}
```

You can create a new file if one doesn't exist by providing a `create` dict:

```python
try: cfg = Config('..', 'tmp.ini', create=_d)
finally: os.unlink('../tmp.ini')
cfg
```

```output
{'user': 'fastai', 'lib_name': 'fastcore', 'some_path': 'test', 'some_bool': 'True', 'some_num': '3'}
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L579)

### Config.get

```python
def get(
    k, default=None
):
```

*Read key `k` (or `default`), converting via `self.types` when configured*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L590)

### Config.path

```python
def path(
    k, default=None
):
```

*Resolve config value for `k` relative to `self.config_path`*

Keys can be accessed as attributes, items, or with `get` and an optional default:

```python
test_eq(cfg.user,'fastai')
test_eq(cfg['some_path'], 'test')
test_eq(cfg.get('foo','bar'),'bar')
```

If you additionally pass `save=False`, the [`Config`](xtras.md#config) will contain the items from `create` without writing a new file:

```python
cfg = Config('..', 'tmp.ini', create=_d, save=False)
test_eq(cfg.user,'fastai')
assert not Path('../tmp.ini').exists()
```

[`Config`](xtras.md#config) passes extra keyword arguments to `ConfigParser`. Inline comments are disabled by default. Set `inline_comment_prefixes` to your comment markers, as in this `#` example:

```python
cfg_str = """\
[DEFAULT]
user = fastai # inline comment

# Library configuration
lib_name = fastcore

# Paths
some_path = test 

# Feature flags
some_bool = True

# Numeric settings
some_num = # missing value
"""

with open('../tmp.ini', 'w') as f: f.write(cfg_str)
```

```python
try: cfg = Config('..', 'tmp.ini', inline_comment_prefixes=('#'))
finally: os.unlink('../tmp.ini')
test_eq(cfg.user,'fastai')
test_eq(cfg.some_num,'')
```

Extra files can be read *before* `cfg_path/cfg_name` using `extra_files`, in the order they appear:

```python
with tempfile.TemporaryDirectory() as d:
    a = Config(d, 'a.ini', {'a':0,'b':0})
    b = Config(d, 'b.ini', {'a':1,'c':0})
    c = Config(d, 'c.ini', {'a':2,'d':0}, extra_files=[a.config_file,b.config_file])
    test_eq(c.d, dict(a='2', b='0', c='0', d='0'))
```

Pass a `{key: type}` mapping in `types` to convert values when reading them. Keys without a type return strings. For `Path` values, relative paths resolve from the config file's directory. `bool` values use [`str2bool`](basics.md#str2bool).

```python
_types = dict(some_path=Path, some_bool=bool, some_num=int)
cfg = Config('..', 'tmp.ini', create=_d, save=False, types=_types)

test_eq(cfg.user,'fastai')
test_eq(cfg['some_path'].resolve(), (Path('..')/'test').resolve())
test_eq(cfg.get('some_num'), 3)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L597)

### Config.find

```python
def find(
    cfg_name, cfg_path=None, **kwargs
):
```

*Search `cfg_path` and its parents to find `cfg_name`*

You can use [`Config.find`](xtras.md#config.find) to search a path and its parents for a config file, starting in the current path if no path is specified:

```python
with tempfile.TemporaryDirectory() as d:
    sub = mkdir(Path(d)/'a'/'b', parents=True)
    Config(d, 'demo.ini', create=dict(user='fastai'))
    test_eq(Config.find('demo.ini', sub).user, 'fastai')
    test_is(Config.find('missing.ini', sub), None)
```

## Collections

[`dict2obj`](xtras.md#dict2obj) converts nested dicts to [`AttrDict`](basics.md#attrdict) and lists to [`L`](foundation.md#l), allowing attribute access such as `d.b.c`. [`obj2dict`](xtras.md#obj2dict) reverses the conversion:

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L603)

### Unset

```python
def Unset(
    *args, **kwds
):
```

*Create a collection of name/value pairs.*

Example enumeration:

> > > class Color(Enum):

...     RED \= 1 ...     BLUE \= 2 ...     GREEN \= 3

Access them by:

- attribute access:
  
  > > > Color.RED
  
  \<Color.RED: 1\>

- value lookup:
  
  > > > Color(1)
  
  \<Color.RED: 1\>

- name lookup:
  
  > > > Color\['RED'\]
  
  \<Color.RED: 1\>

Enumerations can be iterated over, and know how many members they have:

> > > len(Color)

3

> > > list(Color)

\[\<Color.RED: 1\>, \<Color.BLUE: 2\>, \<Color.GREEN: 3\>\]

Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L611)

### dict2obj

```python
def dict2obj(
    d:__main__.Unset=UNSET, list_func:fastcore.foundation._L_Meta=L, dict_func:type=AttrDict, **kwargs
):
```

*Convert (possibly nested) dicts (or lists of dicts) to [`AttrDict`](basics.md#attrdict)*

```python
d = dict2obj({'a':1, 'b':{'c':2, 'd':[3,4]}})
test_eq(d.b.c, 2)
test_eq(d.b.d[1], 4)
```

This is a convenience to give you "dotted" access to (possibly nested) dictionaries, e.g:

```python
d1 = dict(a=1, b=dict(c=2,d=3))
d2 = dict2obj(d1)
test_eq(d2.b.c, 2)
test_eq(d2.b['c'], 2)
```

kwargs can also be used:

```python
d3 = dict2obj(a=1, b=dict(c=2,d=3))
test_eq(d3.b.c, 2)
test_eq(d3.b['c'], 2)
```

It can also be used on lists of dicts.

```python
_list_of_dicts = [d1, d1]
ds = dict2obj(_list_of_dicts)
test_eq(ds[0].b.c, 2)
```

None values should be preserved:

```python
d3 = dict2obj(a=1, b=dict(c=2,d=None))
test_eq(d3.b['d'], None)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L619)

### obj2dict

```python
def obj2dict(
    d
):
```

*Convert (possibly nested) AttrDicts (or lists of AttrDicts) to `dict`*

[`obj2dict`](xtras.md#obj2dict) can be used to reverse what is done by [`dict2obj`](xtras.md#dict2obj):

```python
test_eq(obj2dict(d2), d1)
test_eq(obj2dict(ds), _list_of_dicts)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L633)

### repr\_dict

```python
def repr_dict(
    d
):
```

*Print nested dicts and lists, such as returned by [`dict2obj`](xtras.md#dict2obj)*

```python
print(repr_dict(d2))
```

```output
- a: 1
- b: 
  - c: 2
  - d: 3
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L638)

### is\_listy

```python
def is_listy(
    x
):
```

*`isinstance(x, (tuple,list,L,slice,Generator,set,frozenset))`*

```python
assert is_listy((1,))
assert is_listy([1])
assert is_listy(L([1]))
assert is_listy(slice(2))
assert not is_listy(array([1]))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L644)

### mapped

```python
def mapped(
    f, it
):
```

*map `f` over `it`, unless it's not listy, in which case return `f(it)`*

```python
def _f(x,a=1): return x-a

test_eq(mapped(_f,1),0)
test_eq(mapped(_f,[1,2]),[0,1])
test_eq(mapped(_f,(1,)),(0,))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L649)

### take\_lines

```python
def take_lines(
    s, pat, atstart:bool=True, atend:bool=False, drop:bool=False
):
```

*Take contiguous lines matching `pat` from either end of `s`*

[`take_lines`](xtras.md#take_lines) selects contiguous lines matching `pat` from the start, end, or both. By default it returns the selected lines; `drop=True` returns everything else. Original line endings are preserved.

By default, matching lines are taken only from the start.

```python
s = '# heading\n\n%%time\nx = 1\n'
pat = r'^(#|%%|$)'

test_eq(take_lines(s, pat), '# heading\n\n%%time\n')
test_eq(take_lines(s, pat, drop=True), 'x = 1\n')

s = '# head\nx = 1\n# tail\n'
test_eq(take_lines(s, r'^#', atend=True), '# head\n# tail\n')
take_lines(s, r'^#', atend=True, drop=True)
```

```output
'x = 1\n'
```

## Extensions to Pathlib.Path

These methods extend [Pathlib.Path](https://docs.python.org/3/library/pathlib.html#basic-use):

- `ls()` lists directory contents as an [`L`](foundation.md#l), optionally filtered by MIME prefix or extension.
- `read_json`, `write_json`, `read_jsonl`, `read_toml`, and `write_toml` handle JSON and TOML files.
- `readlines` reads lines; `mk_write` creates parent directories before writing.
- `delete`, `relpath`, and `normpath` provide file deletion and path conversions.

Set `Path.BASE_PATH` to display paths relative to that directory.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L661)

### Path.readlines

```python
def readlines(
    hint:int=-1, encoding:str='utf8'
):
```

*Read the content of `self`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L667)

### Path.read\_json

```python
def read_json(
    encoding=None, errors=None
):
```

*Same as `read_text` followed by [`loads`](xtras.md#loads)*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L673)

### Path.read\_toml

```python
def read_toml(
    encoding:str='utf-8', errors=None
):
```

*Same as `read_text` followed by `tomllib.loads`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L679)

### loads\_jsonl

```python
def loads_jsonl(
    s, name:str='<str>'
):
```

*Parse newline-delimited JSON from string or line iterable `s`, splitting only on `\n`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L688)

### Path.read\_jsonl

```python
def read_jsonl(
    encoding=None, errors=None
):
```

*Parse newline-delimited JSON, returning one object per line*

[JSON Lines](https://jsonlines.org/) uses `\n` to separate records. `splitlines()` also splits at U\+0085, U\+2028, and U\+2029, which can occur inside valid JSON strings:

```python
s = '{"id": 1, "msg": "durable execution,\u2028backend development"}\n{"id": 2, "msg": "plain"}\n'
test_eq(len(s.splitlines()), 3)
```

[`loads_jsonl`](xtras.md#loads_jsonl) (and [`Path.read_jsonl`](xtras.md#path.read_jsonl)) splits records only at `\n`:

```python
recs = loads_jsonl(s)
test_eq(len(recs), 2)
recs
```

```output
[{'id': 1, 'msg': 'durable execution,\u2028backend development'},
 {'id': 2, 'msg': 'plain'}]
```

Parse errors include the source name and line number:

```python
with expect_fail(ValueError, contains='bad.jsonl:2'): loads_jsonl('{"id": 1}\n{"id": 2\n', name='bad.jsonl')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L694)

### Path.mk\_write

```python
def mk_write(
    data, encoding=None, errors=None, mode:int=511, uid:int=-1, gid:int=-1
):
```

*Make all parent dirs of `self`, and write `data`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L702)

### Path.write\_json

```python
def write_json(
    data, encoding=None, errors=None, mode:int=511, uid:int=-1, gid:int=-1, **kw
):
```

*Same as [`dumps`](xtras.md#dumps) followed by `mk_write`*

[`Path.write_json`](xtras.md#path.write_json) creates missing parent directories and writes serialized JSON:

```python
with tempfile.TemporaryDirectory() as d:
    fn = Path(d)/'sub'/'cfg.json'
    fn.write_json(dict(a=1))
    test_eq(fn.read_json(), dict(a=1))
```

[`_toml_key`](xtras.md#_toml_key) leaves bare TOML keys unquoted and JSON-quotes keys with dots, spaces, or control characters:

```python
test_eq(_toml_key('foo-bar_1'), 'foo-bar_1')
test_eq(_toml_key('a.b'), '"a.b"')
test_eq(_toml_key('a\x7fb'), r'"a\u007fb"')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L712)

### toml\_val

```python
def toml_val(
    v, # Python value to format as a TOML literal
    inline:bool=False, # Keep lists on a single line?
)->str:
```

*Format `v` as a TOML value literal using only the standard library*

[`toml_val`](xtras.md#toml_val) formats individual Python values as TOML literals:

```python
test_eq(toml_val(True), 'true')
test_eq(toml_val(float('nan')), 'nan')
test_eq(toml_val(float('-inf')), '-inf')
test_eq(toml_val('a\x7fb'), r'"a\u007fb"')
test_eq(toml_val(date(2026, 11, 29)), '2026-11-29')
test_eq(toml_val(['a', 'b']), '["a", "b"]')
assert '\n' in toml_val([f'pkg-{i}' for i in range(10)])
assert '\n' not in toml_val([f'pkg-{i}' for i in range(10)], inline=True)
test_eq(toml_val({'path': '../pkg', 'a.b': 1}), '{ path = "../pkg", "a.b" = 1 }')
with expect_fail(TypeError, contains='NoneType'): toml_val(None)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L731)

### dumps\_toml

```python
def dumps_toml(
    d:dict, # Mapping to serialize as TOML
)->str:
```

*Serialize `d` to a TOML string using only the standard library*

[`dumps_toml`](xtras.md#dumps_toml) serializes nested dicts to TOML using only the standard library:

```python
data = dict(project=dict(name='demo', deps=[f'pkg-{i}' for i in range(10)]), empty=dict(sub={}),
    patch={'https://example.com/repo': dict(mycrate=dict(path='../mycrate'))})
txt = dumps_toml(data)
test_eq(tomllib.loads(txt), data)
test_eq(dumps_toml(tomllib.loads(txt)), txt)
assert '[patch."https://example.com/repo"]' in txt
assert 'mycrate = { path = "../mycrate" }' in txt
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L754)

### Path.write\_toml

```python
def write_toml(
    data, encoding:str='utf-8', errors=None, mode:int=511, uid:int=-1, gid:int=-1
):
```

*Same as [`dumps_toml`](xtras.md#dumps_toml) followed by `mk_write`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L759)

### write\_if\_changed

```python
def write_if_changed(
    p:str | pathlib._local.Path, # Destination file path
    txt:str, # Text content to write
    encoding:str='utf-8', # File encoding
)->bool: # True if file was created or updated
```

*Write `txt` to `p` only if missing or content differs; return whether written*

[`write_if_changed`](xtras.md#write_if_changed) writes `txt` only when the destination file is missing or its contents differ, returning `True` if written:

```python
with tempfile.TemporaryDirectory() as d:
    p = Path(d)/'sub'/'cfg.toml'
    assert write_if_changed(p, '[project]\nname = "demo"\n')
    assert not write_if_changed(p, '[project]\nname = "demo"\n')
    test_eq(p.read_toml(), {'project': {'name': 'demo'}})
    assert write_if_changed(p, '[project]\nname = "demo2"\n')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L772)

### Path.relpath

```python
def relpath(
    start=None
):
```

*Same as `os.path.relpath`, but returns a `Path`, and resolves symlinks*

[`Path.relpath`](xtras.md#path.relpath) returns a symlink-resolved relative `Path`:

```python
p = Path('../fastcore/').resolve()
p
```

```output
Path('/Users/jhoward/aai-ws/fastcore/fastcore')
```

```python
p.relpath(Path.cwd())
```

```output
Path('../fastcore')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L778)

### Path.ls

```python
def ls(
    n_max=None, file_type=None, file_exts=None
):
```

*Contents of path as a list*

We add an `ls()` method to `pathlib.Path` which is simply defined as `list(Path.iterdir())`, mainly for convenience in REPL environments such as notebooks.

```python
path = Path()
t = path.ls()
assert len(t)>0
t1 = path.ls(10)
test_eq(len(t1), 10)
t2 = path.ls(file_exts='.ipynb')
assert len(t)>len(t2)
t[0]
```

```output
Path('llms.txt')
```

You can also pass an optional `file_type` MIME prefix and/or a list of file extensions.

```python
lib_path = (path/'../fastcore')
txt_files=lib_path.ls(file_type='text')
assert len(txt_files) > 0 and txt_files[0].suffix=='.py'
ipy_files=path.ls(file_exts=['.ipynb'])
assert len(ipy_files) > 0 and ipy_files[0].suffix=='.ipynb'
txt_files[0],ipy_files[0]
```

```output
(Path('../fastcore/shutil.py'), Path('000_tour.ipynb'))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L790)

### Path.normpath

```python
def normpath():
```

*Normalize path, eliminating double slashes, etc.*

`normpath` normalizes a path by collapsing redundant separators and up-level references (e.g., `..`).

```python
p = Path('foo//bar/../baz')
p.normpath()
```

```output
Path('foo/baz')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L796)

### Path.\_\_repr\_\_

```python
def __repr__():
```

*Return repr(self).*

Set `Path.BASE_PATH` to display paths within that directory relative to it. Paths outside the directory keep their existing representation:

```python
t = ipy_files[0].absolute()
try:
    Path.BASE_PATH = t.parent.parent
    test_eq(repr(t), f"Path('ship/{t.name}')")
finally: Path.BASE_PATH = None
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L805)

### Path.delete

```python
def delete():
```

*Delete a file, symlink, or directory tree*

[`Path.delete`](xtras.md#path.delete) removes a file, symlink, or directory tree without raising if the path is already missing:

```python
with tempfile.TemporaryDirectory() as d:
    p1, sub = Path(d)/'a.txt', Path(d)/'sub'
    p1.write_text('x')
    (sub/'b.txt').mk_write('y')
    p1.delete()
    sub.delete()
    p1.delete()
    assert not p1.exists() and not sub.exists()
```

## Reindexing Collections

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L819)

#### ReindexCollection

```python
def ReindexCollection(
    coll, idxs=None, cache=None, tfm:function=noop
):
```

*Reindexes collection `coll` with indices `idxs` and optional LRU cache of size `cache`*

[`ReindexCollection`](xtras.md#reindexcollection) changes the order in which you read a collection without rearranging its contents. fastai uses it to prepare data for language models.

Pass the index order in `idxs`, or change it later with `reindex`. Use descending indices to read the list in reverse order:

```python
rc=ReindexCollection(['a', 'b', 'c', 'd', 'e'], idxs=[4,3,2,1,0])
list(rc)
```

```output
['e', 'd', 'c', 'b', 'a']
```

Alternatively, you can use the `reindex` method:

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L830)

###### ReindexCollection.reindex

```python
def reindex(
    idxs
):
```

*Replace `self.idxs` with idxs*

```python
rc=ReindexCollection(['a', 'b', 'c', 'd', 'e'])
rc.reindex([4,3,2,1,0])
list(rc)
```

```output
['e', 'd', 'c', 'b', 'a']
```

You can optionally specify a LRU cache, which uses [functools.lru\_cache](https://docs.python.org/3/library/functools.html#functools.lru_cache) upon instantiation:

```python
sz = 50
t = ReindexCollection(L.range(sz), cache=2)
t[0], t[0]
t._get.cache_info()
```

```output
CacheInfo(hits=1, misses=1, maxsize=2, currsize=1)
```

You can optionally clear the LRU cache by calling the `cache_clear` method:

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L834)

##### ReindexCollection.cache\_clear

```python
def cache_clear():
```

*Clear LRU cache*

```python
t.cache_clear()
t._get.cache_info()
```

```output
CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L831)

##### ReindexCollection.shuffle

```python
def shuffle():
```

*Randomly shuffle indices*

Without `idxs`, [`ReindexCollection`](xtras.md#reindexcollection) starts in the collection's original order. `shuffle` changes the index order:

```python
rc=ReindexCollection(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
rc.shuffle()
list(rc)
```

```output
['d', 'g', 'a', 'c', 'e', 'h', 'b', 'f']
```

```python
t = ReindexCollection(L.range(50), cache=2)
test_eq(list(t), range(50))
test_eq(t[49], 49)
test_eq(t._get.cache_info().hits, 1)
t.shuffle()
test_eq(t._get.cache_info().hits, 1)
test_ne(list(t), range(50))
test_eq(set(t), set(range(50)))
t.cache_clear()
test_eq((t._get.cache_info().hits, t.count(0)), (0, 1))
```

## [`SaveReturn`](xtras.md#savereturn) and [`save_iter`](xtras.md#save_iter) Variants

A generator can return a final value as well as yielding values. Normal iteration discards that return value:

```python
def example_generator():
    total = 0
    for i in range(3):
        total += i
        yield i
    return total

values = list(example_generator())
values
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L841)

### SaveReturn

```python
def SaveReturn(
    its
):
```

*Wrap an iterator such that the generator function's return value is stored in `.value`*

<details open>
<summary>Exported source</summary>

```python
class SaveReturn:
    "Wrap an iterator such that the generator function's return value is stored in `.value`"
    def __init__(self, its): self.its = its
    def __iter__(self):
        self.value = yield from self.its
        return self.value
```

</details>

[`SaveReturn`](xtras.md#savereturn) wraps a non-async generator and captures its return value. It uses `yield from`, whose result is the value returned by the generator:

```python
def sum_range(n):
    total = 0
    for i in range(n):
        total += i
        yield i
    return total

sr = SaveReturn(sum_range(5))
values = list(sr)
print(f"Values: {values}")
sr.value
```

```output
Values: [0, 1, 2, 3, 4]
10
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L849)

### trim\_wraps

```python
def trim_wraps(
    f, n:int=1
):
```

*Like wraps, but removes the first n parameters from the signature*

[`trim_wraps`](xtras.md#trim_wraps) is a decorator factory that works like `functools.wraps`, but removes the first `n` parameters from the wrapped function's signature (used to give [`save_iter`](xtras.md#save_iter) an accurate signature). This is useful when creating wrapper functions that consume some parameters internally and shouldn't expose them in the public API.

```python
def adder(base, x, y): return base + x + y

def make_adder(base_value):
    @trim_wraps(adder)
    def _(x, y): return adder(base_value, x, y)
    return _

add_10 = make_adder(10)
print(f"{add_10.__name__}{inspect.signature(add_10)}")
```

```output
adder(x, y)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L866)

### save\_iter

```python
def save_iter(
    g
):
```

*Decorator that allows a generator function to store values in the returned iterator object*

[`save_iter`](xtras.md#save_iter) passes the returned iterator to the generator as its first argument. You can store multiple attributes on that object at any point during iteration. Here `o.value` holds the final sum:

```python
@save_iter
def sum_range(o, n):
    total = 0
    for i in range(n):
        total += i
        yield i
    o.value = total
```

Call `sum_range` with only `n`. [`save_iter`](xtras.md#save_iter) supplies `o`:

```python
print(sum_range.__signature__)
```

```output
(n)
```

```python
sr = sum_range(5)
print(f"Values: {list(sr)}")
print(f"Sum stored: {sr.value}")
```

```output
Values: [0, 1, 2, 3, 4]
Sum stored: 10
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L873)

### asave\_iter

```python
def asave_iter(
    g
):
```

*Like [`save_iter`](xtras.md#save_iter), but for async iterators*

[`asave_iter`](xtras.md#asave_iter) works like [`save_iter`](xtras.md#save_iter) for async generators. These cannot return a value or use `yield from`, so [`SaveReturn`](xtras.md#savereturn) does not apply.

```python
@asave_iter
async def asum_range(self, n):
    total = 0
    for i in range(n):
        total += i
        yield i
    self.value = total

asr = asum_range(5)
print(f"Values: {[o async for o in asr]}")
print(f"Sum stored: {asr.value}")
```

```output
Values: [0, 1, 2, 3, 4]
Sum stored: 10
```

## Other Helpers

Other utilities include:

- [`exec_eval`](xtras.md#exec_eval): run a code string and return its last expression, like a notebook cell.
- [`fenced`](xtras.md#fenced): wrap text in a Markdown fence longer than any fence character run in the body.
- [`md_sub`](xtras.md#md_sub): regex-substitute Markdown text outside fenced/indented code blocks and inline code.
- [`md_blocks`](xtras.md#md_blocks) and [`md_unwrap`](xtras.md#md_unwrap): segment Markdown into fenced/semantic/prose blocks and unwrap hard-wrapped paragraphs.
- [`str_diff`](xtras.md#str_diff): return a unified diff, or `''` for identical text.
- [`unqid`](xtras.md#unqid) and [`friendly_name`](xtras.md#friendly_name): generate random Python identifiers or memorable word-based names.
- [`flexicache`](xtras.md#flexicache): cache results with configurable expiration policies.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L880)

### strloader

```python
def strloader():
```

*`yaml.BaseLoader` extended to resolve [`true`](basics.md#true)/`True`/`false`/`False`, and nothing else, to `bool`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L892)

### frontmatter

```python
def frontmatter(
    txt:str, strvals:bool=False
)->tuple:
```

*Tuple of (dict, body) from frontmatter in `txt`; missing frontmatter returns ({}, txt), malformed YAML raises*

The closing fence can end the text without a trailing newline.

`strvals=True` keeps scalar values as strings while preserving YAML's lists and mappings. This is useful when reading amounts and dates from legal forms.

Unquoted [`true`](basics.md#true), `True`, `false`, and `False` become booleans. Keeping `'false'` as a string would make a flag test treat it as true. Quoted values and `yes`/`no`/`on`/`off` remain strings:

```python
test_eq(frontmatter('---\ntitle: "Hi there"\ntags: [a,b]\n---\nBody'), ({'title':'Hi there', 'tags':['a','b']}, 'Body'))
test_eq(frontmatter('---\nbroken: [a,'), ({}, '---\nbroken: [a,'))
test_eq(frontmatter('No frontmatter here'), ({}, 'No frontmatter here'))
test_eq(frontmatter('---\njust text no closing'), ({}, '---\njust text no closing'))
test_eq(frontmatter('---\n---\nBody'), ({}, '---\n---\nBody'))
with expect_fail(): frontmatter('---\nbad: "unclosed\n---\nB')
test_eq(frontmatter('---\nt: v\n...\nBody'), ({'t':'v'}, 'Body'))
test_eq(frontmatter('---\nt: v\n---'), ({'t':'v'}, ''))
```

With `strvals=True`, YAML scalars stay strings except [`true`](basics.md#true)/`True`/`false`/`False`; CRLF line endings pass through unchanged:

```python
test_eq(frontmatter('---\nn: 1000\ngs:\n  - {d: X, n: 1}\n---\nB', strvals=True), ({'n':'1000','gs':[{'d':'X','n':'1'}]}, 'B'))
test_eq(frontmatter('---\na: true\nb: False\nc: TRUE\nq: "true"\nnm: Norway\nn: no\n---\nB', strvals=True), (dict(a=True, b=False, c='TRUE', q='true', nm='Norway', n='no'), 'B'))
test_eq(frontmatter('---\r\nt: v\r\n---\r\nA\r\nB\r\n'), ({'t':'v'}, 'A\r\nB\r\n'))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L900)

### clean\_cli\_output

```python
def clean_cli_output(
    txt:str, strip:bool=True
):
```

*Render CLI output as it appears on screen: alternate screen, `\r` overwrites, `\b` backspaces, and ANSI escapes*

[`clean_cli_output`](xtras.md#clean_cli_output) collapses alternate-screen blocks and applies `\r` carriage-return overwrites (leaving trailing `\r` text visible):

```python
test_eq(clean_cli_output('hello\x1b[?1049hworld'), '')
test_eq(clean_cli_output('before\x1b[?1049hscreen stuff\x1b[?1049lafter'), 'after')
test_eq(clean_cli_output('downloading...\rprogress 50%\rdone!'), 'done!')
test_eq(clean_cli_output('line1\nfoo\rbar\nline3'), 'line1\nbar\nline3')
test_eq(clean_cli_output('abc\r'), 'abc')
test_eq(clean_cli_output('download\rdone\r'), 'done')
```

Backspaces (`\b`) overwrite within the current line without crossing newlines; trailing backspaces only move the cursor:

```python
test_eq(clean_cli_output('hellp\bo world'), 'hello world')
test_eq(clean_cli_output('ab\b'), 'ab')
test_eq(clean_cli_output('\bx'), 'x')
test_eq(clean_cli_output('a\n\bb'), 'a\nb')
```

ANSI and OSC escape sequences are stripped by default (pass `strip=False` to keep them), and PTY `\r\n` endings normalize to `\n`:

```python
test_eq(clean_cli_output('\x1b[31mred\x1b[0m text'), 'red text')
test_eq(clean_cli_output('\x1b]0;title\x07hello'), 'hello')
test_eq(clean_cli_output('\x1b[31mred\x1b[0m', strip=False), '\x1b[31mred\x1b[0m')
test_eq(clean_cli_output('just plain text\nline two'), 'just plain text\nline two')
test_eq(clean_cli_output('hello\r\n'), 'hello\n')
test_eq(clean_cli_output('line1\r\nline2\r\n'), 'line1\nline2\n')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L914)

### unqid

```python
def unqid(
    seeded:bool=False
):
```

*Generate a unique id suitable for use as a Python identifier*

[`unqid`](xtras.md#unqid) generates a random unique identifier that is safe to use as a Python variable name (starts with `_`, uses only alphanumeric characters and underscores). It's based on UUID4, encoded in URL-safe base64.

If `seeded=True`, uses `random.getrandbits` which respects `random.seed()`, making it reproducible. Otherwise uses `uuid4()` which is always random.

```python
unqid()
```

```output
'_sWGFSh8ETTq4er7bX4DUag'
```

With seeding for reproducibility:

```python
random.seed(42)
a = unqid(seeded=True)
random.seed(42)
b = unqid(seeded=True)
test_eq(a, b)
```

Without seeding - always unique:

```python
test_ne(unqid(), unqid())
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L923)

### rtoken\_hex

```python
def rtoken_hex(
    nbytes:int=16, # Number of bytes to generate
)->str: # hex string of length nbytes*2
```

*Generate a random hex string using Python's random module.*

This is the same as `secrets.token_hex`, but is reproducible/seedable.

```python
import secrets
```

```python
secrets.token_hex(4),rtoken_hex(4)
```

```output
('f8d349de', '8c7d7247')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L931)

### friendly\_name

```python
def friendly_name(
    levels:int=3, suffix:int=4
):
```

*Generate a random human-readable name with customizable word levels and suffix length*

[`friendly_name`](xtras.md#friendly_name) generates random, human-readable names by combining adjectives, nouns, verbs, and adverbs with a random alphanumeric suffix. This is useful for creating memorable identifiers for temporary files, test data, or user-friendly resource names.

```python
friendly_name()
```

```output
'objective-forest-builds-0y6d'
```

Names are hyphen-separated and follow the pattern `adjective-noun-verb-adverb`, randomly chosen from lists of size 102, 116, 110, and 30, respectively. The `levels` param selects how many of the names to include:

```python
friendly_name(2)
```

```output
'lavender-hummingbird-divu'
```

`suffix` sets the length of the random alphanumeric ending. Each suffix item is taken from the 36 options of lowercase letters plus digits.

```python
friendly_name(4, 6)
```

```output
'elated-koala-begins-softly-zpqk51'
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L943)

### n\_friendly\_names

```python
def n_friendly_names(
    levels:int=3, suffix:int=4
):
```

*Number of possible combos for [`friendly_name`](xtras.md#friendly_name)*

The number of combinations if all levels are included is:

```python
print(f'{n_friendly_names(4):,}')
```

```output
65,581,614,489,600
```

The default settings give:

```python
print(f'{n_friendly_names():,}')
```

```output
2,186,053,816,320
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L949)

### exec\_eval

```python
def exec_eval(
    code, # Code to exec/eval
    g=None, # Globals namespace dict
    l=None, # Locals namespace dict
):
```

*Evaluate `code` in `g` (defaults to `globals()`) and `l` (defaults to `locals()`)*

This is a combination of `eval` and `exec`, which behaves like ipython and Jupyter. If the last line is an expression, it is evaluated and the result is returned:

```python
exec_eval('''
def f(x): return x+1
f(1)
''')
```

```output
2
```

By default, the code uses the caller's globals and locals. For instance, here `f` is available since it's been added to our symbol table:

```python
exec_eval('print(f(2))')
```

```output
3
```

Pass a dict as the `g` param in order to use an arbitrary namespace:

```python
exec_eval('print(f)', {'f': 'Hi I am f.'})
```

```output
Hi I am f.
```

This function helps us identify the first declared raw function of a dispatched function:

```python
from plum import Function
```

```python
def f1(x): return "Any"
def f2(x:int): return "Int"

df = Function(f1).dispatch(f1).dispatch(f2)

test_eq(_unwrapped_type_dispatch_func(df), f1)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L981)

### get\_source\_link

```python
def get_source_link(
    func
):
```

*Return link to `func` in source code*

[`get_source_link`](xtras.md#get_source_link) returns a link to the source code for an object. For [fastship](https://ship.fast.ai) projects such as `fastcore`, it reads `git_url` from the package's `_modidx.py` (generated by `ship-export`) to build a full GitHub link.

For example, below we get the link to [`fastcore.test.test_eq`](test.md#test_eq):

```python
from fastcore.test import test_eq
```

```python
assert get_source_link(test_eq).startswith('https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/test.py#L')
get_source_link(test_eq)
```

```output
'https://github.com/AnswerDotAI/fastcorefastcore/test.py#L76'
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1011)

### sparkline

```python
def sparkline(
    data, mn=None, mx=None, empty_zero:bool=False
):
```

*Sparkline for `data`, with `None`s (and zero, if `empty_zero`) shown as empty column*

```python
data = [9,6,None,1,4,0,8,15,10]
print(f'without "empty_zero": {sparkline(data, empty_zero=False)}')
print(f'   with "empty_zero": {sparkline(data, empty_zero=True )}')
```

```output
without "empty_zero": ▅▂ ▁▂▁▃▇▅
   with "empty_zero": ▅▂ ▁▂ ▃▇▅
```

You can set a maximum and minimum for the y-axis of the sparkline with the arguments `mn` and `mx` respectively:

```python
sparkline([1,2,3,400], mn=0, mx=3)
```

```output
'▂▅▇▇'
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1020)

### modify\_exception

```python
def modify_exception(
    e:Exception, # An exception
    msg:str=None, # A custom message
    replace:bool=False, # Whether to replace e.args with [msg]
)->Exception:
```

*Modifies `e` with a custom message attached*

[`modify_exception`](xtras.md#modify_exception) prepends or replaces an exception's message in place:

```python
msg = "This is my custom message!"

with expect_fail(Exception, ''): (_ for _ in ()).throw(modify_exception(Exception(), None))
with expect_fail(Exception, msg): (_ for _ in ()).throw(modify_exception(Exception(), msg))
with expect_fail(Exception, "The first message This is my custom message!"): (_ for _ in ()).throw(modify_exception(Exception("The first message"), msg))
with expect_fail(Exception, "This is my custom message!"): (_ for _ in ()).throw(modify_exception(Exception("The first message"), msg, True))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1030)

### round\_multiple

```python
def round_multiple(
    x, mult, round_down:bool=False
):
```

*Round `x` to nearest multiple of `mult`*

[`round_multiple`](xtras.md#round_multiple) rounds numbers to the nearest multiple of `mult` (or down with `round_down=True`):

```python
test_eq(round_multiple(63,32), 64)
test_eq(round_multiple(50,32), 64)
test_eq(round_multiple(40,32), 32)
test_eq(round_multiple( 0,32),  0)
test_eq(round_multiple(63,32, round_down=True), 32)
test_eq(round_multiple((63,40),32), (64,32))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1037)

### set\_num\_threads

```python
def set_num_threads(
    nt
):
```

*Get numpy (and others) to use `nt` threads*

This sets the number of threads consistently for many tools, by:

1. Set the following environment variables equal to `nt`: `OPENBLAS_NUM_THREADS`,`NUMEXPR_NUM_THREADS`,`OMP_NUM_THREADS`,`MKL_NUM_THREADS`
2. Sets `nt` threads for numpy and pytorch.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1051)

### join\_path\_file

```python
def join_path_file(
    file, path, ext:str=''
):
```

*Return `path/file` if file is a string or a `Path`, file otherwise*

[`join_path_file`](xtras.md#join_path_file) joins `path/file` (creating parent directories if needed) for string or `Path` inputs and passes open file objects through unchanged:

```python
path = Path.cwd()/'_tmp'/'tst'
f = join_path_file('tst.txt', path)
assert path.exists()
test_eq(f, path/'tst.txt')
with open(f, 'w') as f_: assert join_path_file(f_, path) == f_
shutil.rmtree(Path.cwd()/'_tmp')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1058)

### autostart

```python
def autostart(
    g
):
```

*Decorator that automatically starts a generator*

[`autostart`](xtras.md#autostart) primes a generator immediately on call so you can call `.send(...)` without calling `next(...)` first:

```python
@autostart
def _acc():
    res = []
    while True: res.append((yield res))
g = _acc()
test_eq(g.send(1), [1])
test_eq(g.send(2), [1, 2])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1068)

#### EventTimer

```python
def EventTimer(
    store:int=5, span:int=60
):
```

*An event timer with history of `store` items of time `span`*

Add events with `add`, and get number of `events` and their frequency (`freq`).

```python
def _randwait(): yield from (sleep(random.random()/200) for _ in range(100))

c = EventTimer(store=5, span=0.03)
for o in _randwait(): c.add(1)
print(f'Num Events: {c.events}, Freq/sec: {c.freq:.01f}')
print('Most recent: ', sparkline(c.hist), *L(c.hist).map('{:.01f}'))
```

```output
Num Events: 9, Freq/sec: 334.2
Most recent:  ▃▂▇▁▆ 263.0 253.9 283.5 243.7 273.8
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1095)

### stringfmt\_names

```python
def stringfmt_names(
    s:str
)->list:
```

*Unique brace-delimited names in `s`*

```python
s = '/pulls/{pull_number}/reviews/{review_id}'
test_eq(stringfmt_names(s), ['pull_number','review_id'])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1100)

#### PartialFormatter

```python
def PartialFormatter():
```

*A `string.Formatter` that doesn't error on missing fields, and tracks missing fields and unused args*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1115)

### partial\_format

```python
def partial_format(
    s:str, **kwargs
):
```

*string format `s`, ignoring missing field errors, returning missing and extra fields*

The result is a tuple of `(formatted_string,missing_fields,extra_fields)`, e.g:

```python
res,missing,xtra = partial_format(s, pull_number=1, foo=2)
test_eq(res, '/pulls/1/reviews/{review_id}')
test_eq(missing, ['review_id'])
test_eq(xtra, {'foo':2})
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1122)

### truncstr

```python
def truncstr(
    s:str, maxlen:int, suf:str='…', space:str='', sizevar:str=None
)->str:
```

*Truncate `s` to length `maxlen` (None: no limit), adding suffix `suf` if truncated; a callable `suf` gets the number of characters cut*

A callable `suf` receives the number of characters removed, including those displaced by the suffix itself:

```python
w = 'abacadabra'
test_eq(truncstr(w, 10), w)
test_eq(truncstr(w, None), w)
test_eq(truncstr(w, 5), 'abac…')
test_eq(truncstr(w, 5, suf=''), 'abaca')
test_eq(truncstr(w, 11, space='_'), w+"_")
test_eq(truncstr(w, 10, space='_'), w[:-1]+'…')
test_eq(truncstr(w, 5, suf='!!'), 'aba!!')
test_eq(truncstr(w, 8, suf=lambda n: f'…[{n}]'), 'abac…[6]')
test_eq(truncstr('x'*5000, 20, suf=lambda n: f'…[{humanize(n)}]'), 'x'*15+'…[5k]')
```

Set `sizevar='_n_'` to substitute the original string length for `{_n_}` in [`truncstr`](xtras.md#truncstr)'s suffix. Here `(11)` records the length before truncation:

```python
test_eq(truncstr('hello world', 8, suf='…({_n_})', sizevar='_n_'), 'hel…(11)')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1133)

### trunc\_ctr

```python
def trunc_ctr(
    s:str, mx:int=1000
)->str:
```

*Truncate the middle of `s` so \~`mx` chars remain, marking the elision with its [`humanize`](basics.md#humanize)d size*

[`trunc_ctr`](xtras.md#trunc_ctr) keeps the head and tail of a long string, elides the middle, and marks the elision with its [`humanize`](basics.md#humanize)d size. Use it when both ends of a document matter, such as a summary at the top and the discussion at the end.

```python
d = 'summary ' + 'x'*30 + ' replies'
test_eq(trunc_ctr(d, 100), d)
test_eq(trunc_ctr(d, None), d)
trunc_ctr(d, 12)
```

```output
'summar…[34 chars]…eplies'
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1140)

### TruncatedString

```python
def TruncatedString(
    s:str='', mx:int=1000
):
```

*A `str` whose repr shows contents verbatim, middle-truncated to \~`mx` chars*

Wrap a large tool result in [`TruncatedString`](xtras.md#truncatedstring) to shorten its bare display without discarding text. Its `repr` uses [`trunc_ctr`](xtras.md#trunc_ctr). Slicing, searching and `print` still use the complete string.

```python
t = TruncatedString(d, 12)
test_eq(t, d)
test_eq(len(t), len(d))
test_eq(t[:7], 'summary')
t
```

```output
summar…[34 chars]…eplies
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1149)

### fenced

```python
def fenced(
    text:str, info:str='', ch:str='`'
)->str:
```

*Wrap `text` in a fence of `ch`, one char longer than any run of `ch` inside it (min 3)*

When generated text goes inside a markdown code fence, the fence must be longer than any run of the fence character in the body, or the block ends early. [`fenced`](xtras.md#fenced) picks a safe fence: one char longer than the longest such run anywhere in the text, at least the standard three.

`````python
print(fenced('x=1', 'python'))
test_eq(fenced('x=1', 'python'), '```python\nx=1\n```')
s = 'a ````four```` backtick run'
test_eq(fenced(s), '`'*5 + '\n' + s + '\n' + '`'*5)
`````

````output
```python
x=1
```
````

Fence character runs count anywhere in the text, including mid-line. `info` is appended verbatim; include a leading space for forms such as `::: output`. Trailing newlines are stripped. An empty body leaves one blank line between the fences.

````python
test_eq(fenced('text', 'output', ch=':'), ':::output\ntext\n:::')
test_eq(fenced('x\n\n'), '```\nx\n```')
test_eq(fenced(''), '```\n\n```')
````

[`_fence_step`](xtras.md#_fence_step) tracks opening, nested inner fences (shorter than the opener), and matching closing fences:

`````python
test_eq(_fence_step('````md\n', None), ('````', 'open', 'md'))
test_eq(_fence_step('```py\n', '````'), ('````', None, ''))
test_eq(_fence_step('````\n', '````'), (None, 'close', ''))
`````

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1174)

### fenced\_blocks

```python
def fenced_blocks(
    text:str, # Markdown text to scan
    ch:str='`', # Fence character
)->list: # `(info, body, start, end)` per block; `start`/`end` are char offsets of the whole block
```

*Top-level fenced blocks in `text`, fence-nesting-aware: the inverse of [`fenced`](xtras.md#fenced)*

Only top-level blocks are returned. A closing fence must be at least as long as its opener and contain no other text. Shorter fences remain in the body. Unclosed blocks are omitted.

````python
s = "before\n\n```json {.tool}\n{\"a\": 1}\n```\n\nafter\n"
blks = fenced_blocks(s)
test_eq(len(blks), 1)
info,body,start,end = blks[0]
test_eq(info, 'json {.tool}')
test_eq(body, '{"a": 1}\n')
test_eq(s[start:end], '```json {.tool}\n{"a": 1}\n```\n')
````

Nested fences stay inside the outer block, unclosed fences return no block, and `ch` selects a custom fence character:

````python
outer = fenced(s, 'markdown')
test_eq(fenced_blocks(outer)[0][0], 'markdown')
test_eq(fenced_blocks('```\nopen\n'), [])
test_eq(fenced_blocks('::::a\nx\n::::\n', ch=':')[0][0], 'a')
````

[`_sub_non_code`](xtras.md#_sub_non_code) applies a compiled regex outside single- and multi-backtick inline code spans on one line:

```python
test_eq(_sub_non_code(re.compile('X'), 'Y', "Hi X, `X`, and ``X ` X``"), "Hi Y, `X`, and ``X ` X``")
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1202)

### md\_sub

```python
def md_sub(
    pat, # Regex pattern or compiled regex to replace
    repl, # Replacement string or callable taking a `re.Match`
    txt:str, # Markdown text
    skip_inline:bool=True, # Also skip inline backtick code spans?
)->str:
```

*Replace `pat` with `repl` in Markdown `txt`, skipping fenced and indented code blocks (and optionally inline code)*

[`md_sub`](xtras.md#md_sub) runs regex replacement on Markdown prose while leaving fenced code blocks (backticks or tildes, nested or indented up to 3 spaces), indented code blocks, and (by default) inline backtick spans untouched:

`````python
s = "Hi X and `X` and ``X ` X``\n\n````md\n```py\nX\n```\n````\n  ~~~py\nX\n  ~~~\n    X\nEnd X\n"
test_eq(md_sub('X', 'Y', s), "Hi Y and `X` and ``X ` X``\n\n````md\n```py\nX\n```\n````\n  ~~~py\nX\n  ~~~\n    X\nEnd Y\n")
test_eq(md_sub(r'`(\w+)`', lambda m: f'[{m[1]}]', "See `a`:\n```\n`b`\n```\n", skip_inline=False), "See [a]:\n```\n`b`\n```\n")
`````

[`_md_frontmatter`](xtras.md#_md_frontmatter) locates leading YAML `---` blocks, and [`_md_table_lines`](xtras.md#_md_table_lines) marks contiguous pipe-table line indices:

```python
_lines = ['---', 'title: Demo', '---', '', 'a|b', '-|-', '1|2']
test_eq(_md_frontmatter(_lines), (0, 2))
test_eq(_md_table_lines(_lines), {4, 5, 6})
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1240)

### MdBlock

```python
def MdBlock(
    kind:str, lines:list[str], start:int
):
```

*A contiguous block of lines in Markdown text (`kind` is `'fence'`, `'blank'`, `'block'`, or `'para'`).*

[`MdBlock`](xtras.md#mdblock) holds each contiguous segment, and [`_is_md_block_line`](xtras.md#_is_md_block_line) distinguishes structural Markdown lines (such as headings, lists, setext underlines, and tables) from plain prose:

```python
_ls = ['Title', '===', 'plain prose', '- item']
test_eq([_is_md_block_line(_ls, i, set(), (0, -1)) for i in range(len(_ls))], [True, True, False, True])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1257)

### md\_blocks

```python
def md_blocks(
    txt:str, # Markdown or docstring text to segment
)->list[__main__.MdBlock]: # Contiguous `MdBlock(kind, lines, start)` items covering every line of `txt`
```

*Segment Markdown `txt` into `'fence'`, `'blank'`, `'block'`, and plain-prose `'para'` blocks.*

[`md_blocks`](xtras.md#md_blocks) segments Markdown text into `'fence'`, `'blank'`, `'block'` (headings, YAML frontmatter, pipe tables, lists, blockquotes, indented code, doctests), and plain-prose `'para'` runs using [`_fence_step`](xtras.md#_fence_step):

````python
s = "---\ntitle: Demo\n---\n\nFirst line\nsecond line.\n\na|b\n-|-\n1|2\n\n```py\nnot\njoined\n```\n\n>>> 1 + 1\n2\n3\n\nHard break  \nkept."
blks = md_blocks(s)
expected = [('block',3),('blank',1),('para',2),('blank',1),('block',3),('blank',1),('fence',4),('blank',1),('block',3),('blank',1),('para',1),('para',1)]
test_eq([(b.kind, len(b.lines)) for b in blks], expected)
````

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1280)

### md\_unwrap

```python
def md_unwrap(
    txt:str, # Markdown or docstring text
)->str: # Text with hard-wrapped plain-prose paragraphs joined onto single lines
```

*Join hard-wrapped plain-prose paragraphs in `txt`, preserving fences and semantic Markdown blocks.*

[`md_unwrap`](xtras.md#md_unwrap) joins hard-wrapped `'para'` blocks onto single lines while keeping fences, tables, and trailing hard breaks intact:

```python
test_eq(md_unwrap(s).splitlines()[4], 'First line second line.')
assert 'a|b\n-|-\n1|2' in md_unwrap(s) and 'not\njoined' in md_unwrap(s) and 'Hard break  \nkept.' in md_unwrap(s)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1293)

### str\_diff

```python
def str_diff(
    a:str, # Original text
    b:str, # New text
    n:int=1, # Context lines around changes
    names:tuple=None, # Optional `(a_name,b_name)` labels; `---`/`+++` header omitted if None
)->str: # Unified diff, `''` when equal
```

*Unified diff of `a` and `b`*

[`str_diff`](xtras.md#str_diff) returns a unified diff as a plain string, or `''` when the texts match.

```python
test_eq(str_diff('a\nb\nc', 'a\nB\nc'), '@@ -1,3 +1,3 @@\n a\n-b\n+B\n c')
test_eq(str_diff('same', 'same'), '')
d = str_diff('x=1\n', 'x=2\n', names=('old.py','new.py'))
assert d.startswith('--- old.py\n+++ new.py\n')
assert '-x=1' in d and '+x=2' in d
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1305)

### utc2local

```python
def utc2local(
    dt:datetime.datetime
)->datetime.datetime:
```

*Convert `dt` from UTC to local time*

[`utc2local`](xtras.md#utc2local) converts a naive UTC `datetime` to local time:

```python
dt = datetime(2000,1,1,12)
print(f'{dt} UTC is {utc2local(dt)} local time')
```

```output
2000-01-01 12:00:00 UTC is 2000-01-01 22:00:00+10:00 local time
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1310)

### local2utc

```python
def local2utc(
    dt:datetime.datetime
)->datetime.datetime:
```

*Convert `dt` from local to UTC time*

```python
print(f'{dt} local is {local2utc(dt)} UTC time')
```

```output
2000-01-01 12:00:00 local is 2000-01-01 02:00:00+00:00 UTC time
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1315)

### trace

```python
def trace(
    f
):
```

*Add `set_trace` to an existing function `f`*

You can add a breakpoint to an existing function, e.g:

```python
Path.cwd = trace(Path.cwd)
Path.cwd()
```

Now, when the function is called it will drop you into the debugger.  Note, you must issue  the `s` command when you begin to step into the function that is being traced.

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1327)

### modified\_env

```python
def modified_env(
    *delete, **replace
):
```

*Context manager temporarily modifying `os.environ` by deleting `delete` and replacing `replace`*

[`modified_env`](xtras.md#modified_env) temporarily deletes or overrides `os.environ` keys for a `with` block and restores them on exit:

```python
env_test = 'USERNAME' if sys.platform == "win32" else 'SHELL'
oldusr = os.environ[env_test]

replace_param = {env_test: 'a'}
with modified_env('PATH', **replace_param):
    test_eq(os.environ[env_test], 'a')
    assert 'PATH' not in os.environ

assert 'PATH' in os.environ
test_eq(os.environ[env_test], oldusr)
```

[`ContextManagers`](xtras.md#contextmanagers) enters a list of context managers via `ExitStack` and exits all of them together:

```python
with ContextManagers([modified_env(_CM_A='1'), modified_env(_CM_B='2')]): test_eq((os.environ['_CM_A'], os.environ['_CM_B']), ('1', '2'))
assert '_CM_A' not in os.environ and '_CM_B' not in os.environ
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1339)

#### ContextManagers

```python
def ContextManagers(
    mgrs
):
```

*Wrapper for `contextlib.ExitStack` which enters a collection of context managers*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1346)

### shufflish

```python
def shufflish(
    x, pct:float=0.04
):
```

*Randomly relocate items of `x` up to `pct` of `len(x)` from their starting location*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1353)

### console\_help

```python
def console_help(
    libname:str
):
```

*Show help for all console scripts from `libname`*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1364)

### hl\_md

```python
def hl_md(
    s, lang:str='html', show:bool=True
):
```

*Syntax highlight `s` using `lang`.*

When we display code in a notebook, it's nice to highlight it, so we create a function to simplify that:

```python
hl_md('<test><xml foo="bar">a child</xml></test>')
```

```html
<test><xml foo="bar">a child</xml></test>
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1375)

### type2str

```python
def type2str(
    typ:type
)->str:
```

*Stringify `typ`*

[`type2str`](xtras.md#type2str) formats Python type objects and generics as concise strings:

```python
test_eq(type2str(Optional[float]), 'Union[float, None]')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1386)

### dataclass\_src

```python
def dataclass_src(
    cls
):
```

[`dataclass_src`](xtras.md#dataclass_src) renders a `@dataclass` definition as Python source:

```python
DC = make_dataclass('DC', [('x', int), ('y', Optional[float], None), ('z', float, None)])
print(dataclass_src(DC))
```

```output
@dataclass
class DC:
    x: int
    y: Union[float, None] = None
    z: float = None
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1394)

### nullable\_dc

```python
def nullable_dc(
    cls
):
```

*Like `dataclass`, but default of `UNSET` added to fields without defaults*

[`nullable_dc`](xtras.md#nullable_dc) turns a class into a dataclass whose fields without defaults default to `UNSET`:

```python
@nullable_dc
class Person: name: str; age: int; city: str = "Unknown"
Person(name="Bob")
```

```output
Person(name='Bob', age=UNSET, city='Unknown')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1401)

### make\_nullable

```python
def make_nullable(
    clas
):
```

[`make_nullable`](xtras.md#make_nullable) patches an existing dataclass so omitted `None`-defaulted fields initialize to `UNSET`:

```python
@dataclass
class Person: name: str; age: int; city: str = "Unknown"

make_nullable(Person)
Person("Bob", city='NY')
```

```output
Person(name='Bob', age=UNSET, city='NY')
```

```python
Person(name="Bob")
```

```output
Person(name='Bob', age=UNSET, city='Unknown')
```

```python
Person("Bob", 34)
```

```output
Person(name='Bob', age=34, city='Unknown')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1422)

### flexiclass

```python
def flexiclass(
    cls, # The class to convert
)-><function dataclass at 0x7d1298e1a840>:
```

*Convert `cls` into a `dataclass` like [`make_nullable`](xtras.md#make_nullable). Converts in place and also returns the result.*

This can be used as a decorator...

```python
@flexiclass
class Person: name: str; age: int; city: str = "Unknown"

bob = Person(name="Bob")
bob
```

```output
Person(name='Bob', age=UNSET, city='Unknown')
```

...or can update the behavior of an existing class (or dataclass):

```python
class Person: name: str; age: int; city: str = "Unknown"

flexiclass(Person)
bob = Person(name="Bob")
bob
```

```output
Person(name='Bob', age=UNSET, city='Unknown')
```

Action occurs in-place:

```python
class Person: name: str; age: int; city: str = "Unknown"

flexiclass(Person)
is_dataclass(Person)
```

```output
True
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1432)

### asdict

```python
def asdict(
    o
)->dict:
```

*Convert `o` to a `dict`, supporting dataclasses, namedtuples, iterables, and `__dict__` attrs.*

Any `UNSET` values are not included.

```python
asdict(bob)
```

```output
{'name': 'Bob', 'city': 'Unknown'}
```

Set the optional `__flds__` parameter to customise the field list, and the optional `__skip__` parameter to skip some names.

```python
class CustomObj:
    def __init__(self): self.a,self.b,self.c,self.d = 1,2,3,4
    __flds__ = ['a','b','c','d']
    __skip__ = ['b']

obj = CustomObj()
test_eq(asdict(obj), dict(a=1, c=3, d=4))
```

An object may be iterable without yielding key-value pairs; since `dict` can't consume it, [`asdict`](xtras.md#asdict) falls back to its instance attributes.

```python
class IterObj:
    def __init__(self): self.a,self.b = 1,2
    def __iter__(self): return iter([self.a,self.b])

test_eq(asdict(IterObj()), dict(a=1,b=2))
```

To customise dict conversion behavior for a class, implement the `_asdict` method (this is used in the Python stdlib for named tuples).

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1446)

### vars\_pub

```python
def vars_pub(
    x
):
```

*Get public non-skipped vars*

The [`vars_pub`](xtras.md#vars_pub) function returns a list of public (non-underscore-prefixed) variable names from an object, excluding any names listed in the object's optional `__skip__` attribute.

```python
class TestObj:
    def __init__(self): self.pub_attr,self._priv_attr,self.another_pub,self.skip_me = 1,2,3,4
    __skip__ = ['skip_me']

obj = TestObj()
test_eq(vars_pub(obj), ['pub_attr', 'another_pub'])
```

Without `__skip__`, all pub vars are returned

```python
class SimpleObj:
    def __init__(self): self.a,self._b,self.c = 1,2,3

simple = SimpleObj()
test_eq(vars_pub(simple), ['a', 'c'])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1452)

### is\_typeddict

```python
def is_typeddict(
    cls:type
)->bool:
```

*Check if `cls` is a `TypedDict`*

[`is_typeddict`](xtras.md#is_typeddict) checks whether a class is a `TypedDict`:

```python
class MyDict(TypedDict): name:str

assert is_typeddict(MyDict)
assert not is_typeddict({'a':1})
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1458)

### is\_namedtuple

```python
def is_namedtuple(
    cls
):
```

*`True` if `cls` is a namedtuple type*

```python
assert is_namedtuple(namedtuple('tst', ['a']))
assert not is_namedtuple(tuple)
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1463)

### CachedIter

```python
def CachedIter(
    o
):
```

*Cache the result returned by an iterator*

[`CachedIter`](xtras.md#cachediter) caches all yielded values and the final return value of an iterator on its first pass:

```python
def f():
    yield 1
    return 2

r = CachedIter(f())
for o in r: print(o)
r.value
```

```output
1
2
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1471)

### wrap\_sync\_async

```python
def wrap_sync_async(
    func, # Sync or async callable to wrap
    on_call, # Callback `on_call(execute, args, kwargs)` where `execute()` runs `func(*args, **kwargs)`
):
```

*Wrap sync or async `func` with `on_call(execute, args, kwargs)`, preserving metadata and sync/async calling convention*

[`wrap_sync_async`](xtras.md#wrap_sync_async) applies a single `on_call(execute, args, kwargs)` hook to either a regular function or a coroutine function without duplicating wrapper logic:

```python
seen = []
def _trace(ex, a, kw):
    seen.append((a, kw))
    return ex()
_add = wrap_sync_async(lambda x, y=1: x + y, _trace)
async def _aadd(x, y=1): return x + y
_aadd_w = wrap_sync_async(_aadd, _trace)
test_eq((_add(2, y=3), await _aadd_w(4, y=5)), (5, 9))
test_eq(seen, [((2,), {'y': 3}), ((4,), {'y': 5})])
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1486)

### LRUCache

```python
def LRUCache(
    maxsize:int=128
):
```

*Bounded least-recently-used cache backed by `OrderedDict`*

[`LRUCache`](xtras.md#lrucache) refreshes recency on reads (`[]`/`get`) and writes, evicting the oldest entry once `maxsize` is exceeded; `peek` inspects an entry without changing its recency:

```python
_c = LRUCache(maxsize=2)
_c['a'], _c['b'] = 1, 2
test_eq((_c.peek('a'), _c['a']), (1, 1))
_c['c'] = 3
test_eq(('a' in _c, 'b' in _c, 'c' in _c, len(_c)), (True, False, True, 2))
_c.clear()
test_eq(len(_c), 0)
```

### flexicache

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1509)

### flexicache

```python
def flexicache(
    *funcs, maxsize:int=128
):
```

*Like `lru_cache`, but customisable with policy `funcs`*

With no expiration policy, [`flexicache`](xtras.md#flexicache) acts as an LRU cache of size `maxsize`:

```python
@flexicache(maxsize=2)
def cached_func(x): return time()

time_1 = cached_func(1)
test_eq(time_1, cached_func(1))
time_2 = cached_func(2)
test_eq(time_1, cached_func(1))
test_eq(time_2, cached_func(2))
time_3 = cached_func(3)
```

Adding key `3` evicts the least recently used entry (`1`), while `2` and `3` remain cached:

```python
test_eq(time_2, cached_func(2))
test_eq(time_3, cached_func(3))
test_ne(time_1, cached_func(1))
test_ne(time_2, cached_func(2))
test_eq(cached_func(1), cached_func(1))
```

If recomputing an expired entry raises an exception, [`flexicache`](xtras.md#flexicache) returns the previous cached value while still raising on an uncached miss; once recomputation succeeds, the entry updates and moves to the most-recently-used end of the cache.

```python
v, exp = 1, False
@flexicache(lambda s: exp, maxsize=2)
def flaky(x):
    if v is None: raise RuntimeError('boom')
    return x, v
test_eq((flaky(1), flaky(2)), ((1, 1), (2, 1)))
exp, v = True, None
with expect_fail(RuntimeError, 'boom'): flaky(3)
test_eq(flaky(1), (1, 1))
```

```python
v = 2
test_eq((flaky(1), flaky(3)), ((1, 2), (3, 2)))
exp, v = False, 3
test_eq(flaky(1), (1, 2))
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1528)

### time\_policy

```python
def time_policy(
    seconds
):
```

*A [`flexicache`](xtras.md#flexicache) policy that expires cached items after `seconds` have passed*

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1536)

### mtime\_policy

```python
def mtime_policy(
    filepath=None, # File to watch, fixed at policy creation
    arg=None, # Or: positional index or keyword name of a call argument naming the file to watch
):
```

*A [`flexicache`](xtras.md#flexicache) policy that expires cached items after the watched file's modified-time changes*

[`flexicache`](xtras.md#flexicache) adds expiration policies to an LRU cache. [`time_policy`](xtras.md#time_policy) expires results after an interval; [`mtime_policy`](xtras.md#mtime_policy) expires them when a file changes. Call `cache_clear()` on the wrapped function to discard all cached results.

When caching a new result, [`flexicache`](xtras.md#flexicache) calls each policy with `None`. Return the state to save for that cache entry. On later lookups, [`flexicache`](xtras.md#flexicache) passes the saved state to the policy. Return a truthy value to expire the result, or a falsy value to reuse it. After recomputing an expired result, [`flexicache`](xtras.md#flexicache) calls each policy with `None` to save new state.

Set a policy's `needs_args=True` to receive `(state, args, kwargs)` instead. This lets `mtime_policy(arg=...)` watch a file named in the cached call's arguments.

```python
@flexicache(time_policy(10), mtime_policy('000_tour.ipynb'))
def cached_func(x, y): return x+y

cached_func(1,2)
```

```output
3
```

```python
@flexicache(time_policy(10), mtime_policy('000_tour.ipynb'))
async def cached_func(x, y): return x+y

print(await cached_func(1,2))
await cached_func(1,2)
```

```output
3
3
```

```python
@flexicache(mtime_policy(arg=0))
def slurp(p): return p.read_text()

with tempfile.TemporaryDirectory() as d:
    fp = Path(d)/'flexi-test.txt'
    fp.write_text('a')
    test_eq(slurp(fp), 'a')
    fp.write_text('b')
    os.utime(fp, (time()+1,)*2)
    test_eq(slurp(fp), 'b')
```

[`mtime_policy`](xtras.md#mtime_policy) also detects backward mtime changes and accepts a keyword argument name in `arg`:

```python
@flexicache(mtime_policy(arg='p'))
def slurp2(p=None): return p.read_text()

with tempfile.TemporaryDirectory() as d:
    fp = Path(d)/'flexi-test.txt'
    fp.write_text('b')
    test_eq(slurp2(p=fp), 'b')
    fp.write_text('c')
    os.utime(fp, (time()-1,)*2)
    test_eq(slurp2(p=fp), 'c')
```

[source](https://github.com/AnswerDotAI/fastcore/blob/main/fastcore/xtras.py#L1551)

### timed\_cache

```python
def timed_cache(
    seconds:int=60, maxsize:int=128
):
```

*Like `lru_cache`, but also with time-based eviction*

This function is a small convenience wrapper for using [`flexicache`](xtras.md#flexicache) with [`time_policy`](xtras.md#time_policy).

```python
@timed_cache(seconds=0.05, maxsize=2)
def cached_func(x): return x * 2, time()

result1, time1 = cached_func(2)
sleep(0.001)
result2, time2 = cached_func(2)
test_eq((result1, result2, time1), (4, 4, time2))
test_eq(cached_func(3)[0], 6)
_, time4 = cached_func(4)
test_close(time2, cached_func(2)[1], eps=0.1)
```

Entries evicted by `maxsize` or older than `seconds` recompute:

```python
_, time3_new = cached_func(3)
test_ne(time3_new, time())
sleep(0.05)
_, time4_new = cached_func(4)
test_ne(time4_new, time())
```
