vistir.compat module

class vistir.compat.Path[source]

Bases: pathlib.PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

absolute()[source]

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

chmod(mode)[source]

Change the permissions of the path, like os.chmod().

classmethod cwd()[source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()[source]

Whether this path exists.

expanduser()[source]

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)[source]

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()[source]

Return the group name of the file gid.

classmethod home()[source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()[source]

Whether this path is a block device.

is_char_device()[source]

Whether this path is a character device.

is_dir()[source]

Whether this path is a directory.

is_fifo()[source]

Whether this path is a FIFO.

is_file()[source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source]

Check if this path is a POSIX mount point

is_socket()[source]

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()[source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)[source]

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

lstat()[source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)[source]

Create a new directory at this given path.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source]

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()[source]

Return the login name of the file owner.

read_bytes()[source]

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source]

Open the file in text mode, read it, and close the file.

rename(target)[source]

Rename this path to the given path.

replace(target)[source]

Rename this path to the given path, clobbering the existing destination if it exists.

resolve(strict=False)[source]

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

rglob(pattern)[source]

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()[source]

Remove this directory. The directory must be empty.

samefile(other_path)[source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat()[source]

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink’s.

touch(mode=438, exist_ok=True)[source]

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)[source]

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None)[source]

Open the file in text mode, write to it, and close the file.

vistir.compat.get_terminal_size(fallback=(80, 24))[source]

Get the size of the terminal window.

For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used.

When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size.

If the terminal size cannot be successfully queried, either because the system doesn’t support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators.

The value returned is a named tuple of type os.terminal_size.

class vistir.compat.finalize(obj, func, *args, **kwargs)[source]

Bases: object

Class for finalization of weakrefable objects

finalize(obj, func, *args, **kwargs) returns a callable finalizer object which will be called when obj is garbage collected. The first time the finalizer is called it evaluates func(*arg, **kwargs) and returns the result. After this the finalizer is dead, and calling it just returns None.

When the program exits any remaining finalizers for which the atexit attribute is true will be run in reverse order of creation. By default atexit is true.

alive

Whether finalizer is alive

atexit

Whether finalizer should be called at exit

detach()[source]

If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None

peek()[source]

If alive then return (obj, func, args, kwargs); otherwise return None

class vistir.compat.partialmethod(func, *args, **keywords)[source]

Bases: object

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

exception vistir.compat.JSONDecodeError(msg, doc, pos)[source]

Bases: ValueError

Subclass of ValueError with the following additional properties:

msg: The unformatted error message doc: The JSON document being parsed pos: The start index of doc where parsing failed lineno: The line corresponding to pos colno: The column corresponding to pos

exception vistir.compat.FileNotFoundError

Bases: OSError

File not found.

exception vistir.compat.ResourceWarning

Bases: Warning

Base class for warnings about resource usage.

exception vistir.compat.PermissionError

Bases: OSError

Not enough permissions.

vistir.compat.is_type_checking()[source]
exception vistir.compat.IsADirectoryError

Bases: OSError

Operation doesn’t work on directories.

vistir.compat.fs_str(string)[source]

Encodes a string into the proper filesystem encoding.

Borrowed from pip-tools

vistir.compat.lru_cache(maxsize=128, typed=False)[source]

Least-recently-used cache decorator.

If maxsize is set to None, the LRU features are disabled and the cache can grow without bound.

If typed is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results.

Arguments to the cached function must be hashable.

View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__.

See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used

class vistir.compat.TemporaryDirectory(suffix='', prefix=None, dir=None)[source]

Bases: object

Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example:

with TemporaryDirectory() as tmpdir:

Upon exiting the context, the directory and everything contained in it are removed.

cleanup()[source]
vistir.compat.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True)[source]

Create and return a temporary file. Arguments: ‘prefix’, ‘suffix’, ‘dir’ – as for mkstemp. ‘mode’ – the mode argument to io.open (default “w+b”). ‘buffering’ – the buffer size argument to io.open (default -1). ‘encoding’ – the encoding argument to io.open (default None) ‘newline’ – the newline argument to io.open (default None) ‘delete’ – whether the file is deleted on close (default True). The file is created as mkstemp() would do it.

Returns an object with a file-like interface; the name of the file is accessible as its ‘name’ attribute. The file will be automatically deleted when it is closed unless the ‘delete’ argument is set to False.

vistir.compat.to_native_string(string)[source]
vistir.compat.samefile(f1, f2)[source]

Test whether two pathnames reference the same actual file

class vistir.compat.Mapping

Bases: collections.abc.Collection

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
items() → a set-like object providing a view on D's items
keys() → a set-like object providing a view on D's keys
values() → an object providing a view on D's values
class vistir.compat.Hashable

Bases: object

class vistir.compat.MutableMapping

Bases: collections.abc.Mapping

clear() → None. Remove all items from D.
pop(k[, d]) → v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) → None. Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

class vistir.compat.Container

Bases: object

class vistir.compat.Iterator

Bases: collections.abc.Iterable

class vistir.compat.KeysView(mapping)

Bases: collections.abc.MappingView, collections.abc.Set

class vistir.compat.ItemsView(mapping)

Bases: collections.abc.MappingView, collections.abc.Set

class vistir.compat.MappingView(mapping)

Bases: collections.abc.Sized

class vistir.compat.Iterable

Bases: object

class vistir.compat.Set

Bases: collections.abc.Collection

A set is a finite, iterable container.

This class provides concrete generic implementations of all methods except for __contains__, __iter__ and __len__.

To override the comparisons (presumably for speed, as the semantics are fixed), redefine __le__ and __ge__, then the other operations will automatically follow suit.

isdisjoint(other)

Return True if two sets have a null intersection.

class vistir.compat.Sequence

Bases: collections.abc.Reversible, collections.abc.Collection

All the operations on a read-only sequence.

Concrete subclasses must override __new__ or __init__, __getitem__, and __len__.

count(value) → integer -- return number of occurrences of value
index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

class vistir.compat.Sized

Bases: object

class vistir.compat.ValuesView(mapping)

Bases: collections.abc.MappingView, collections.abc.Collection

class vistir.compat.MutableSet

Bases: collections.abc.Set

A mutable set is a finite, iterable container.

This class provides concrete generic implementations of all methods except for __contains__, __iter__, __len__, add(), and discard().

To override the comparisons (presumably for speed, as the semantics are fixed), all you have to do is redefine __le__ and then the other operations will automatically follow suit.

add(value)

Add an element.

clear()

This is slow (creates N new iterators!) but effective.

discard(value)

Remove an element. Do not raise an exception if absent.

pop()

Return the popped value. Raise KeyError if empty.

remove(value)

Remove an element. If not a member, raise a KeyError.

class vistir.compat.MutableSequence

Bases: collections.abc.Sequence

append(value)

S.append(value) – append value to the end of the sequence

clear() → None -- remove all items from S
extend(values)

S.extend(iterable) – extend sequence by appending elements from the iterable

insert(index, value)

S.insert(index, value) – insert value before index

pop([index]) → item -- remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

remove(value)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE

class vistir.compat.Callable

Bases: object

vistir.compat.fs_encode(path)[source]

Encode a filesystem path to the proper filesystem encoding.

Parameters:bytes] path (Union[str,) – A string-like path
Returns:A bytes-encoded filesystem path representation
vistir.compat.fs_decode(path)[source]

Decode a filesystem path using the proper filesystem encoding.

Parameters:path – The filesystem path to decode from bytes or string
Returns:The filesystem path, decoded with the determined encoding
Return type:Text