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 |
|---|---|---|---|---|---|
attrs | tests/test_setattr.py | .py | # SPDX-License-Identifier: MIT
import pickle
import pytest
import attr
from attr import setters
from attr.exceptions import FrozenAttributeError
from attr.validators import instance_of, matches_re
@attr.s(frozen=True)
class Frozen:
x = attr.ib()
@attr.s
class WithOnSetAttrHook:
x = attr.ib(on_setattr=l... | 648 | 16,349 |
attrs | tests/test_forward_references.py | .py | """
Tests for behavior specific to forward references via PEP 749.
"""
from attrs import define, fields, resolve_types
def test_forward_class_reference():
"""
Class A can reference B even though it is defined later.
"""
@define
class A:
b: B
class B:
pass
resolve_types(... | 23 | 357 |
attrs | tests/test_filters.py | .py | # SPDX-License-Identifier: MIT
"""
Tests for `attr.filters`.
"""
import pytest
import attr
from attr import fields
from attr.filters import _split_what, exclude, include
@attr.s
class C:
a = attr.ib()
b = attr.ib()
class TestSplitWhat:
"""
Tests for `_split_what`.
"""
def test_splits(se... | 127 | 2,896 |
attrs | tests/test_abc.py | .py | # SPDX-License-Identifier: MIT
import abc
import inspect
import pytest
import attrs
from attr._compat import PY_3_12_PLUS
class TestUpdateAbstractMethods:
def test_abc_implementation(self, slots):
"""
If an attrs class implements an abstract method, it stops being
abstract.
"""... | 60 | 1,534 |
attrs | tests/test_packaging.py | .py | # SPDX-License-Identifier: MIT
from importlib import metadata
import pytest
import attr
import attrs
@pytest.fixture(name="mod", params=(attr, attrs))
def _mod(request):
return request.param
class TestLegacyMetadataHack:
def test_version(self, mod, recwarn):
"""
__version__ returns the c... | 43 | 1,033 |
attrs | tests/test_pattern_matching.py | .py | # SPDX-License-Identifier: MIT
import pytest
import attr
class TestPatternMatching:
"""
Pattern matching syntax test cases.
"""
@pytest.mark.parametrize("dec", [attr.s, attr.define, attr.frozen])
def test_simple_match_case(self, dec):
"""
Simple match case statement works as exp... | 101 | 2,245 |
attrs | tests/test_annotations.py | .py | # SPDX-License-Identifier: MIT
"""
Tests for PEP-526 type annotations.
"""
import sys
import types
import typing
import pytest
import attr
import attrs
from attr._make import _is_class_var
from attr.exceptions import UnannotatedAttributeError
def assert_init_annotations(cls, **annotations):
"""
Assert cl... | 719 | 18,752 |
attrs | tests/test_utils.py | .py | from .utils import simple_class
class TestSimpleClass:
"""
Tests for the testing helper function `make_class`.
"""
def test_returns_class(self):
"""
Returns a class object.
"""
assert type is simple_class().__class__
def test_returns_distinct_classes(self):
... | 20 | 440 |
attrs | tests/test_hooks.py | .py | # SPDX-License-Identifier: MIT
from __future__ import annotations
from datetime import datetime
import pytest
import attr
class TestTransformHook:
"""
Tests for `attrs(tranform_value_serializer=func)`
"""
def test_hook_applied(self):
"""
The transform hook is applied to all attrib... | 454 | 12,789 |
attrs | tests/conftest.py | .py | # SPDX-License-Identifier: MIT
from datetime import timedelta
import pytest
from hypothesis import HealthCheck, settings
from attr._compat import PY_3_14_PLUS
@pytest.fixture(name="slots", params=(True, False))
def _slots(request):
return request.param
@pytest.fixture(name="frozen", params=(True, False))
de... | 37 | 809 |
attrs | bench/test_benchmarks.py | .py | """
Benchmark attrs using CodSpeed.
"""
from __future__ import annotations
import functools
import time
import pytest
import attrs
pytestmark = pytest.mark.benchmark()
ROUNDS = 1_000
def test_create_simple_class():
"""
Benchmark creating a simple class without any extras.
"""
for _ in range(RO... | 233 | 4,281 |
attrs | typing_tests/pyrefly.py | .py | # SPDX-License-Identifier: MIT
"""
Typing examples that rely on Pyrefly's advanced attrs integration.
"""
from __future__ import annotations
import copy
import re
import sys
from typing import Any
import attrs
@attrs.define
class C:
a: int = attrs.field()
cc = C(1)
C(a=1)
if sys.version_info >= (3, 13):
... | 400 | 8,247 |
attrs | typing_tests/baseline.py | .py | # SPDX-License-Identifier: MIT
# pyright: strict
"""
Baseline features that should be supported by all type checkers.
"""
from __future__ import annotations
from typing import Any, Generator
import attrs
@attrs.define(order=True)
class NGClass:
x: int = attrs.field(default=42)
ngc = NGClass(1)
ngc = attrs.... | 228 | 4,329 |
attrs | typing_tests/mypy.py | .py | # SPDX-License-Identifier: MIT
"""
Typing examples that rely on Mypy-specific features (mostly the attrs plugin).
"""
from __future__ import annotations
import re
from typing import Any, Dict, List, Tuple
import attr
import attrs
# Typing via "type" Argument ---
@attr.s
class C:
a = attr.ib(type=int)
c =... | 429 | 8,241 |
attrs | src/attr/setters.py | .py | # SPDX-License-Identifier: MIT
"""
Commonly used hooks for on_setattr.
"""
from . import _config
from .exceptions import FrozenAttributeError
def pipe(*setters):
"""
Run all *setters* and return the return value of the last one.
.. warning::
Generators are not allowed in ``pipe()``.
.. vers... | 83 | 1,684 |
attrs | src/attr/_compat.py | .py | # SPDX-License-Identifier: MIT
import sys
import threading
from collections.abc import Mapping, Sequence # noqa: F401
from typing import Callable, _GenericAlias
PYPY = sys.implementation.name == "pypy"
PY_3_11_PLUS = sys.version_info[:2] >= (3, 11)
PY_3_12_PLUS = sys.version_info[:2] >= (3, 12)
PY_3_13_PLUS = sys.... | 128 | 3,430 |
attrs | src/attr/exceptions.py | .py | # SPDX-License-Identifier: MIT
from __future__ import annotations
class FrozenError(AttributeError):
"""
A frozen/immutable instance or attribute have been attempted to be
modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing `AttributeError`.
... | 96 | 1,990 |
attrs | src/attr/_cmp.py | .py | # SPDX-License-Identifier: MIT
import functools
import types
from ._make import __ne__
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
"""
... | 161 | 4,117 |
attrs | src/attr/_config.py | .py | # SPDX-License-Identifier: MIT
__all__ = ["get_run_validators", "set_run_validators"]
_run_validators = True
def set_run_validators(run):
"""
Set whether or not validators are run. By default, they are run.
.. deprecated:: 21.3.0
It will not be removed, but it also will not be moved to new ``at... | 32 | 841 |
attrs | src/attr/filters.py | .py | # SPDX-License-Identifier: MIT
"""
Commonly useful filters for `attrs.asdict` and `attrs.astuple`.
"""
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isinstance(cls, type)),
... | 73 | 1,795 |
attrs | src/attr/__init__.py | .py | # SPDX-License-Identifier: MIT
"""
Classes Without Boilerplate
"""
import sys
from functools import partial
from typing import Callable, Literal, Protocol
from . import exceptions, setters
from ._cmp import cmp_using
from ._config import get_run_validators, set_run_validators
from ._funcs import asdict, assoc, astu... | 121 | 2,386 |
attrs | src/attr/_version_info.py | .py | # SPDX-License-Identifier: MIT
from functools import total_ordering
from ._funcs import astuple
from ._make import attrib, attrs
@total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo:
"""
A version object that can be compared to tuple of length 1--4:
>>> attr.Version... | 90 | 2,222 |
attrs | src/attr/_funcs.py | .py | # SPDX-License-Identifier: MIT
from ._compat import get_generic_base
from ._make import _OBJ_SETATTR, NOTHING, fields
from .exceptions import AttrsAttributeNotFoundError
_ATOMIC_TYPES = frozenset(
{
type(None),
bool,
int,
float,
str,
complex,
bytes,
... | 496 | 16,346 |
attrs | src/attr/_next_gen.py | .py | # SPDX-License-Identifier: MIT
"""
These are keyword-only APIs that call `attr.s` and `attr.ib` with different
default values.
"""
from functools import partial
from . import setters
from ._funcs import asdict as _asdict
from ._funcs import astuple as _astuple
from ._make import (
_DEFAULT_ON_SETATTR,
NOTHIN... | 679 | 26,392 |
attrs | src/attr/_make.py | .py | # SPDX-License-Identifier: MIT
from __future__ import annotations
import abc
import contextlib
import enum
import itertools
import linecache
import sys
import types
import unicodedata
import weakref
from collections.abc import Callable, Mapping
from functools import cached_property
from typing import Any, NamedTuple... | 3,463 | 108,046 |
attrs | src/attr/converters.py | .py | # SPDX-License-Identifier: MIT
"""
Commonly useful converters.
"""
from ._compat import _AnnotationExtractor
from ._make import NOTHING, Converter, Factory, pipe
__all__ = [
"default_if_none",
"optional",
"pipe",
"to_bool",
]
def optional(converter):
"""
A converter that allows an attribut... | 161 | 3,826 |
attrs | src/attr/validators.py | .py | # SPDX-License-Identifier: MIT
"""
Commonly useful validators.
"""
import operator
import re
from contextlib import contextmanager
from re import Pattern
from ._config import get_run_validators, set_run_validators
from ._make import _AndValidator, and_, attrib, attrs
from .converters import default_if_none
from .ex... | 767 | 21,903 |
attrs | src/attrs/__init__.py | .py | # SPDX-License-Identifier: MIT
from attr import (
NOTHING,
Attribute,
AttrsInstance,
Converter,
Factory,
NothingType,
_make_getattr,
assoc,
cmp_using,
define,
evolve,
field,
fields,
fields_dict,
frozen,
has,
make_class,
mutable,
resolve_types,... | 77 | 1,238 |
dirty-equals | dirty_equals/_strings.py | .py | import re
from re import Pattern
from typing import Any, Literal, Optional, TypeVar, Union
from ._base import DirtyEquals
from ._utils import Omit, plain_repr
T = TypeVar('T', str, bytes)
__all__ = 'IsStr', 'IsBytes', 'IsAnyStr'
class IsAnyStr(DirtyEquals[T]):
"""
Comparison of `str` or `bytes` objects.
... | 161 | 5,103 |
dirty-equals | dirty_equals/_utils.py | .py | __all__ = 'plain_repr', 'PlainRepr', 'Omit', 'get_dict_arg'
from typing import Any
class PlainRepr:
"""
Hack to allow repr of string without quotes.
"""
def __init__(self, v: str):
self.v = v
def __repr__(self) -> str:
return self.v
def plain_repr(v: str) -> PlainRepr:
ret... | 47 | 1,121 |
dirty-equals | dirty_equals/_base.py | .py | import io
from abc import ABCMeta
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, Generic, Optional, Protocol, TypeVar
try:
from _pytest._io.pprint import PrettyPrinter
except ImportError:
# support for pytest 7.4.4
from pprint import PrettyPrinter # type: ignore
from ._utils... | 263 | 8,354 |
dirty-equals | dirty_equals/_other.py | .py | from __future__ import annotations
import json
import re
from dataclasses import fields, is_dataclass
from enum import Enum
from functools import lru_cache
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_network
from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, Union, over... | 590 | 19,070 |
dirty-equals | dirty_equals/__init__.py | .py | from ._base import AnyThing, DirtyEquals, IsOneOf
from ._boolean import IsFalseLike, IsTrueLike
from ._datetime import IsDate, IsDatetime, IsNow, IsToday
from ._dict import IsDict, IsIgnoreDict, IsPartialDict, IsStrictDict
from ._inspection import HasAttributes, HasName, HasRepr, IsInstance
from ._numeric import (
... | 112 | 2,102 |
dirty-equals | dirty_equals/_numeric.py | .py | import math
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Optional, TypeVar, Union
from ._base import DirtyEquals
__all__ = (
'IsApprox',
'IsNumeric',
'IsNumber',
'IsPositive',
'IsNegative',
'IsNonPositive',
'IsNonNegative',
'IsInt',... | 504 | 14,104 |
dirty-equals | dirty_equals/_datetime.py | .py | from __future__ import annotations as _annotations
from datetime import date, datetime, timedelta, timezone, tzinfo
from typing import Any
from zoneinfo import ZoneInfo
from ._numeric import IsNumeric
from ._utils import Omit
class IsDatetime(IsNumeric[datetime]):
"""
Check if the value is a datetime, and m... | 307 | 11,208 |
dirty-equals | dirty_equals/_sequence.py | .py | import sys
from collections.abc import Container, Sized
from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union, overload
from ._base import DirtyEquals
from ._utils import Omit, plain_repr
if TYPE_CHECKING:
from typing import TypeAlias
if sys.version_info >= (3, 10):
from types import EllipsisType
e... | 284 | 10,220 |
dirty-equals | dirty_equals/_inspection.py | .py | from typing import Any, TypeVar, Union, overload
from ._base import DirtyEquals
from ._strings import IsStr
from ._utils import get_dict_arg
ExpectedType = TypeVar('ExpectedType', bound=Union[type, tuple[Union[type, tuple[Any, ...]], ...]])
class IsInstance(DirtyEquals[ExpectedType]):
"""
A type which check... | 203 | 6,514 |
dirty-equals | dirty_equals/_boolean.py | .py | from typing import Any
from ._base import DirtyEquals
from ._utils import Omit
class IsTrueLike(DirtyEquals[bool]):
"""
Check if the value is True like. `IsTrueLike` allows comparison to anything and effectively uses just
`return bool(other)`.
Example of basic usage:
```py title="IsTrueLike"
... | 80 | 2,416 |
dirty-equals | dirty_equals/_dict.py | .py | from __future__ import annotations
from collections.abc import Container
from typing import Any, Callable, overload
from ._base import DirtyEquals, DirtyEqualsMeta
from ._utils import get_dict_arg
NotGiven = object()
class IsDict(DirtyEquals[dict[Any, Any]]):
"""
Base class for comparing dictionaries. By d... | 235 | 8,285 |
dirty-equals | docs/plugins.py | .py | import logging
import os
import re
from mkdocs.config import Config
from mkdocs.structure.files import Files
from mkdocs.structure.pages import Page
try:
import pytest
except ImportError:
pytest = None
logger = logging.getLogger('mkdocs.test_examples')
def on_pre_build(config: Config):
pass
def on_fi... | 77 | 2,526 |
dirty-equals | tests/mypy_checks.py | .py | """
This module is run with mypy to check types can be used correctly externally.
"""
import sys
sys.path.append('.')
from dirty_equals import HasName, HasRepr, IsStr
assert 123 == HasName('int')
assert 123 == HasRepr('123')
assert 123 == HasName(IsStr(regex='i..'))
assert 123 == HasRepr(IsStr(regex=r'\d{3}'))
# t... | 18 | 436 |
dirty-equals | tests/test_numeric.py | .py | import pytest
from dirty_equals import (
IsApprox,
IsFloat,
IsFloatInf,
IsFloatInfNeg,
IsFloatInfPos,
IsFloatNan,
IsInt,
IsNegative,
IsNegativeFloat,
IsNegativeInt,
IsNonNegative,
IsNonPositive,
IsPositive,
IsPositiveFloat,
IsPositiveInt,
)
@pytest.mark.par... | 146 | 3,726 |
dirty-equals | tests/test_boolean.py | .py | import platform
import pytest
from dirty_equals import IsFalseLike, IsTrueLike
@pytest.mark.parametrize(
'other, expected',
[
(False, IsFalseLike),
(True, ~IsFalseLike),
([], IsFalseLike),
([1], ~IsFalseLike),
((), IsFalseLike),
('', IsFalseLike),
('',... | 86 | 2,401 |
dirty-equals | tests/test_pytest_report.py | .py | def test_anything_diff(pytester):
# see https://github.com/samuelcolvin/dirty-equals/issues/108
pytester.makepyfile("""
from dirty_equals import AnyThing
def test_dirty_equals_1():
leftdct = {"id": 1, "name": "AAA", "anything": [1, 2, 3]}
rightdct = {"id": 1, "name": "BBB", "anything": AnyThing()}
... | 95 | 3,077 |
dirty-equals | tests/test_datetime.py | .py | from datetime import date, datetime, timedelta, timezone
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from dirty_equals import IsDate, IsDatetime, IsNow, IsToday
@pytest.mark.parametrize(
'value,dirty,expect_match',
[
pytest.param(datetime(2000, 1, 1), IsDatetime(approx... | 196 | 9,031 |
dirty-equals | tests/test_inspection.py | .py | import pytest
from dirty_equals import AnyThing, HasAttributes, HasName, HasRepr, IsInstance, IsInt, IsStr
class Foo:
def __init__(self, a=1, b=2):
self.a = a
self.b = b
def spam(self):
pass
def dirty_repr(value):
if hasattr(value, 'equals'):
return repr(value)
retu... | 103 | 2,559 |
dirty-equals | tests/test_dict.py | .py | import pytest
from dirty_equals import IsDict, IsIgnoreDict, IsPartialDict, IsPositiveInt, IsStr, IsStrictDict
@pytest.mark.parametrize(
'input_value,expected',
[
({}, IsDict),
({}, IsDict()),
({'a': 1}, IsDict(a=1)),
({1: 2}, IsDict({1: 2})),
({'a': 1, 'b': 2}, IsDict... | 144 | 5,010 |
dirty-equals | tests/test_base.py | .py | import platform
from functools import singledispatch
import packaging.version
import pytest
from _pytest._io.pprint import PrettyPrinter
from dirty_equals import Contains, DirtyEquals, IsApprox, IsInt, IsList, IsNegative, IsOneOf, IsPositive, IsStr
from dirty_equals.version import VERSION
pprint = PrettyPrinter()
... | 227 | 5,127 |
dirty-equals | tests/test_strings.py | .py | import re
import pytest
from dirty_equals import IsAnyStr, IsBytes, IsStr
@pytest.mark.parametrize(
'value,dirty,match',
[
# IsStr tests
('foo', IsStr, True),
('foo', IsStr(), True),
(b'foo', IsStr, False),
('foo', IsStr(regex='fo{2}'), True),
('foo', IsStr(re... | 113 | 4,252 |
dirty-equals | tests/test_docs.py | .py | import platform
import sys
from pathlib import Path
import pytest
from pytest_examples import CodeExample, EvalExample, find_examples
root_dir = Path(__file__).parent.parent
examples = find_examples(
root_dir / 'dirty_equals',
root_dir / 'docs',
)
@pytest.mark.skipif(platform.python_implementation() == 'Py... | 42 | 1,507 |
dirty-equals | tests/test_other.py | .py | import sys
import uuid
from dataclasses import dataclass
from enum import Enum, auto
from hashlib import md5, sha1, sha256
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
import pytest
from dirty_equals import (
FunctionCheck,
IsDataclass,
IsDataclassType,
IsEnum,
IsHash,
... | 433 | 11,551 |
dirty-equals | tests/test_list_tuple.py | .py | import pytest
from dirty_equals import AnyThing, Contains, HasLen, IsInt, IsList, IsListOrTuple, IsNegative, IsTuple
@pytest.mark.parametrize(
'other,dirty',
[
([], IsList),
((), IsTuple),
([], IsList()),
([1], IsList(length=1)),
((), IsTuple()),
([1, 2, 3], Is... | 125 | 4,387 |
python-dotenv | tests/test_fifo_dotenv.py | .py | import os
import pathlib
import sys
import threading
import pytest
from dotenv import load_dotenv
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="FIFOs are Unix-only")
def test_load_dotenv_from_fifo(tmp_path: pathlib.Path, monkeypatch):
fifo = tmp_path / ".env"
os.mkfifo(fifo) # create na... | 32 | 743 |
python-dotenv | tests/test_lib.py | .py | import subprocess
from pathlib import Path
from typing import Sequence
def run_dotenv(
args: Sequence[str],
cwd: str | Path | None = None,
env: dict | None = None,
) -> subprocess.CompletedProcess:
"""
Run the `dotenv` CLI in a subprocess with the given arguments.
"""
process = subprocess... | 47 | 1,122 |
python-dotenv | tests/test_is_interactive.py | .py | import builtins
import sys
from unittest import mock
from dotenv.main import find_dotenv
class TestIsInteractive:
"""Tests for the _is_interactive helper function within find_dotenv.
The _is_interactive function is used by find_dotenv to determine if the code
is running in an interactive environment (li... | 233 | 8,921 |
python-dotenv | tests/test_parser.py | .py | import io
import pytest
from dotenv.parser import Binding, Original, parse_stream
@pytest.mark.parametrize(
"test_input,expected",
[
("", []),
(
"a=b",
[
Binding(
key="a",
value="b",
original=... | 583 | 15,343 |
python-dotenv | tests/test_variables.py | .py | import pytest
from dotenv.variables import Literal, Variable, parse_variables
@pytest.mark.parametrize(
"value,expected",
[
("", []),
("a", [Literal(value="a")]),
("${a}", [Variable(name="a", default=None)]),
("${a:-b}", [Variable(name="a", default="b")]),
(
... | 36 | 884 |
python-dotenv | tests/test_zip_imports.py | .py | import os
import posixpath
import subprocess
import sys
import textwrap
from typing import List
from unittest import mock
from zipfile import ZipFile
def walk_to_root(path: str):
last_dir = None
current_dir = path
while last_dir != current_dir:
yield current_dir
parent_dir = posixpath.dirn... | 110 | 2,864 |
python-dotenv | tests/test_ipython.py | .py | import os
import sys
from unittest import mock
import pytest
pytest.importorskip("IPython")
@pytest.mark.skipif(
sys.platform == "win32", reason="This test assumes case-sensitive variable names"
)
@mock.patch.dict(os.environ, {}, clear=True)
def test_ipython_existing_variable_no_override(tmp_path):
from IPy... | 64 | 1,739 |
python-dotenv | tests/test_cli.py | .py | import os
from pathlib import Path
from typing import Optional
import pytest
import dotenv
from dotenv.cli import cli as dotenv_cli
from dotenv.version import __version__
from tests.test_lib import check_process, run_dotenv
@pytest.mark.parametrize(
"output_format,content,expected",
(
(None, "x='a b... | 296 | 8,135 |
python-dotenv | tests/test_main.py | .py | import io
import logging
import os
import stat
import subprocess
import sys
import textwrap
from unittest import mock
import pytest
import dotenv
from dotenv.main import DotEnv
def test_set_key_no_file(tmp_path):
nx_path = tmp_path / "nx"
logger = logging.getLogger("dotenv.main")
with mock.patch.object... | 711 | 19,894 |
python-dotenv | tests/test_utils.py | .py | from dotenv import get_cli_string as c
def test_to_cli_string():
assert c() == "dotenv"
assert c(path="/etc/.env") == "dotenv -f /etc/.env"
assert c(path="/etc/.env", action="list") == "dotenv -f /etc/.env list"
assert c(action="list") == "dotenv list"
assert c(action="get", key="DEBUG") == "doten... | 20 | 747 |
python-dotenv | tests/conftest.py | .py | import pytest
from click.testing import CliRunner
@pytest.fixture
def cli():
runner = CliRunner()
with runner.isolated_filesystem():
yield runner
@pytest.fixture
def dotenv_path(tmp_path):
path = tmp_path / ".env"
path.write_bytes(b"")
yield path
| 17 | 279 |
python-dotenv | src/dotenv/parser.py | .py | import codecs
import re
from typing import (
IO,
Iterator,
Match,
NamedTuple,
Optional,
Pattern,
Sequence,
)
def make_regex(string: str, extra_flags: int = 0) -> Pattern[str]:
return re.compile(string, re.UNICODE | extra_flags)
_newline = make_regex(r"(\r\n|\n|\r)")
_multiline_whites... | 183 | 5,202 |
python-dotenv | src/dotenv/main.py | .py | import io
import logging
import os
import pathlib
import stat
import sys
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union
from .parser import Binding, parse_stream
from .variables import parse_vari... | 483 | 14,866 |
python-dotenv | src/dotenv/__main__.py | .py | """Entry point for cli, enables execution with `python -m dotenv`"""
from .cli import cli
if __name__ == "__main__":
cli()
| 7 | 129 |
python-dotenv | src/dotenv/__init__.py | .py | from typing import Any, Optional
from .main import dotenv_values, find_dotenv, get_key, load_dotenv, set_key, unset_key
def load_ipython_extension(ipython: Any) -> None:
from .ipython import load_ipython_extension
load_ipython_extension(ipython)
def get_cli_string(
path: Optional[str] = None,
acti... | 52 | 1,230 |
python-dotenv | src/dotenv/variables.py | .py | import re
from abc import ABCMeta, abstractmethod
from typing import Iterator, Mapping, Optional, Pattern
_posix_variable: Pattern[str] = re.compile(
r"""
\$\{
(?P<name>[^\}:]*)
(?::-
(?P<default>[^\}]*)
)?
\}
""",
re.VERBOSE,
)
class Atom(metaclass=ABCMeta):
... | 87 | 2,348 |
python-dotenv | src/dotenv/ipython.py | .py | from IPython.core.magic import Magics, line_magic, magics_class # type: ignore
from IPython.core.magic_arguments import (
argument,
magic_arguments,
parse_argstring,
) # type: ignore
from .main import find_dotenv, load_dotenv
@magics_class
class IPythonDotEnv(Magics):
@magic_arguments()
@argume... | 51 | 1,326 |
python-dotenv | src/dotenv/cli.py | .py | import json
import os
import shlex
import sys
from contextlib import contextmanager
from typing import IO, Any, Dict, Iterator, List, Optional
if sys.platform == "win32":
from subprocess import Popen
try:
import click
except ImportError:
sys.stderr.write(
"It seems python-dotenv is not installed w... | 248 | 6,865 |
tomli | setup.py | .py | import os
from setuptools import setup # type: ignore[import-untyped]
if os.environ.get("TOMLI_USE_MYPYC") == "1":
import glob
from mypyc.build import mypycify
files = glob.glob("src/**/*.py", recursive=True)
ext_modules = mypycify(files)
else:
ext_modules = []
setup(ext_modules=ext_modules)
| 16 | 319 |
tomli | profiler/profiler_script.py | .py | """A script for profiling.
To generate and read results:
- `tox -e profile`
- `firefox .tox/prof/output.svg`
"""
from pathlib import Path
import tomli
benchmark_toml = (
(Path(__file__).parent.parent / "benchmark" / "data.toml").read_bytes().decode()
)
# Run this a few times to emphasize over imports and o... | 19 | 395 |
tomli | fuzzer/fuzz.py | .py | import atheris
with atheris.instrument_imports():
from math import isnan
import sys
import warnings
import tomli_w
import tomli
# Disable any caching used so that the same lines of code run
# on a given input consistently.
tomli._re.cached_tz = tomli._re.cached_tz.__wrapped__
# Suppress all war... | 80 | 2,132 |
tomli | tests/burntsushi.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
"""Utilities for tests that are in the "burntsushi" format."""
import datetime
from typing import Any
def convert(obj):
if isinstance(obj, str):
return {"type": "string", "value... | 104 | 3,172 |
tomli | tests/test_misc.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
import copy
import datetime
from decimal import Decimal as D
import importlib
from pathlib import Path
import subprocess
import sys
import tempfile
import textwrap
import unittest
from . impo... | 178 | 6,113 |
tomli | tests/test_error.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
from __future__ import annotations
from typing import Any
import unittest
from . import tomllib
class TestError(unittest.TestCase):
def test_line_and_col(self):
with self.asser... | 105 | 3,852 |
tomli | tests/test_data.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
import json
from pathlib import Path
import unittest
from . import burntsushi, tomllib
DATA_DIR = Path(__file__).parent / "data"
VALID_FILES = tuple((DATA_DIR / "valid").glob("**/*.toml"))
... | 48 | 1,689 |
tomli | scripts/use_setuptools.py | .py | """Script that switches build backend to setuptools with mypyc support.
Overwrites pyproject.toml. Does not create a backup.
"""
from pathlib import Path
import tomllib
import tomli_w # type: ignore[import-not-found]
def use_setuptools() -> None:
pyproject_path = Path(__file__).parent.parent / "pyproject.toml... | 24 | 646 |
tomli | benchmark/run.py | .py | from __future__ import annotations
from collections.abc import Callable
from pathlib import Path
import timeit
import pytomlpp
import rtoml
import toml
import tomlkit
import tomli
def benchmark(
name: str,
run_count: int,
func: Callable,
col_width: tuple,
compare_to: float | None = None,
) -> f... | 60 | 2,103 |
tomli | src/tomli/_parser.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
from __future__ import annotations
# Defer loading regular expressions until we actually need them in
# parse_value().
__lazy_modules__ = ["tomli._re"]
import sys
from ._re import (
RE_... | 800 | 26,622 |
tomli | src/tomli/_types.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
from typing import Any, Callable, Tuple
# Type annotations
ParseFloat = Callable[[str], Any]
Key = Tuple[str, ...]
Pos = int
| 11 | 254 |
tomli | src/tomli/_re.py | .py | # SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
# Licensed to PSF under a Contributor Agreement.
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from functools import lru_cache
import re
TYPE_CHECKING = False
if TYPE_CHECKING:
... | 120 | 3,396 |
textual | tools/widget_documentation.py | .py | """
Helper script to help document all widgets.
This goes through the widgets listed in textual.widgets and prints the scaffolding
for the tables that are used to document the classvars BINDINGS and COMPONENT_CLASSES.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import textual.widgets
if ... | 80 | 2,127 |
textual | docs/blog/images/gen_inspect.py | .py | from rich import inspect
from rich.console import Console
c = Console(record=True, width=110)
f = open("foo.txt", "w")
inspect(f, console=c)
c.save_svg("inspect1.svg")
inspect(f, console=c, methods=True)
c.save_svg("inspect2.svg")
inspect(f, console=c, methods=True, help=True)
c.save_svg("inspect3.svg")
| 18 | 312 |
textual | docs/blog/snippets/2022-12-07-responsive-app-background-task/blocking01.py | .py | import time
from random import randint
from textual.app import App, ComposeResult
from textual.color import Color
from textual.containers import Grid, VerticalScroll
from textual.widget import Widget
from textual.widgets import Footer, Label
class ColourChanger(Widget): # (1)!
def on_click(self) -> None:
... | 41 | 904 |
textual | docs/blog/snippets/2022-12-07-responsive-app-background-task/nonblocking01.py | .py | import asyncio
from random import randint
from textual.app import App, ComposeResult
from textual.color import Color
from textual.containers import Grid, VerticalScroll
from textual.widget import Widget
from textual.widgets import Footer, Label
class ColourChanger(Widget):
def on_click(self) -> None:
sel... | 45 | 1,072 |
textual | docs/blog/snippets/2022-12-07-responsive-app-background-task/blocking02.py | .py | import asyncio
import time
from random import randint
from textual.app import App, ComposeResult
from textual.color import Color
from textual.containers import Grid, VerticalScroll
from textual.widget import Widget
from textual.widgets import Footer, Label
class ColourChanger(Widget):
def on_click(self) -> None:... | 45 | 1,015 |
textual | docs/examples/themes/colored_text.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label
COLORS = ("primary", "secondary", "accent", "warning", "error", "success")
class ColoredText(App[None]):
CSS = "\n".join(f".text-{color} {{color: $text-{color};}}" for color in COLORS)
def compose(self) -> ComposeResult:
fo... | 18 | 469 |
textual | docs/examples/themes/todo_app.py | .py | from itertools import cycle
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.widgets import Footer, Header, Input, Label, SelectionList
class TodoList(App[None]):
CSS = """
Screen {
align: center middle;
hatch:... | 97 | 2,176 |
textual | docs/examples/themes/muted_backgrounds.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label
COLORS = ("primary", "secondary", "accent", "warning", "error", "success")
class MutedBackgrounds(App[None]):
CSS = "\n".join(
f".text-{color} {{padding: 0 1; color: $text-{color}; background: ${color}-muted;}}"
for colo... | 21 | 561 |
textual | docs/examples/widgets/directory_tree_filtered.py | .py | from pathlib import Path
from typing import Iterable
from textual.app import App, ComposeResult
from textual.widgets import DirectoryTree
class FilteredDirectoryTree(DirectoryTree):
def filter_paths(self, paths: Iterable[Path]) -> Iterable[Path]:
return [path for path in paths if not path.name.startswith... | 21 | 512 |
textual | docs/examples/widgets/tabbed_content.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Footer, Label, Markdown, TabbedContent, TabPane
LETO = """
# Duke Leto I Atreides
Head of House Atreides.
"""
JESSICA = """
# Lady Jessica
Bene Gesserit and concubine of Leto, and mother of Paul and Alia.
"""
PAUL = """
# Paul Atreides
Son of ... | 58 | 1,467 |
textual | docs/examples/widgets/header.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Header
class HeaderApp(App):
def compose(self) -> ComposeResult:
yield Header()
if __name__ == "__main__":
app = HeaderApp()
app.run()
| 13 | 230 |
textual | docs/examples/widgets/data_table_cursors.py | .py | from itertools import cycle
from textual.app import App, ComposeResult
from textual.widgets import DataTable
ROWS = [
("lane", "swimmer", "country", "time"),
(4, "Joseph Schooling", "Singapore", 50.39),
(2, "Michael Phelps", "United States", 51.14),
(5, "Chad le Clos", "South Africa", 51.14),
(6, ... | 41 | 1,110 |
textual | docs/examples/widgets/progress_bar_styled_.py | .py | from textual.app import App, ComposeResult
from textual.clock import MockClock
from textual.containers import Center, Middle
from textual.timer import Timer
from textual.widgets import Footer, ProgressBar
class StyledProgressBar(App[None]):
BINDINGS = [("s", "start", "Start")]
CSS_PATH = "progress_bar_styled.... | 53 | 1,693 |
textual | docs/examples/widgets/data_table_fixed.py | .py | from textual.app import App, ComposeResult
from textual.widgets import DataTable
class TableApp(App):
CSS = "DataTable {height: 1fr}"
def compose(self) -> ComposeResult:
yield DataTable()
def on_mount(self) -> None:
table = self.query_one(DataTable)
table.focus()
table.ad... | 26 | 645 |
textual | docs/examples/widgets/input_types.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Input
class InputApp(App):
def compose(self) -> ComposeResult:
yield Input(placeholder="An integer", type="integer")
yield Input(placeholder="A number", type="number")
if __name__ == "__main__":
app = InputApp()
app.r... | 14 | 325 |
textual | docs/examples/widgets/label.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label
class LabelApp(App):
def compose(self) -> ComposeResult:
yield Label("Hello, world!")
if __name__ == "__main__":
app = LabelApp()
app.run()
| 13 | 241 |
textual | docs/examples/widgets/footer.py | .py | from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import Footer
class FooterApp(App):
BINDINGS = [
Binding(key="q", action="quit", description="Quit the app"),
Binding(
key="question_mark",
action="help",
descrip... | 26 | 680 |
textual | docs/examples/widgets/directory_tree.py | .py | from textual.app import App, ComposeResult
from textual.widgets import DirectoryTree
class DirectoryTreeApp(App):
def compose(self) -> ComposeResult:
yield DirectoryTree("./")
if __name__ == "__main__":
app = DirectoryTreeApp()
app.run()
| 13 | 262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.