repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
pyfilesystem2 | fs/appfs.py | .py | """Manage filesystems in platform-specific application directories.
These classes abstract away the different requirements for user data
across platforms, which vary in their conventions. They are all
subclasses of `~fs.osfs.OSFS`.
"""
# Thanks to authors of https://pypi.org/project/appdirs
# see http://technet.micr... | 169 | 4,335 |
pyfilesystem2 | fs/move.py | .py | """Functions for moving files between filesystems.
"""
from __future__ import print_function, unicode_literals
import typing
from ._pathcompat import commonpath
from .copy import copy_dir, copy_file
from .errors import FSError
from .opener import manage_fs
from .osfs import OSFS
from .path import frombase
if typing... | 151 | 5,619 |
pyfilesystem2 | fs/iotools.py | .py | """Compatibility tools between Python 2 and Python 3 I/O interfaces.
"""
from __future__ import print_function, unicode_literals
import typing
import array
import io
from io import SEEK_CUR, SEEK_SET
from .mode import Mode
if typing.TYPE_CHECKING:
from typing import IO, Any, Iterable, Iterator, List, Optional,... | 234 | 6,575 |
pyfilesystem2 | fs/errors.py | .py | """Exception classes thrown by filesystem operations.
Errors relating to the underlying filesystem are translated in
to one of the following exceptions.
All Exception classes are derived from `~fs.errors.FSError`
which may be used as a catch-all filesystem exception.
"""
from __future__ import print_function, unico... | 377 | 10,109 |
pyfilesystem2 | fs/filesize.py | .py | # coding: utf-8
"""Functions for reporting filesizes.
The functions declared in this module should cover the different
usecases needed to generate a string representation of a file size
using several different units. Since there are many standards regarding
file size units, three different functions have been implemen... | 119 | 3,495 |
pyfilesystem2 | fs/wrapfs.py | .py | """Base class for filesystem wrappers.
"""
from __future__ import unicode_literals
import typing
import six
from . import errors
from .base import FS
from .copy import copy_dir, copy_file
from .error_tools import unwrap_errors
from .info import Info
from .path import abspath, join, normpath
if typing.TYPE_CHECKING... | 548 | 17,457 |
pyfilesystem2 | fs/wrap.py | .py | """Collection of useful `~fs.wrapfs.WrapFS` subclasses.
Here's an example that opens a filesystem then makes it *read only*::
>>> home_fs = fs.open_fs('~')
>>> read_only_home_fs = fs.wrap.read_only(home_fs)
>>> read_only_home_fs.removedir('Desktop')
Traceback (most recent call last):
...
fs.... | 332 | 9,847 |
pyfilesystem2 | fs/_ftp_parse.py | .py | from __future__ import absolute_import, print_function, unicode_literals
import re
import time
import unicodedata
from datetime import datetime
try:
from datetime import timezone
except ImportError:
from ._tzcompat import timezone # type: ignore
from .enums import ResourceType
from .permissions import Permi... | 202 | 5,098 |
pyfilesystem2 | fs/_url_tools.py | .py | import typing
import platform
import re
import six
if typing.TYPE_CHECKING:
from typing import Text
_WINDOWS_PLATFORM = platform.system() == "Windows"
def url_quote(path_snippet):
# type: (Text) -> Text
"""Quote a URL without quoting the Windows drive letter, if any.
On Windows, it will separate d... | 56 | 1,525 |
pyfilesystem2 | fs/compress.py | .py | """Functions to compress the contents of a filesystem.
Currently zip and tar are supported, using the `zipfile` and
`tarfile` modules from the standard library.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
import six
import tarfile
import time
import zipfile
from dateti... | 188 | 7,048 |
pyfilesystem2 | fs/_version.py | .py | """Version, used in module and setup.py.
"""
__version__ = "2.4.16"
| 4 | 68 |
pyfilesystem2 | fs/info.py | .py | """Container for filesystem resource informations.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from typing import cast
import six
from copy import deepcopy
from ._typing import Text, overload
from .enums import ResourceType
from .errors import MissingInfoNamespace
from... | 466 | 13,457 |
pyfilesystem2 | fs/_pathcompat.py | .py | # mypy: ignore-errors
try:
from os.path import commonpath
except ImportError:
# Return the longest common sub-path of the sequence of paths given as input.
# The paths are not normalized before comparing them (this is the
# responsibility of the caller). Any trailing separator is stripped from the
#... | 42 | 1,309 |
pyfilesystem2 | fs/__init__.py | .py | """Python filesystem abstraction layer.
"""
__import__("pkg_resources").declare_namespace(__name__) # type: ignore
from . import path
from ._fscompat import fsdecode, fsencode
from ._version import __version__
from .enums import ResourceType, Seek
from .opener import open_fs
__all__ = ["__version__", "ResourceType"... | 13 | 341 |
pyfilesystem2 | fs/zipfs.py | .py | """Manage the filesystem in a Zip archive.
"""
from __future__ import print_function, unicode_literals
import sys
import typing
import six
import zipfile
from datetime import datetime
from . import errors
from ._url_tools import url_quote
from .base import FS
from .compress import write_zip
from .enums import Resou... | 512 | 17,756 |
pyfilesystem2 | fs/_bulk.py | .py | """
Implements a thread pool for parallel copying of files.
"""
from __future__ import unicode_literals
import typing
import threading
from six.moves.queue import Queue
from .copy import copy_file_internal, copy_modified_time
from .errors import BulkCopyFailed
from .tools import copy_file_data
if typing.TYPE_CHE... | 157 | 4,667 |
pyfilesystem2 | fs/mountfs.py | .py | """Manage other filesystems as a folder hierarchy.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from six import text_type
from . import errors
from .base import FS
from .memoryfs import MemoryFS
from .mode import validate_open_mode, validate_openbin_mode
from .path impo... | 324 | 9,492 |
pyfilesystem2 | fs/_typing.py | .py | """
Typing objects missing from Python3.5.1
"""
import sys
import six
_PY = sys.version_info
from typing import overload # type: ignore
if _PY.major == 3 and _PY.minor == 5 and _PY.micro in (0, 1):
def overload(func): # pragma: no cover # noqa: F811
return func
try:
from typing import Text
ex... | 23 | 399 |
pyfilesystem2 | fs/constants.py | .py | """Constants used by PyFilesystem.
"""
import io
DEFAULT_CHUNK_SIZE = io.DEFAULT_BUFFER_SIZE * 16
"""`int`: the size of a single chunk read from or written to a file.
"""
| 9 | 173 |
pyfilesystem2 | fs/glob.py | .py | """Useful functions for working with glob patterns.
"""
from __future__ import unicode_literals
import typing
from functools import partial
import re
from collections import namedtuple
from ._repr import make_repr
from .lrucache import LRUCache
from .path import iteratepath
GlobMatch = namedtuple("GlobMatch", ["p... | 462 | 13,740 |
pyfilesystem2 | fs/subfs.py | .py | """Manage a directory in a *parent* filesystem.
"""
from __future__ import print_function, unicode_literals
import typing
import six
from .path import abspath, join, normpath, relpath
from .wrapfs import WrapFS
if typing.TYPE_CHECKING:
from typing import Text, Tuple
from .base import FS # noqa: F401
_F... | 64 | 1,654 |
pyfilesystem2 | fs/_fscompat.py | .py | import six
try:
from os import fsdecode, fsencode
except ImportError:
from backports.os import fsdecode, fsencode # type: ignore
try:
from os import fspath
except ImportError:
def fspath(path): # type: ignore
"""Return the path representation of a path-like object.
If str or bytes ... | 43 | 1,464 |
pyfilesystem2 | fs/enums.py | .py | """Enums used by PyFilesystem.
"""
from __future__ import absolute_import, unicode_literals
import os
from enum import IntEnum, unique
@unique
class ResourceType(IntEnum):
"""Resource Types.
Positive values are reserved, negative values are implementation
dependent.
Most filesystems will support o... | 57 | 1,230 |
pyfilesystem2 | fs/path.py | .py | """Useful functions for working with PyFilesystem paths.
This is broadly similar to the standard `os.path` module but works
with paths in the canonical format expected by all FS objects (that is,
separated by forward slashes and with an optional leading slash).
See :ref:`paths` for an explanation of PyFilesystem path... | 593 | 13,411 |
pyfilesystem2 | fs/_repr.py | .py | """Tools to generate __repr__ strings.
"""
from __future__ import unicode_literals
import typing
if typing.TYPE_CHECKING:
from typing import Text, Tuple
def make_repr(class_name, *args, **kwargs):
# type: (Text, *object, **Tuple[object, object]) -> Text
"""Generate a repr string.
Positional argume... | 42 | 1,211 |
pyfilesystem2 | fs/error_tools.py | .py | """Tools for managing OS errors.
"""
from __future__ import print_function, unicode_literals
import sys
import typing
import errno
import platform
from contextlib import contextmanager
from six import reraise
from . import errors
if typing.TYPE_CHECKING:
from typing import Iterator, Optional, Text, Type, Union... | 118 | 3,824 |
pyfilesystem2 | fs/mode.py | .py | """Abstract I/O mode container.
Mode strings are used in in `~fs.base.FS.open` and
`~fs.base.FS.openbin`.
"""
from __future__ import print_function, unicode_literals
import typing
import six
from ._typing import Text
if typing.TYPE_CHECKING:
from typing import FrozenSet, Set, Union
__all__ = ["Mode", "chec... | 239 | 6,220 |
pyfilesystem2 | fs/wildcard.py | .py | """Match wildcard filenames.
"""
# Adapted from https://hg.python.org/cpython/file/2.7/Lib/fnmatch.py
from __future__ import print_function, unicode_literals
import typing
import re
from functools import partial
from .lrucache import LRUCache
if typing.TYPE_CHECKING:
from typing import Callable, Iterable, Patt... | 179 | 4,982 |
pyfilesystem2 | fs/walk.py | .py | """Machinery for walking a filesystem.
*Walking* a filesystem means recursively visiting a directory and
any sub-directories. It is a fairly common requirement for copying,
searching etc. See :ref:`walking` for details.
"""
from __future__ import unicode_literals
import typing
from collections import defaultdict, d... | 777 | 29,708 |
pyfilesystem2 | fs/permissions.py | .py | """Abstract permissions container.
"""
from __future__ import print_function, unicode_literals
import typing
from typing import Iterable
import six
from ._typing import Text
if typing.TYPE_CHECKING:
from typing import Iterator, List, Optional, Tuple, Type, Union
def make_mode(init):
# type: (Union[int, I... | 318 | 9,817 |
pyfilesystem2 | fs/tree.py | .py | # coding: utf-8
"""Render a FS object as text tree views.
Color is supported on UNIX terminals.
"""
from __future__ import print_function, unicode_literals
import sys
import typing
from fs.path import abspath, join, normpath
if typing.TYPE_CHECKING:
from typing import List, Optional, Text, TextIO, Tuple
f... | 173 | 5,656 |
pyfilesystem2 | fs/osfs.py | .py | """Manage the filesystem provided by your OS.
In essence, an `OSFS` is a thin layer over the `io` and `os` modules
of the Python standard library.
"""
from __future__ import absolute_import, print_function, unicode_literals
import sys
import typing
import errno
import io
import itertools
import logging
import os
im... | 690 | 26,101 |
pyfilesystem2 | fs/ftpfs.py | .py | """Manage filesystems on remote FTP servers.
"""
from __future__ import print_function, unicode_literals
import typing
import array
import calendar
import datetime
import io
import itertools
import socket
import threading
from collections import OrderedDict
from contextlib import contextmanager
from ftplib import FT... | 909 | 30,138 |
pyfilesystem2 | fs/tarfs.py | .py | """Manage the filesystem in a Tar archive.
"""
from __future__ import print_function, unicode_literals
import typing
from typing import IO, cast
import os
import six
import tarfile
from collections import OrderedDict
from . import errors
from ._url_tools import url_quote
from .base import FS
from .compress import w... | 494 | 15,498 |
pyfilesystem2 | fs/time.py | .py | """Time related tools.
"""
from __future__ import print_function, unicode_literals
import typing
from calendar import timegm
from datetime import datetime
try:
from datetime import timezone
except ImportError:
from ._tzcompat import timezone # type: ignore
if typing.TYPE_CHECKING:
from typing import O... | 44 | 870 |
pyfilesystem2 | fs/tempfs.py | .py | """Manage filesystems in temporary locations.
A temporary filesytem is stored in a location defined by your OS
(``/tmp`` on linux). The contents are deleted when the filesystem
is closed.
A `TempFS` is a good way of preparing a directory structure in advance,
that you can later copy. It can also be used as a temporar... | 138 | 4,291 |
pyfilesystem2 | fs/tools.py | .py | """Miscellaneous tools for operating on filesystems.
"""
from __future__ import print_function, unicode_literals
import typing
from . import errors
from .errors import DirectoryNotEmpty, ResourceNotFound
from .path import abspath, dirname, normpath, recursepath
if typing.TYPE_CHECKING:
from typing import IO, Li... | 99 | 2,714 |
pyfilesystem2 | fs/mirror.py | .py | """Function for *mirroring* a filesystem.
Mirroring will create a copy of a source filesystem on a destination
filesystem. If there are no files on the destination, then mirroring
is simply a straight copy. If there are any files or directories on the
destination they may be deleted or modified to match the source.
I... | 159 | 5,363 |
pyfilesystem2 | fs/multifs.py | .py | """Manage several filesystems through a single view.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from collections import OrderedDict, namedtuple
from operator import itemgetter
from six import text_type
from . import errors
from .base import FS
from .mode import check_... | 427 | 13,183 |
pyfilesystem2 | fs/memoryfs.py | .py | """Manage a volatile in-memory filesystem.
"""
from __future__ import absolute_import, unicode_literals
import typing
import contextlib
import io
import os
import six
import time
from collections import OrderedDict
from threading import RLock
from . import errors
from ._typing import overload
from .base import FS
fr... | 662 | 22,022 |
pyfilesystem2 | fs/base.py | .py | """PyFilesystem base class.
The filesystem base class is common to all filesystems. If you
familiarize yourself with this (rather straightforward) API, you
can work with any of the supported filesystems.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
import abc
import ha... | 1,834 | 63,977 |
pyfilesystem2 | fs/test.py | .py | # coding: utf-8
"""Base class for tests.
All Filesystems should be able to pass these.
"""
from __future__ import absolute_import, unicode_literals
import io
import itertools
import json
import os
import six
import time
import unittest
import warnings
from datetime import datetime
from six import text_type
import ... | 2,004 | 77,367 |
pyfilesystem2 | fs/lrucache.py | .py | """Least Recently Used cache mapping.
"""
from __future__ import absolute_import, unicode_literals
import typing
from collections import OrderedDict
_K = typing.TypeVar("_K")
_V = typing.TypeVar("_V")
class LRUCache(OrderedDict, typing.Generic[_K, _V]):
"""A dictionary-like container that stores a given maxim... | 44 | 1,303 |
pyfilesystem2 | fs/_tzcompat.py | .py | """Compatibility shim for python2's lack of datetime.timezone.
This is the example code from the Python 2 documentation:
https://docs.python.org/2.7/library/datetime.html#tzinfo-objects
"""
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
... | 30 | 475 |
pyfilesystem2 | fs/opener/appfs.py | .py | # coding: utf-8
"""``AppFS`` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .errors import OpenerError
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text, Union
from ..appfs import _App... | 73 | 2,059 |
pyfilesystem2 | fs/opener/parse.py | .py | """Function to parse FS URLs in to their constituent parts.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
import collections
import re
import six
from six.moves.urllib.parse import parse_qs, unquote
from .errors import ParseError
if typing.TYPE_CHECKING:
from typing... | 96 | 2,322 |
pyfilesystem2 | fs/opener/errors.py | .py | # coding: utf-8
"""Errors raised when attempting to open a filesystem.
"""
class ParseError(ValueError):
"""Attempt to parse an invalid FS URL."""
class OpenerError(Exception):
"""Base exception for opener related errors."""
class UnsupportedProtocol(OpenerError):
"""No opener found for the given prot... | 24 | 494 |
pyfilesystem2 | fs/opener/__init__.py | .py | # coding: utf-8
"""Open filesystems from a URL.
"""
# Declare fs.opener as a namespace package
__import__("pkg_resources").declare_namespace(__name__) # type: ignore
# Import opener modules so that `registry.install` if called on each opener
from . import appfs, ftpfs, memoryfs, osfs, tarfs, tempfs, zipfs
# Import ... | 23 | 686 |
pyfilesystem2 | fs/opener/zipfs.py | .py | # coding: utf-8
"""`ZipFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .errors import NotWriteable
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from ..zipfs import ZipFS # noq... | 41 | 925 |
pyfilesystem2 | fs/opener/registry.py | .py | # coding: utf-8
"""`Registry` class mapping protocols and FS URLs to their `Opener`.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
import collections
import contextlib
import pkg_resources
from ..errors import ResourceReadOnly
from .base import Opener
from .errors import... | 295 | 9,862 |
pyfilesystem2 | fs/opener/osfs.py | .py | # coding: utf-8
"""`OSFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from ..osfs import OSFS # noqa: F401
from .parse import Parse... | 42 | 924 |
pyfilesystem2 | fs/opener/ftpfs.py | .py | # coding: utf-8
"""`FTPFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from ..errors import CreateFailed
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text, Union
from ..ftpfs import FTPF... | 58 | 1,597 |
pyfilesystem2 | fs/opener/tarfs.py | .py | # coding: utf-8
"""`TarFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .errors import NotWriteable
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from ..tarfs import TarFS # noq... | 41 | 925 |
pyfilesystem2 | fs/opener/tempfs.py | .py | # coding: utf-8
"""`TempFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from ..tempfs import TempFS # noqa: F401
from .parse import... | 38 | 785 |
pyfilesystem2 | fs/opener/memoryfs.py | .py | # coding: utf-8
"""`MemoryFS` opener definition.
"""
from __future__ import absolute_import, print_function, unicode_literals
import typing
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from ..memoryfs import MemoryFS # noqa: F401
from .parse ... | 38 | 765 |
pyfilesystem2 | fs/opener/base.py | .py | # coding: utf-8
"""`Opener` abstract base class.
"""
import typing
import abc
import six
if typing.TYPE_CHECKING:
from typing import List, Text
from ..base import FS
from .parse import ParseResult
@six.add_metaclass(abc.ABCMeta)
class Opener(object):
"""The base class for filesystem openers.
... | 62 | 1,522 |
black | docs/conf.py | .py | #
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
#... | 236 | 7,298 |
black | tests/test_format.py | .py | import re
from collections.abc import Iterator
from dataclasses import replace
from typing import Any
from unittest.mock import patch
import pytest
import black
from black.mode import TargetVersion
from tests.util import (
all_data_cases,
assert_format,
dump_to_stderr,
read_data,
read_data_with_mo... | 100 | 2,905 |
black | tests/optional.py | .py | """
Allows configuring optional test markers in config, see pyproject.toml.
Run optional tests with `pytest --run-optional=...`.
Mark tests to run only if an optional test ISN'T selected by prepending the mark with
"no_".
You can specify a "no_" prefix straight in config, in which case you can mark tests
to run when... | 134 | 4,700 |
black | tests/test_ranges.py | .py | """Test the black.ranges module."""
import pytest
from black.ranges import adjusted_lines, parse_line_ranges, sanitized_lines
@pytest.mark.parametrize(
"lines_str, expected",
[
(["1-5"], [(1, 5)]),
(["1-1"], [(1, 1)]),
(["1-3", "5-7"], [(1, 3), (5, 7)]),
],
)
def test_parse_line_... | 276 | 5,153 |
black | tests/test_trans.py | .py | from black.trans import iter_fexpr_spans
def test_fexpr_spans() -> None:
def check(
string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str]
) -> None:
spans = list(iter_fexpr_spans(string))
# Checking slices isn't strictly necessary, but it's easier to verify at... | 50 | 2,219 |
black | tests/test_no_ipynb.py | .py | import pathlib
import pytest
from click.testing import CliRunner
from black import jupyter_dependencies_are_installed, main
from tests.util import get_case_path
pytestmark = pytest.mark.no_jupyter
runner = CliRunner()
def test_ipynb_diff_with_no_change_single() -> None:
jupyter_dependencies_are_installed.cach... | 37 | 1,247 |
black | tests/test_black.py | .py | #!/usr/bin/env python3
import asyncio
import inspect
import io
import itertools
import logging
import multiprocessing
import os
import pickle
import re
import sys
import textwrap
import types
from collections.abc import Callable, Iterator, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib impo... | 3,459 | 137,956 |
black | tests/util.py | .py | import argparse
import functools
import os
import shlex
import sys
import unittest
from collections.abc import Collection, Iterator
from contextlib import contextmanager
from dataclasses import dataclass, field, replace
from functools import partial
from pathlib import Path
from typing import Any
import black
from bla... | 356 | 12,188 |
black | tests/test_concurrency_manager_shutdown.py | .py | from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any, Optional
import black.concurrency as concurrency
from black import Mode, WriteBack
from black.report import Report
class FakeManager:
shutdown_called: bool
de... | 67 | 1,821 |
black | tests/test_blackd.py | .py | import asyncio
import gc
import re
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from threading import Event
from unittest.mock import patch
import pytest
from click.testing import CliRunner
from tests.util import DETERMINISTIC_HEADER, read_data
try:
from aiohttp impor... | 450 | 17,497 |
black | tests/test_tokenize.py | .py | """Tests for the blib2to3 tokenizer."""
import sys
import textwrap
from dataclasses import dataclass
import black
from blib2to3.pgen2 import token, tokenize
@dataclass
class Token:
type: str
string: str
start: tokenize.Coord
end: tokenize.Coord
def get_tokens(text: str) -> list[Token]:
"""Retu... | 108 | 3,571 |
black | tests/test_ipynb.py | .py | import contextlib
import pathlib
import re
from contextlib import AbstractContextManager
from contextlib import ExitStack as does_not_raise
from dataclasses import replace
import pytest
from click.testing import CliRunner
from pytest import MonkeyPatch
from black import (
Mode,
NothingChanged,
format_cell... | 566 | 17,469 |
black | tests/test_docs.py | .py | """
Test that the docs are up to date.
"""
import re
from collections.abc import Sequence
from itertools import islice
from pathlib import Path
import pytest
from black.mode import UNSTABLE_FEATURES, Preview
DOCS_PATH = Path("docs/the_black_code_style/future_style.md")
def check_feature_list(
lines: Sequenc... | 75 | 2,522 |
black | tests/test_schema.py | .py | import importlib.metadata
def test_schema_entrypoint() -> None:
(black_ep,) = importlib.metadata.entry_points(
group="validate_pyproject.tool_schema", name="black"
)
black_fn = black_ep.load()
schema = black_fn()
assert schema == black_fn("black")
assert schema["properties"]["line-len... | 13 | 347 |
black | tests/conftest.py | .py | import pytest
pytest_plugins = ["tests.optional"]
PRINT_FULL_TREE: bool = False
PRINT_TREE_DIFF: bool = True
def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption(
"--print-full-tree",
action="store_true",
default=False,
help="print full syntax trees on failed tes... | 29 | 727 |
black | tests/data/line_ranges_formatted/pattern_matching.py | .py | # flags: --minimum-version=3.10
def pattern_matching():
match status:
case 1:
return "1"
case [single]:
return "single"
case [
action,
obj,
]:
return "act on obj"
case Point(x=0):
return "class pattern"... | 26 | 537 |
black | tests/data/line_ranges_formatted/basic.py | .py | """Module doc."""
from typing import (
Callable,
Literal,
)
# fmt: off
class Unformatted:
def should_also_work(self):
pass
# fmt: on
a = [1, 2] # fmt: skip
# This should cover as many syntaxes as possible.
class Foo:
"""Class doc."""
def __init__(self) -> None:
pass
@add_... | 50 | 852 |
black | tests/data/cases/pattern_matching_long.py | .py | # flags: --minimum-version=3.10
match x:
case "abcd" | "abcd" | "abcd" :
pass
case "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd":
pass
case xxxxxxxxxxxxxxxxxxxxxxx:
pass
# output
match x:
cas... | 35 | 692 |
black | tests/data/cases/async_stmts.py | .py | async def func() -> (int):
return 0
@decorated
async def func() -> (int):
return 0
async for (item) in async_iter:
pass
# output
async def func() -> int:
return 0
@decorated
async def func() -> int:
return 0
async for item in async_iter:
pass
| 28 | 279 |
black | tests/data/cases/yield_singleton_tuple_stable.py | .py | def f():
yield x,
# output
def f():
yield x,
| 10 | 57 |
black | tests/data/cases/preview_comments7.py | .py | # flags: --unstable
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
Path,
# String,
# resolve_to_config_type,
# DEFAULT_TYPE_ATTRIBUTES,
)
from .config import (
Any,
Bool,
ConfigType,
ConfigTypeAttributes,
Int,
no_comma_here_yet
... | 309 | 8,995 |
black | tests/data/cases/power_op_spacing.py | .py | def function(**kwargs):
t = a**2 + b**3
return t ** 2
def function_replace_spaces(**kwargs):
t = a **2 + b** 3 + c ** 4
def function_dont_replace_spaces():
{**a, **b, **c}
a = 5**~4
b = 5 ** f()
c = -(5**2)
d = 5 ** f["hi"]
e = lazy(lambda **kwargs: 5)
f = f() ** 5
g = a.b**c.d
h = 5 ** funcs.f()
... | 150 | 3,533 |
black | tests/data/cases/preview_hug_parens_with_braces_and_square_brackets.py | .py | # flags: --unstable
def foo_brackets(request):
return JsonResponse(
{
"var_1": foo,
"var_2": bar,
}
)
def foo_square_brackets(request):
return JsonResponse(
[
"var_1",
"var_2",
]
)
func({"a": 37, "b": 42, "c": 927, "aaaaaa... | 348 | 5,823 |
black | tests/data/cases/pep_572.py | .py | (a := 1)
(a := a)
if (match := pattern.search(data)) is None:
pass
if match := pattern.search(data):
pass
[y := f(x), y**2, y**3]
filtered_data = [y for x in data if (y := f(x)) is None]
(y := f(x))
y0 = (y1 := f(x))
foo(x=(y := f(x)))
def foo(answer=(p := 42)):
pass
def foo(answer: (p := 42) = 5):
... | 48 | 970 |
black | tests/data/cases/module_docstring_4.py | .py | """Single line module-level docstring should be followed by single newline."""
a = 1
# output
"""Single line module-level docstring should be followed by single newline."""
a = 1
| 9 | 182 |
black | tests/data/cases/trailing_commas_in_leading_parts.py | .py | zero(one,).two(three,).four(five,)
func1(arg1).func2(arg2,).func3(arg3).func4(arg4,).func5(arg5)
# Inner one-element tuple shouldn't explode
func1(arg1).func2(arg1, (one_tuple,)).func3(arg3)
(a, b, c, d,) = func1(arg1) and func2(arg2)
# Example from https://github.com/psf/black/issues/3229
def refresh_token(self, ... | 89 | 2,123 |
black | tests/data/cases/pyi_docstring_blank_lines_no_preview.py | .py | # flags: --pyi
import sys
class C:
def before_comment(self) -> None:
"""docs"""
# leading comment for the next method
def after_comment(self) -> None: ...
def before_if(self) -> None:
"""docs"""
if sys.version_info >= (3, 12):
if_attr: int
| 13 | 285 |
black | tests/data/cases/remove_for_brackets.py | .py | # Only remove tuple brackets after `for`
for (k, v) in d.items():
print(k, v)
# Don't touch tuple brackets after `in`
for module in (core, _unicodefun):
if hasattr(module, "_verify_python3_env"):
module._verify_python3_env = lambda: None
# Brackets remain for long for loop lines
for (why_would_anyone_... | 49 | 1,460 |
black | tests/data/cases/remove_parens_from_lhs.py | .py | # Remove unnecessary parentheses from LHS of assignments
def a():
return [1, 2, 3]
# Single variable with unnecessary parentheses
(b) = a()[0]
# Tuple unpacking with unnecessary parentheses
(c, *_) = a()
# These should not be changed - parentheses are necessary
(d,) = a() # single-element tuple
e = (1 + 2) *... | 36 | 709 |
black | tests/data/cases/long_strings__type_annotations.py | .py | def func(
arg1,
arg2,
) -> Set["this_is_a_very_long_module_name.AndAVeryLongClasName"
".WithAVeryVeryVeryVeryVeryLongSubClassName"]:
pass
def func(
argument: (
"VeryLongClassNameWithAwkwardGenericSubtype[int] |"
"VeryLongClassNameWithAwkwardGenericSubtype[str]"
),
) -> (
... | 60 | 1,075 |
black | tests/data/cases/pyi_decorated_class_blank_line.py | .py | # flags: --preview --pyi
#
# Test case for https://github.com/psf/black/issues/4256
# Blank line should be enforced between a function and a decorated class in stubs.
def foo(): ...
@decorator
class Bar: ...
def baz(): ...
@decorator
class Qux: ...
class Already: ...
@decorator
class After: ...
@decorator
class F... | 116 | 1,621 |
black | tests/data/cases/line_ranges_fmt_off_decorator.py | .py | # flags: --line-ranges=12-12 --line-ranges=21-21
# NOTE: If you need to modify this file, pay special attention to the --line-ranges=
# flag above as it's formatting specifically these lines.
# Regression test for an edge case involving decorators and fmt: off/on.
class MyClass:
# fmt: off
@decorator ( )
... | 48 | 998 |
black | tests/data/cases/preview_cantfit_string.py | .py | # flags: --unstable
# long arguments
normal_name = normal_function_name(
"but with super long string arguments that on their own exceed the line limit so there's no way it can ever fit",
"eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs",
... | 19 | 829 |
black | tests/data/cases/comment_in_subscript_annotation.py | .py | # Regression test for https://github.com/psf/black/issues/4733.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: list[ # bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
int
] = []
# Original (non-minimized) snippet from the issue report.
def foo():
possibly_redundant_lowlevel_checkpoints: list[ # pyright: ignore[reportUnkn... | 26 | 812 |
black | tests/data/cases/tuple_with_stmt.py | .py | # don't remove the brackets here, it changes the meaning of the code.
# even though the code will always trigger a runtime error
with (name_5, name_4), name_5:
pass
with c, (a, b):
pass
with c, (a, b), d:
pass
with c, (a, b, e, f, g), d:
pass
def test_tuple_as_contextmanager():
from contextl... | 31 | 555 |
black | tests/data/cases/attribute_access_on_number_literals.py | .py | x = 123456789 .bit_count()
x = (123456).__abs__()
x = .1.is_integer()
x = 1. .imag
x = 1E+1.imag
x = 1E-1.real
x = 123456789.123456789.hex()
x = 123456789.123456789E123456789 .real
x = 123456789E123456789 .conjugate()
x = 123456789J.real
x = 123456789.123456789J.__add__(0b1011.bit_length())
x = 0XB1ACC.conjugate()
x = ... | 48 | 907 |
black | tests/data/cases/fmtskip11.py | .py | def foo():
pass
# comment 1 # fmt: skip
# comment 2
[
(1, 2),
# # fmt: off
# (3,
# 4),
# # fmt: on
(5, 6),
]
[
(1, 2),
# # fmt: off
# (3,
# 4),
# fmt: on
(5, 6),
]
[
(1, 2),
# fmt: off
# (3,
# 4),
# # fmt: on
(5, 6),
]
[
(... | 89 | 769 |
black | tests/data/cases/fmtskip_multiple_strings.py | .py | # Multiple fmt: skip on string literals
a = (
"this should " # fmt: skip
"be fine"
)
b = (
"this is " # fmt: skip
"not working" # fmt: skip
)
c = (
"and neither " # fmt: skip
"is this " # fmt: skip
"working"
)
d = (
"nor "
"is this " # fmt: skip
"working" # fmt: skip
)
... | 76 | 1,567 |
black | tests/data/cases/raw_docstring_no_string_normalization.py | .py | # flags: --skip-string-normalization
def do_not_touch_this_prefix():
R"""There was a bug where docstring prefixes would be normalized even with -S."""
def do_not_touch_this_prefix2():
FR'There was a bug where docstring prefixes would be normalized even with -S.'
def do_not_touch_this_prefix3():
u'''Ther... | 12 | 394 |
black | tests/data/cases/fmtskip4.py | .py | a = 2
# fmt: skip
l = [1, 2, 3,]
# output
a = 2
# fmt: skip
l = [
1,
2,
3,
] | 13 | 92 |
black | tests/data/cases/type_params.py | .py | # flags: --minimum-version=3.12
def func [T ](): pass
async def func [ T ] (): pass
class C[ T ] : pass
def all_in[T : int,U : (bytes, str),* Ts,**P](): pass
def really_long[WhatIsTheLongestTypeVarNameYouCanThinkOfEnoughToMakeBlackSplitThisLine](): pass
def even_longer[WhatIsTheLongestTypeVarNameYouCanThinkOf... | 102 | 1,763 |
black | tests/data/cases/line_ranges_basic.py | .py | # flags: --line-ranges=5-6
# NOTE: If you need to modify this file, pay special attention to the --line-ranges=
# flag above as it's formatting specifically these lines.
def foo1(parameter_1, parameter_2, parameter_3, parameter_4, parameter_5, parameter_6, parameter_7): pass
def foo2(parameter_1, parameter_2, parameter... | 108 | 3,519 |
black | tests/data/cases/docstring_no_extra_empty_line_before_eof.py | .py | # Make sure when the file ends with class's docstring,
# It doesn't add extra blank lines.
class ClassWithDocstring:
"""A docstring."""
| 5 | 140 |
black | tests/data/cases/preview_return_annotation_brackets_string.py | .py | # flags: --unstable
# Long string example
def frobnicate() -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnreasonablyExtremelyLongClassName]":
pass
# splitting the string breaks if there's any parameters
def frobnicate(a) -> "ThisIsTrulyUnreasonablyExtremelyLongClassName | list[ThisIsTrulyUnr... | 25 | 742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.