Fileseq Python API

fileseq module

A Python library for parsing frame ranges and file sequences commonly used in VFX and Animation applications.

The MIT License (MIT)

Original work Copyright (c) 2015 Matthew Chambers

Modified work Copyright 2015 Justin Israel

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Frame Range Shorthand

Support for:

  • Standard: 1-10

  • Comma Delimited: 1-10,10-20

  • Chunked: 1-100x5

  • Filled: 1-100y5

  • Staggered: 1-100:3 (1-100x3, 1-100x2, 1-100)

  • Negative frame numbers: -10-100

  • Subframes: 1001-1066x0.25

  • Padding: #=4 padded, @=single pad

  • Printf Syntax Padding: %04d=4 padded, %01d=1 padded

  • Houdini Syntax Padding: $F4=4 padding, $F=1 padded

  • Udim Syntax Padding: <UDIM> or %(UDIM)d, always 4 padded

FrameSets

A FrameSet wraps a sequence of frames in a list list container.

Iterate a FrameSet

>>> fs = FrameSet("1-5")
>>> for f in fs:
...     print(f)
1
2
3
4
5

Access Frames Using Indices

>>> fs = FrameSet("1-100:8")
>>> fs[0] # First frame.
1
>>> fs[-1] # Last frame.
98

Access Frames Using Convenience Methods:

>>> fs = FrameSet("1-100:8")
>>> fs.start() # First frame.
1
>>> fs.end() # Last frame.
98

FileSequence

A FileSequence is a container representing a filepath over a range of frames

Instantiate from string

>>> FileSequence("/foo/bar.1-10#.exr")
<FileSequence: '/foo/bar.1-10#.exr'>

Format Path for VFX Software

Using FileSequence.format Method

>>> seq = FileSequence("/foo/bar.1-10#.exr")
>>> seq.format(template='{dirname}{basename}{padding}{extension}')
'/foo/bar.#.exr'
>>> seq = FileSequence("/foo/bar.1-10#.#.exr", allow_subframes=True)
>>> seq.format(template='{dirname}{basename}{padding}{extension}')
'/foo/bar.#.#.exr'

Joining

>>> seq = FileSequence("/foo/bar.1-10#.exr")
>>> seq.setPadding('%02d')
>>> seq
<FileSequence: '/foo/bar.1-10%02d.exr'>
>>> seq.format(template='{dirname}{basename}{padding}{extension}')
'/foo/bar.%02d.exr'

Get List of File Paths

>>> seq = FileSequence("/foo/bar.1-5#.exr")
>>> list(seq)
['/foo/bar.0001.exr',
 '/foo/bar.0002.exr',
 '/foo/bar.0003.exr',
 '/foo/bar.0004.exr',
 '/foo/bar.0005.exr']
>>> [seq[idx] for idx, fr in enumerate(seq.frameSet())]
['/foo/bar.0001.exr',
 '/foo/bar.0002.exr',
 '/foo/bar.0003.exr',
 '/foo/bar.0004.exr',
 '/foo/bar.0005.exr']

Finding Sequences on Disk

Check a Directory for All Existing Sequences

>>> seqs = findSequencesOnDisk("/show/shot/renders/bty_foo/v1")

Check a Directory for One Existing Sequence

  • Use a ‘@’ or ‘#’ where you might expect to use ‘*’ for a wildcard character.

  • For this method, it doesn’t matter how many instances of the padding character you use, it will still find your sequence (unless enabling strict padding option).

Yes:

findSequenceOnDisk('/foo/bar.@.exr')

Yes:

findSequenceOnDisk('/foo/bar.@@@@@.exr')

No:

findSequenceOnDisk('/foo/bar.*.exr')
  • To find subframe sequences you must explicitly opt-in

fileseq.findSequenceOnDisk('/foo/bar.#.#.exr', allow_subframes=True)

fileseq.exceptions module

exceptions - Exception subclasses relevant to fileseq operations.

exception fileseq.exceptions.FileSeqException[source]

Bases: ValueError

Thrown for general exceptions handled by FileSeq.

exception fileseq.exceptions.MaxSizeException[source]

Bases: ValueError

Thrown when a range exceeds allowable size.

exception fileseq.exceptions.ParseException[source]

Bases: FileSeqException

Thrown after a frame range or file sequence parse error.

fileseq.filesequence module

filesequence - A parsing object representing sequential files for fileseq.

class fileseq.filesequence.FileSequence(sequence: str, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>, allow_subframes: bool = False)[source]

Bases: object

FileSequence represents an ordered sequence of files.

Parameters:

sequence (str) – (ie: dir/path.1-100#.ext)

Return type:

FileSequence

Raises:
DISK_RE = re.compile('\n    \\A\n    ((?:.*[/\\\\])?)             # dirname\n    (.*?)                      # basename\n    (-?\\d+)?                   # frame\n    (                          # ext\n        (?:\\.\\w*[a-z, re.VERBOSE)
DISK_SUB_RE = re.compile('\n    \\A\n    ((?:.*[/\\\\])?)             # dirname\n    (.*?)                      # basename\n    (-?\\d+(?:\\.\\d+)?)?         # frame\n    (                          # ext\n        (?:\\.\\w*[a, re.VERBOSE)
PAD_MAP = {'#': {<PAD_STYLE: HASH1>: 1, <PAD_STYLE: HASH4>: 4}, '@': {<PAD_STYLE: HASH1>: 1, <PAD_STYLE: HASH4>: 1}}
REVERSE_PAD_MAP = {<PAD_STYLE: HASH1>: {1: '#'}, <PAD_STYLE: HASH4>: {1: '@', 4: '#'}}
SPLIT_RE = re.compile('\n    ((?:\n    -?\\d+           # start frame\n    (?:             # optional range\n        -           #   range delimiter\n        -?\\d+       #   end frame\n        (?:         #   optional ste, re.VERBOSE)
SPLIT_SUB_RE = re.compile('\n    (                         # range\n        (?:\n            (?:\n    -?\\d+           # start frame\n    (?:             # optional range\n        -           #   range delimiter\n        -?\\d, re.VERBOSE)
__getitem__(idx)[source]

Allows indexing and slicing into the underlying FrameSet

When indexing, a string filepath is returns for the frame.

When slicing, a new FileSequence is returned. Slicing outside the range of the sequence results in an IndexError

Parameters:

idx (int or slice) – the desired index

Return type:

str or FileSequence

Raises:

IndexError – If slice is outside the range of the sequence

__iter__()[source]

Allow iteration over the path or paths this FileSequence represents.

Yields:

FileSequence

__len__()[source]

The length (number of files) represented by this FileSequence.

Return type:

int

basename() str[source]

Return the basename of the sequence.

Returns:

sequence basename

Return type:

str

batches(batch_size: int, paths: bool = False) Iterable[str | FileSequence][source]

Returns a generator that yields groups of file paths, up to batch_size. Convenience method for fileseq.utils.batchIterable(self, batch_size) If paths=False, each batch is a new FileSequence subrange. If paths=True, each batch is an islice generator object of each file path in the subrange.

Parameters:
  • batch_size (int) – max file paths in each batch

  • paths (bool) – if True, generate individual file paths instead of FileSequences

Returns:

yields batches of file paths or FileSequence subranges of sequence

Return type:

generator

classmethod conformPadding(chars: str, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>) str[source]

Ensure alternate input padding formats are conformed to formats defined in PAD_MAP

If chars is already a format defined in PAD_MAP, then it is returned unmodified.

Example::

‘#’ -> ‘#’ ‘@@@@’ -> ‘@@@@’ ‘%04d’ -> ‘#’

Parameters:
  • chars (str) – input padding chars

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

Returns:

conformed padding chars

Return type:

str

Raises:

ValueError – If chars contains invalid padding characters

copy() Self[source]

Create a deep copy of this sequence

Return type:

FileSequence

decimalPlaces() int[source]

Returns the number of decimal places to output.

Return type:

int or None

dirname() str[source]

Return the directory name of the sequence.

Return type:

str

end() int[source]

Returns the end frame of the sequences FrameSet. Will return 0 if the sequence has no frame pattern.

Return type:

int

extension() str[source]

Return the file extension of the sequence, including leading period.

Return type:

str

classmethod findSequenceOnDisk(pattern: str, strictPadding: bool = False, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>, allow_subframes: bool = False, force_case_sensitive: bool = True, preserve_padding: bool = False) FileSequence[source]

Search for a specific sequence on disk.

The padding characters used in the pattern are used to filter the frame values of the files on disk (if strictPadding is True).

Case-sensitive matching follows POSIX behavior, even on Windows platforms. “file.1.png” and “file.2.PNG” result in two different sequences. This behavior can be disabled on Windows by setting force_case_sensitive=False.

By default, the returned sequence will use the “#@” padding character format. If preserve_padding=True, then preserve the original pattern padding character format, as long as the padding length matches the existing sequence. In the case of strictPadding=False and the original padding length not matching the existing sequence, then the “#@” format will still be used in the result.

Examples

Find sequence matching basename and extension, and a wildcard for any frame. returns bar.1.exr bar.10.exr, bar.100.exr, bar.1000.exr, inclusive:

FileSequence.findSequenceOnDisk("seq/bar@@@@.exr")

Find exactly 4-padded sequence, i.e. seq/bar1-100#.exr returns only frames bar1000.exr through bar9999.exr

FileSequence.findSequenceOnDisk("seq/bar#.exr", strictPadding=True)

Find exactly 3-padded sequence, i.e. seq/bar1-3%03d.exr and return sequence that preserves the original printf padding format

FileSequence.findSequenceOnDisk("seq/bar%03d.exr", strictPadding=True, preserve_padding=True)

Note

Unlike findSequencesOnDisk, general wildcard characters (“*”, “?”) are not supported and result in undefined behavior. Only the frame component of the paths may be replaced with padding characters to serve as a limited wildcard.

Parameters:
  • pattern (str) – the sequence pattern being searched for

  • strictPadding (bool) – if True, ignore files with padding length different from pattern

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

  • allow_subframes (bool) – if True, handle subframe filenames

  • force_case_sensitive (bool) – force posix-style case-sensitive matching on Windows filesystems

  • preserve_padding (bool) – if True, preserve pattern-provided padding characters in returned sequence, if the padding length matches. Default: conform padding to “#@” style.

Returns:

A single matching file sequence existing on disk

Return type:

FileSequence

Raises:

.FileSeqException – if no sequence is found on disk

classmethod findSequencesInList(paths: ~typing.Iterable[str], pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>, allow_subframes: bool = False) list[FileSequence][source]

Returns the list of discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that.

Parameters:
  • paths (list[str]) – a list of paths

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

  • allow_subframes (bool) – if True, handle subframe filenames

Return type:

list

classmethod findSequencesOnDisk(pattern: str, include_hidden: bool = False, strictPadding: bool = False, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>, allow_subframes: bool = False) list[FileSequence][source]

Yield the sequences found in the given directory.

Examples:

FileSequence.findSequencesOnDisk('/path/to/files')
The pattern can also specify glob-like shell wildcards including the following:
  • ? - 1 wildcard character

  • * - 1 or more wildcard character

  • {foo,bar} - either ‘foo’ or ‘bar’

Exact frame ranges are not considered, and padding characters are converted to wildcards (# or @)

Case-sensitive matching follows POSIX behavior, even on Windows platforms. “file.1.png” and “file.2.PNG” result in two different sequences.

Examples:

FileSequence.findSequencesOnDisk('/path/to/files/image_stereo_{left,right}.#.jpg')
FileSequence.findSequencesOnDisk('/path/to/files/imag?_*_{left,right}.@@@.jpg', strictPadding=True)
Parameters:
  • pattern (str) – directory to scan, or pattern to filter in directory

  • include_hidden (bool) – if true, show .hidden files as well

  • strictPadding (bool) – if True, ignore files with padding length different from pattern

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

  • allow_subframes (bool) – if True, handle subframe filenames

Return type:

list

format(template='{basename}{range}{padding}{extension}') str[source]

Return the file sequence as a formatted string according to the given template.

Utilizes the python string format syntax. Available keys include:
  • basename - the basename of the sequence.

  • range - the range of the sequence

  • padding - the detecting amount of padding.

  • extension - the file extension of the sequence.

  • start - the start frame.

  • end - the end frame.

  • length - the length of the frame range.

  • inverted - the inverted frame range. (returns “” if none)

  • dirname - the directory name.

If asking for the inverted range value, and the new inverted range exceeded fileseq.constants.MAX_FRAME_SIZE, a MaxSizeException will be raised.

Parameters:

template (str) –

Return type:

str

Raises:
frame(frame: int | float | Decimal | str) str[source]

Return a path for the given frame in the sequence. Numeric values or numeric strings are treated as a frame number and padding is applied, all other values are passed though.

Examples

>>> seq = FileSequence('/foo/bar.1-10#.exr')
>>> seq.frame(1)
'/foo/bar.0001.exr'
>>> seq.frame("#")
'/foo/bar.#.exr'
Parameters:

frame (int, float, decimal.Decimal or str) – the desired frame number or a char to pass through (ie. #)

Return type:

str

framePadding() str[source]

Return the padding characters in the sequence.

Returns:

sequence padding

Return type:

str

frameRange() str[source]

Returns the string formatted frame range of the sequence. Will return an empty string if the sequence has no frame pattern.

Return type:

str

frameSet() FrameSet | None[source]

Return the FrameSet of the sequence if specified, otherwise None.

Return type:

FrameSet or None

classmethod from_dict(state: dict) FileSequence[source]

Constructor to create a new sequence object from a state that was previously returned by FileSequence.to_dict()

Parameters:

state (dict) – state returned from FileSequence.to_dict()

Returns:

FileSequence

classmethod getPaddingChars(num: int, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>) str[source]

Given a particular amount of padding, return the proper padding characters.

Parameters:
  • num (int) – required width of string with padding

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

Return type:

str

classmethod getPaddingNum(chars: str, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>) int[source]

Given a supported group of padding characters, return the amount of padding.

Parameters:
  • chars (str) – a supported group of padding characters

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

Return type:

int

Raises:

ValueError – if unsupported padding character is detected

index(idx: int) str[source]

Return the path to the file at the given index.

Parameters:

idx (int) – the desired index

Return type:

str

invertedFrameRange() str[source]

Returns the inverse string formatted frame range of the sequence. Will return an empty string if the sequence has no frame pattern, or the frame range includes subframes.

Return type:

str

Raises:

fileseq.exceptions.MaxSizeException – If new inverted range exceeded fileseq.constants.MAX_FRAME_SIZE

padStyle() _PadStyle[source]

Return the padding style of the sequence. See fileseq.constants.PAD_STYLE_HASH1 and fileseq.constants.PAD_STYLE_HASH4

Returns:

padding style

Return type:

(PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4)

padding() str[source]

Return the padding characters in the sequence.

Returns:

sequence padding

Return type:

str

setBasename(base: str)[source]

Set a new basename for the sequence.

Parameters:

base (str) – the new base name

setDirname(dirname: str)[source]

Set a new directory name for the sequence.

Parameters:

dirname (str) – the new directory name

setExtension(ext: str)[source]

Set a new file extension for the sequence.

Note

A leading period will be added if none is provided.

Parameters:

ext (str) – the new file extension

setExtention(ext: str)[source]

Deprecated: use setExtension().

Parameters:

ext (str) –

setFramePadding(padding: str)[source]

Set new padding characters for the frames of the sequence. i.e. “#” or “@@@” or ‘%04d’, or an empty string to disable range formatting.

Parameters:

padding (str) – sequence padding to set

Raises:

ValueError – if unrecognized padding characters are provided

setFrameRange(frange)[source]

Set a new frame range for the sequence.

Parameters:

frange (str) – a properly formatted frame range, as per FrameSet

setFrameSet(frameSet: FrameSet | None)[source]

Set a new FrameSet for the sequence.

Parameters:

frameSet (FrameSet) – the new FrameSet object

setPadStyle(pad_style: _PadStyle, set_zfill: bool = False)[source]

Set new padding style for the sequence. See fileseq.constants.PAD_STYLE_HASH1 and fileseq.constants.PAD_STYLE_HASH4

The default behavior converts only the padding characters representation per the new style, the same zfill/decimalPlaces value. If set_zfill=True, convert the zfill/decimalPlaces values to match the meaning of the padding characters per the new style.

Parameters:
  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style to set

  • set_zfill (bool) – If True, convert zfill/decimalPlaces value instead of padding chars

setPadding(padding: str)[source]

Set new padding characters for the sequence. i.e. “#” or “@@@” or ‘%04d’, or an empty string to disable range formatting.

Parameters:

padding (str) – sequence padding to set

Raises:

ValueError – if unrecognized padding characters are provided

setSubframePadding(padding: str)[source]

Set new padding characters for the subframes in the sequence. i.e. “#” or “@@@”, or an empty string to disable range formatting.

Parameters:

padding (str) – sequence padding to set

Raises:

ValueError – if unrecognized padding characters are provided

split() list[Self][source]

Split the FileSequence into contiguous pieces and return them as a list of FileSequence instances.

Return type:

list[FileSequence]

start() int[source]

Returns the start frame of the sequence’s FrameSet. Will return 0 if the sequence has no frame pattern.

Return type:

int

subframePadding() str[source]

Return the padding characters for subframes in the sequence.

Returns:

sequence padding

Return type:

str

to_dict() dict[source]

Convert sequence object into a state dict that is suitable for further serialization, such as to JSON

Returns:

state of the current sequence object

Return type:

dict

classmethod yield_sequences_in_list(paths: ~typing.Iterable[str], using: ~fileseq.filesequence.FileSequence | None = None, pad_style: ~fileseq.constants._PadStyle = <PAD_STYLE: HASH4>, allow_subframes: bool = False) Iterator[FileSequence][source]

Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that.

A template FileSequence object can also be provided via the using parameter. Given this template, the dirname, basename, and extension values will be used to extract the frame value from the paths instead of parsing each path from scratch.

Examples

The using field can supply a template for extracting the frame component from the paths:

paths = [
    '/dir/file_001.0001.ext',
    '/dir/file_002.0001.ext',
    '/dir/file_003.0001.ext',
]
template = FileSequence('/dir/file_#.0001.ext')
seqs = FileSequence.yield_sequences_in_list(paths, using)
# [<FileSequence: '/dir/file_1-3@@@.0001.ext'>]
Parameters:
  • paths (list[str]) – a list of paths

  • using (FileSequence) – Optional sequence to use as template

  • pad_style (PAD_STYLE_DEFAULT or PAD_STYLE_HASH1 or PAD_STYLE_HASH4) – padding style

  • allow_subframes (bool) – if True, handle subframe filenames

Yields:

FileSequence

zfill() int[source]

Returns the zfill depth (ie the number of zeroes to pad with).

Return type:

int

fileseq.frameset module

frameset - A set-like object representing a frame range for fileseq.

class fileseq.frameset.FrameSet(*args, **kwargs)[source]

Bases: Set

A FrameSet is an immutable representation of the ordered, unique set of frames in a given frame range.

The frame range can be expressed in the following ways:
  • 1-5

  • 1-5,10-20

  • 1-100x5 (every fifth frame)

  • 1-100y5 (opposite of above, fills in missing frames)

  • 1-100:4 (same as 1-100x4,1-100x3,1-100x2,1-100)

  • 1-2x0.333333 (subframes)

A FrameSet is effectively an ordered frozenset, with FrameSet-returning versions of frozenset methods:

>>> FrameSet('1-5').union(FrameSet('5-10'))
FrameSet("1-10")
>>> FrameSet('1-5').intersection(FrameSet('5-10'))
FrameSet("5")

Because a FrameSet is hashable, it can be used as the key to a dictionary:

>>> d = {FrameSet("1-20"): 'good'}

A FrameSet can be created from an iterable of frame numbers, and will construct an appropriate string representation:

>>> FrameSet([1,2,3,4,5]).frange
'1-5'
>>> FrameSet([0, '0.1429', '0.2857', '0.4286', '0.5714', '0.7143', '0.8571', 1]).frange
'0-1x0.142857'
Caveats:
  1. Because the internal storage of a FrameSet contains the discreet values of the entire range, an exception will be thrown if the range exceeds a large reasonable limit, which could lead to huge memory allocations or memory failures. See fileseq.constants.MAX_FRAME_SIZE.

  2. All frozenset operations return a normalized FrameSet: internal frames are in numerically increasing order.

  3. Equality is based on the contents and order, NOT the frame range string (there are a finite, but potentially extremely large, number of strings that can represent any given range, only a “best guess” can be made).

  4. Human-created frame ranges (ie 1-100x5) will be reduced to the actual internal frames (ie 1-96x5).

  5. The “null” Frameset (FrameSet('')) is now a valid thing to create, it is required by set operations, but may cause confusion as both its start and end methods will raise IndexError. The is_null() property allows you to guard against this.

Parameters:
  • str (frange (str or FrameSet or collections.Iterable of) – decimal.Decimal): the frame range as a string (ie “1-100x5”) or iterable of frame numbers.

  • int – decimal.Decimal): the frame range as a string (ie “1-100x5”) or iterable of frame numbers.

  • float – decimal.Decimal): the frame range as a string (ie “1-100x5”) or iterable of frame numbers.

  • or – decimal.Decimal): the frame range as a string (ie “1-100x5”) or iterable of frame numbers.

Raises:
  • .ParseException – if the frame range (or a portion of it) could not be parsed.

  • fileseq.exceptions.MaxSizeException – if the range exceeds fileseq.constants.MAX_FRAME_SIZE

FRANGE_RE = re.compile('\n    \\A\n    (-?\\d+(?:\\.\\d+)?)         # start frame\n    (?:                       # optional range\n        -                     #   range delimiter\n        (-?\\d+(?:\\.\\d+)?)     #   end , re.VERBOSE)
PAD_MAP = {'#': {<PAD_STYLE: HASH1>: 1, <PAD_STYLE: HASH4>: 4}, '@': {<PAD_STYLE: HASH1>: 1, <PAD_STYLE: HASH4>: 1}}
PAD_RE = re.compile('\n    (-?)(\\d+(?:\\.\\d+)?)     # start frame\n    (?:                     # optional range\n        (-)                 #   range delimiter\n        (-?)(\\d+(?:\\.\\d+)?) #   end frame\n        (?, re.VERBOSE)
__and__(other)[source]

Overloads the & operator. Returns a new FrameSet that holds only the frames self and other have in common.

Note

The order of operations is irrelevant: (self & other) == (other & self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__contains__(item)[source]

Check if item is a member of this FrameSet.

Parameters:

item (int) – the frame number to check for

Return type:

bool

__eq__(other)[source]

Check if self == other via a comparison of the hash of their contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Parameters:

other (FrameSet) – Also accepts an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__ge__(other)[source]

Check if self >= other via a comparison of the contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Parameters:

other (FrameSet) – Also accepts an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__getitem__(index)[source]

Allows indexing into the ordered frames of this FrameSet.

Parameters:

index (int) – the index to retrieve

Return type:

int

Raises:

IndexError – if index is out of bounds

__getstate__()[source]

Allows for serialization to a pickled FrameSet.

Returns:

(frame range string, )

Return type:

tuple

__gt__(other)[source]

Check if self > other via a comparison of the contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Note

A FrameSet is greater than other if the set of its contents are greater, OR if the contents are equal but the order is greater.

Same contents, but (1,2,3,4,5) sorts below (5,4,3,2,1)
>>> FrameSet("1-5") > FrameSet("5-1")
False
Parameters:

other (FrameSet) – Also accepts an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__hash__()[source]

Builds the hash of this FrameSet for equality checking and to allow use as a dictionary key.

Return type:

int

__iter__()[source]

Allows for iteration over the ordered frames of this FrameSet.

Return type:

generator

__le__(other)[source]

Check if self <= other via a comparison of the contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Parameters:

other (FrameSet) – Also accepts an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__len__()[source]

Returns the length of the ordered frames of this FrameSet.

Return type:

int

__lt__(other)[source]

Check if self < other via a comparison of the contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Note

A FrameSet is less than other if the set of its contents are less, OR if the contents are equal but the order of the items is less.

Same contents, but (1,2,3,4,5) sorts below (5,4,3,2,1)
>>> FrameSet("1-5") < FrameSet("5-1")
True
Parameters:

other (FrameSet) – Can also be an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__ne__(other)[source]

Check if self != other via a comparison of the hash of their contents. If other is not a FrameSet, but is a set, frozenset, or is iterable, it will be cast to a FrameSet.

Parameters:

other (FrameSet) – Also accepts an object that can be cast to a FrameSet

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

__or__(other)[source]

Overloads the | operator. Returns a new FrameSet that holds all the frames in self, other, or both.

Note

The order of operations is irrelevant: (self | other) == (other | self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__rand__(other)

Overloads the & operator. Returns a new FrameSet that holds only the frames self and other have in common.

Note

The order of operations is irrelevant: (self & other) == (other & self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__repr__()[source]

Returns a long-form representation of this FrameSet.

Return type:

str

__reversed__()[source]

Allows for reversed iteration over the ordered frames of this FrameSet.

Return type:

generator

__ror__(other)

Overloads the | operator. Returns a new FrameSet that holds all the frames in self, other, or both.

Note

The order of operations is irrelevant: (self | other) == (other | self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__rsub__(other)[source]

Overloads the - operator. Returns a new FrameSet that holds only the frames of other that are not in self.

Note

This is for right-hand subtraction (other - self).

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__rxor__(other)

Overloads the ^ operator. Returns a new FrameSet that holds all the frames in self or other but not both.

Note

The order of operations is irrelevant: (self ^ other) == (other ^ self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__setstate__(state)[source]

Allows for de-serialization from a pickled FrameSet.

Parameters:

state (tuple or str or dict) – A string/dict can be used for backwards compatibility

Raises:

ValueError – if state is not an appropriate type

__str__()[source]

Returns the frame range string of this FrameSet.

Return type:

str

__sub__(other)[source]

Overloads the - operator. Returns a new FrameSet that holds only the frames of self that are not in other.

Note

This is for left-hand subtraction (self - other).

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

__xor__(other)[source]

Overloads the ^ operator. Returns a new FrameSet that holds all the frames in self or other but not both.

Note

The order of operations is irrelevant: (self ^ other) == (other ^ self)

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

FrameSet

batches(batch_size: int, frames: bool = False) Iterator[source]

Returns a generator that yields sub-batches of frames, up to batch_size. If frames=False, each batch is a new FrameSet subrange. If frames=True, each batch is an islice generator object of the sub-range.

Parameters:
  • batch_size (int) – max frame values in each batch

  • frames (bool) – if True, generate islice sub-ranges instead of FrameSets

Returns:

yields batches of islice or FrameSet sub-ranges

Return type:

generator

copy() FrameSet[source]

Create a deep copy of this FrameSet.

Return type:

FrameSet

difference(*other) FrameSet[source]

Returns a new FrameSet with elements in self but not in other.

Parameters:

other (FrameSet) – or objects that can cast to FrameSet

Return type:

FrameSet

end() int[source]

The last frame in the FrameSet.

Return type:

int

Raises:

IndexError – (with the empty FrameSet)

frame(index: int) int[source]

Return the frame at the given index.

Parameters:

index (int) – the index to find the frame for

Return type:

int

Raises:

IndexError – if index is out of bounds

frameRange(zfill: int = 0, decimal_places: int | None = None) str[source]

Return the frame range used to create this FrameSet, padded if desired.

Examples

>>> FrameSet('1-100').frameRange()
'1-100'
>>> FrameSet('1-100').frameRange(5)
'00001-00100'
>>> FrameSet('1-100').frameRange(0, 1)
'1.0-100.0'
>>> FrameSet('1.0-100.0').frameRange()
'1.0-100.0'
Parameters:
  • zfill (int) – the width to use to zero-pad the frame range string

  • decimal_places (int or None) – the number of decimal places to use in frame range string

Return type:

str

static framesToFrameRange(frames: Iterable, sort: bool = True, zfill: int = 0, compress: bool = False) str[source]

Converts an iterator of frames into a frame range string.

Parameters:
  • frames (collections.Iterable) – sequence of frames to process

  • sort (bool) – sort the sequence before processing

  • zfill (int) – width for zero padding

  • compress (bool) – remove any duplicates before processing

Return type:

str

static framesToFrameRanges(frames: Iterable, zfill: int = 0) Iterator[str][source]

Converts a sequence of frames to a series of padded frame range strings.

Parameters:
  • frames (collections.Iterable) – sequence of frames to process

  • zfill (int) – width for zero padding

Yields:

str

property frange: str

Read-only access to the frame range used to create this FrameSet.

Return type:

str

classmethod from_iterable(frames: Iterable[int], sort: bool = False) FrameSet[source]

Build a FrameSet from an iterable of frames.

Parameters:
  • frames (collections.Iterable) – an iterable object containing frames as integers

  • sort (bool) – True to sort frames before creation, default is False

Return type:

FrameSet

classmethod from_range(start: int, end: int, step: int = 1) FrameSet[source]

Build a FrameSet from given start and end frames (inclusive).

Parameters:
  • start (int) – The first frame of the FrameSet.

  • end (int) – The last frame of the FrameSet.

  • step (int, optional) – Range step (default 1).

Return type:

FrameSet

hasFrame(frame: int) bool[source]

Check if the FrameSet contains the frame or subframe

Parameters:

frame (int) – the frame number to search for

Return type:

bool

hasSubFrames() bool[source]

Check if the FrameSet contains any subframes

Return type:

bool

index(frame: int) int[source]

Return the index of the given frame number within the FrameSet.

Parameters:

frame (int) – the frame number to find the index for

Return type:

int

Raises:

ValueError – if frame is not in self

intersection(*other) FrameSet[source]

Returns a new FrameSet with the elements common to self and other.

Parameters:

other (FrameSet) – or objects that can cast to FrameSet

Return type:

FrameSet

invertedFrameRange(zfill: int = 0, decimal_places: int | None = None) str[source]

Return the inverse of the FrameSet ‘s frame range, padded if desired. The inverse is every frame within the full extent of the range.

Examples

>>> FrameSet('1-100x2').invertedFrameRange()
'2-98x2'
>>> FrameSet('1-100x2').invertedFrameRange(5)
'00002-00098x2'

If the inverted frame size exceeds fileseq.constants.MAX_FRAME_SIZE, a MaxSizeException will be raised.

Parameters:
  • zfill (int) – the width to use to zero-pad the frame range string

  • decimal_places (int or None) – the number of decimal places to use in frame range string

Return type:

str

Raises:

fileseq.exceptions.MaxSizeException

isConsecutive() bool[source]

Return whether the frame range represents consecutive integers, as opposed to having a stepping >= 2

Examples

>>> FrameSet('1-100').isConsecutive()
True
>>> FrameSet('1-100x2').isConsecutive()
False
>>> FrameSet('1-50,60-100').isConsecutive()
False
Return type:

bool

classmethod isFrameRange(frange: str) bool[source]

Return True if the given string is a frame range. Any padding characters, such as ‘#’ and ‘@’ are ignored.

Parameters:

frange (str) – a frame range to test

Return type:

bool

property is_null: bool

Read-only access to determine if the FrameSet is the null or empty FrameSet.

Return type:

bool

isdisjoint(other) bool | NotImplemented[source]

Check if the contents of :class:self has no common intersection with the contents of :class:other.

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

issubset(other) bool | NotImplemented[source]

Check if the contents of self is a subset of the contents of other.

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

issuperset(other) bool | NotImplemented[source]

Check if the contents of self is a superset of the contents of other.

Parameters:

other (FrameSet) –

Returns:

NotImplemented: if other fails to convert to a FrameSet

Return type:

bool

property items: frozenset[int]

Read-only access to the unique frames that form this FrameSet.

Return type:

frozenset

normalize() FrameSet[source]

Returns a new normalized (sorted and compacted) FrameSet.

Return type:

FrameSet

property order: tuple[int, ...]

Read-only access to the ordered frames that form this FrameSet.

Return type:

tuple

classmethod padFrameRange(frange: str, zfill: int, decimal_places: int | None = None) str[source]

Return the zero-padded version of the frame range string.

Parameters:
  • frange (str) – a frame range to test

  • zfill (int) –

  • decimal_places (int or None) –

Return type:

str

start() int[source]

The first frame in the FrameSet.

Return type:

int

Raises:

IndexError – (with the empty FrameSet)

symmetric_difference(other) FrameSet[source]

Returns a new FrameSet that contains all the elements in either self or other, but not both.

Parameters:

other (FrameSet) –

Return type:

FrameSet

union(*other) FrameSet[source]

Returns a new FrameSet with the elements of self and of other.

Parameters:

other (FrameSet) – or objects that can cast to FrameSet

Return type:

FrameSet

fileseq.utils module

utils - General tools of use to fileseq operations.

fileseq.utils.asString(obj)[source]

Ensure an object is either explicitly str or unicode and not some derived type that can change semantics.

If the object is unicode, return unicode. Otherwise, return the string conversion of the object.

Parameters:

obj – Object to return as str or unicode

Return type:

str or unicode

fileseq.utils.batchFrames(start, stop, batch_size)[source]

Returns a generator that yields batches of frames from start to stop, inclusive. Each batch value is a range generator object, also providing start, stop, and step properties. The last batch frame length may be smaller if the batches cannot be divided evenly.

start value is allowed to be greater than stop value, to generate decreasing frame values.

Parameters:
  • start (int) – start frame value

  • stop (int) – stop frame value

  • batch_size (int) – max size of each batch

Yields:

range(sub_start, sub_stop)

fileseq.utils.batchIterable(it, batch_size)[source]

Returns a generator that yields batches of items returned by the given iterable. The last batch frame length may be smaller if the batches cannot be divided evenly.

Parameters:
  • it (iterable) – An iterable from which to yield batches of values

  • batch_size (int) – max size of each batch

Yields:

iterable – a subset of batched items

fileseq.utils.lenRange(start, stop, step=1)[source]

Get the length of values for a given range, exclusive of the stop

Parameters:
  • start (int) –

  • stop (int) –

  • step (int) –

fileseq.utils.normalizeFrame(frame)[source]

Convert a frame number to the most appropriate type - the most compact type that doesn’t affect precision, for example numbers that convert exactly to integer values will be converted to int

Parameters:

frame (int, float, decimal.Decimal, str) – frame number to normalize

Return type:

frame (int, float, or decimal.Decimal)

fileseq.utils.normalizeFrames(frames: Iterable[Any]) list[source]

Convert a sequence of frame numbers to the most appropriate type for the overall sequence, where all members of the result are of the same type.

Parameters:

frames (iterable of int, float, decimal.Decimal, or str) – frame numbers to normalize

Return type:

frames (iterable of int, float, or decimal.Decimal)

fileseq.utils.pad(number, width=0, decimal_places=None)[source]

Return the zero-padded string of a given number.

Parameters:
  • number (str, int, float, or decimal.Decimal) – the number to pad

  • width (int) – width for zero padding the integral component

  • decimal_places (int) – number of decimal places to use in frame range

Return type:

str

fileseq.utils.quantize(number, decimal_places, rounding='ROUND_HALF_EVEN')[source]

Round a decimal value to given number of decimal places

Parameters:
Return type:

decimal.Decimal

fileseq.utils.unique(seen, *iterables)[source]

Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used.

Parameters:
  • seen (set) – either an empty set, or the set of things already seen

  • *iterables – one or more iterable lists to chain together

Return type:

generator

fileseq.utils.xfrange(start, stop, step=1, maxSize=-1)[source]

Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value.

Parameters:
  • start (int) –

  • stop (int) –

  • step (int) – Note that the sign will be ignored

  • maxSize (int) –

Return type:

generator

Raises:

fileseq.exceptions.MaxSizeException – if size is exceeded

class fileseq.utils.xrange2(start, stop=None, step=1)[source]

Bases: object

An itertools-based replacement for xrange which does not exhibit the OverflowError issue on some platforms, when a value exceeds a C long size.

Provides the features of an islice, with the added support for checking the length of the range.

property start
property step
property stop