Skip to content

Commit

Permalink
Merge pull request #20 from dangle/black
Browse files Browse the repository at this point in the history
Blackify the code base.
  • Loading branch information
dangle committed Oct 11, 2018
2 parents ea98a18 + eed0ad3 commit 62afa5f
Show file tree
Hide file tree
Showing 9 changed files with 304 additions and 210 deletions.
16 changes: 16 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[tool.black]
line-length = 79
exclude = '''
/(
\.eggs
| \.git
| \.mypy_cache
| \.pytest_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
67 changes: 34 additions & 33 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,40 +9,41 @@


setup(
name='typet',
name="typet",
use_scm_version=True,
description='A library of types that simplify working with typed Python.',
long_description=open('README.rst').read(),
author='Melissa Nuño',
author_email='dangle@contains.io',
url='https://github.com/contains-io/typet',
keywords=['typing', 'schema' 'validation', 'types', 'annotation',
'PEP 483', 'PEP 484', 'PEP 526'],
license='MIT',
packages=find_packages(exclude=['tests', 'docs']),
install_requires=[
'pathlib2',
'typingplus >= 2.2.1, < 3'
description="A library of types that simplify working with typed Python.",
long_description=open("README.rst").read(),
author="Melissa Nuño",
author_email="dangle@contains.io",
url="https://github.com/contains-io/typet",
keywords=[
"typing",
"schema" "validation",
"types",
"annotation",
"PEP 483",
"PEP 484",
"PEP 526",
],
setup_requires=[
'pytest-runner',
'setuptools_scm',
],
tests_require=['pytest >= 3.2'],
license="MIT",
packages=find_packages(exclude=["tests", "docs"]),
install_requires=["pathlib2", "typingplus >= 2.2.1, < 3"],
setup_requires=["pytest-runner", "setuptools_scm"],
tests_require=["pytest >= 3.2"],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: PyPy',
'Intended Audience :: Developers',
'Topic :: Software Development',
]
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: PyPy",
"Intended Audience :: Developers",
"Topic :: Software Development",
],
)
18 changes: 13 additions & 5 deletions tests/py36/test_typed_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,46 @@

def test_strict_object():
"""Simple test to verify basic StrictObject functionality."""

class X(typet.StrictObject):
x: str
x = X('initial')
x.x = 'hello'

x = X("initial")
x.x = "hello"
assert isinstance(x.x, str)
assert x.x == 'hello'
assert x.x == "hello"
with pytest.raises(TypeError):
x.x = 5


def test_object():
"""Simple test to verify basic Object functionality."""

class X(typet.Object):
x: str = None

x = X()
x.x = 5
assert isinstance(x.x, str)
assert x.x == '5'
assert x.x == "5"


def test_object_failure():
"""Simple test to verify basic Object failure functionality."""

class X(typet.Object):
x: int = None

x = X()
x.x = None
with pytest.raises(TypeError):
x.x = 'not an integer'
x.x = "not an integer"


def test_optional_unassigned():
"""Verify that an unassigned Optional attribute is optional in __init__."""

class X(typet.Object):
x: typing.Optional[int]

X()
72 changes: 42 additions & 30 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ def test_bounded_type():
BoundedInt(25)
BoundedStr = typet.Bounded[str, 1:5, len]
with pytest.raises(ValueError):
BoundedStr('')
assert BoundedStr('abc') == 'abc'
BoundedStr("")
assert BoundedStr("abc") == "abc"
with pytest.raises(ValueError):
BoundedStr('abcdef')
assert str(BoundedInt) == 'typet.validation.Bounded[int, 10:20]'
BoundedStr("abcdef")
assert str(BoundedInt) == "typet.validation.Bounded[int, 10:20]"
assert typet.Bounded[Any, 10:20](15) == 15
assert typet.Bounded['int', 20](15) == 15
assert typet.Bounded['int', 10:](15) == 15
assert typet.Bounded["int", 20](15) == 15
assert typet.Bounded["int", 10:](15) == 15


def test_length_type():
Expand All @@ -49,20 +49,20 @@ def test_length_type():
LengthBoundedStr = typet.Length[str, 10:20, lambda x: x]
LengthBoundedStr = typet.Length[str, 1:5]
with pytest.raises(ValueError):
LengthBoundedStr('')
assert LengthBoundedStr('a') == 'a'
assert LengthBoundedStr('abcde') == 'abcde'
LengthBoundedStr("")
assert LengthBoundedStr("a") == "a"
assert LengthBoundedStr("abcde") == "abcde"
with pytest.raises(ValueError):
LengthBoundedStr('abcdef')
LengthBoundedStr("abcdef")
LengthBoundedList = typet.Length[list, 1:1]
with pytest.raises(ValueError):
LengthBoundedList([])
assert LengthBoundedList([1]) == [1]
with pytest.raises(ValueError):
LengthBoundedList([1, 2])
assert str(LengthBoundedStr) == 'typet.validation.Length[str, 1:5]'
assert typet.Length[Any, 1:5]('abc') == 'abc'
assert typet.Length['str', 20]('abc') == 'abc'
assert str(LengthBoundedStr) == "typet.validation.Length[str, 1:5]"
assert typet.Length[Any, 1:5]("abc") == "abc"
assert typet.Length["str", 20]("abc") == "abc"


def test_string_type():
Expand All @@ -71,13 +71,13 @@ def test_string_type():
BoundedStr = typet.String[10:20, lambda x: x]
BoundedStr = typet.String[1:5]
with pytest.raises(ValueError):
BoundedStr('')
assert BoundedStr('a') == 'a'
assert BoundedStr('abcde') == 'abcde'
BoundedStr("")
assert BoundedStr("a") == "a"
assert BoundedStr("abcde") == "abcde"
with pytest.raises(ValueError):
BoundedStr('abcdef')
assert str(BoundedStr) == 'typet.validation.String[1:5]'
assert typet.String('hello') == 'hello'
BoundedStr("abcdef")
assert str(BoundedStr) == "typet.validation.String[1:5]"
assert typet.String("hello") == "hello"


def test_validation_type():
Expand All @@ -90,16 +90,18 @@ def test_validation_type():

def test_path_types():
"""Test that the supplied path validation paths work."""
assert str(typet.File(__file__))== __file__
assert str(typet.File(__file__)) == __file__
with pytest.raises(ValueError):
typet.File(str(uuid.uuid4()))
assert str(typet.Dir(os.path.dirname(__file__))) == os.path.dirname(
__file__)
__file__
)
with pytest.raises(ValueError):
typet.Dir(str(uuid.uuid4()))
assert str(typet.ExistingPath(__file__)) == __file__
assert str(typet.ExistingPath(
os.path.dirname(__file__))) == os.path.dirname(__file__)
assert str(
typet.ExistingPath(os.path.dirname(__file__))
) == os.path.dirname(__file__)
with pytest.raises(ValueError):
typet.ExistingPath(str(uuid.uuid4()))

Expand All @@ -111,6 +113,7 @@ def test_none_type():

def test_singleton():
"""Test that a singleton only allows a single instance of a class."""

@six.add_metaclass(typet.Singleton)
class TestClass(object):
pass
Expand All @@ -120,6 +123,7 @@ class TestClass(object):

def test_uninstantiable():
"""Test that an uninstantiable class cannot be instantiated."""

@six.add_metaclass(typet.Uninstantiable)
class TestClass(object):
pass
Expand All @@ -134,47 +138,55 @@ def test_isinstance():
assert isinstance(25, Age) is True
assert isinstance(-5, Age) is False
assert isinstance(200, Age) is False
assert isinstance('not an int', Age) is False
assert isinstance("not an int", Age) is False


def test_strict_object():
"""Simple test to verify basic StrictObject functionality."""

class X(typet.StrictObject):
x = None # type: str
x = X('initial')
x.x = 'hello'

x = X("initial")
x.x = "hello"
assert is_instance(x.x, str)
assert x.x == 'hello'
assert x.x == "hello"
with pytest.raises(TypeError):
x.x = 5


def test_object():
"""Simple test to verify basic Object functionality."""

class X(typet.Object):
x = None # type: Optional[str]

x = X()
x.x = 5
assert is_instance(x.x, str)
assert x.x == '5'
assert x.x == "5"


def test_object_comments():
"""Simple test to verify basic Object functionality with comment hints."""

class X(typet.Object):
x = None # type: str

with pytest.raises(TypeError):
X()
x = X(5)
assert is_instance(x.x, str)
assert x.x == '5'
assert x.x == "5"


def test_object_failure():
"""Simple test to verify basic Object failure functionality."""

class X(typet.Object):
x = None # type: Optional[int]

x = X()
x.x = None
with pytest.raises(TypeError):
x.x = 'not an integer'
x.x = "not an integer"
29 changes: 18 additions & 11 deletions typet/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@

from typingplus import ( # noqa: F401 pylint: disable=unused-import
Any,
Callable
Callable,
)
import six


__all__ = (
'metaclass',
'Singleton',
'singleton',
'IdempotentSingleton',
'Uninstantiable',
"metaclass",
"Singleton",
"singleton",
"IdempotentSingleton",
"Uninstantiable",
)


Expand All @@ -47,17 +47,23 @@ def metaclass(*metaclasses):
A decorator that will recreate the class using the specified
metaclasses.
"""

def _inner(cls):
# pragma pylint: disable=unused-variable
metabases = tuple(collections.OrderedDict( # noqa: F841
(c, None) for c in (metaclasses + (type(cls),))
).keys())
metabases = tuple(
collections.OrderedDict( # noqa: F841
(c, None) for c in (metaclasses + (type(cls),))
).keys()
)
# pragma pylint: enable=unused-variable
_Meta = metabases[0]
for base in metabases[1:]:

class _Meta(base, _Meta): # pylint: disable=function-redefined
pass

return six.add_metaclass(_Meta)(cls)

return _inner


Expand Down Expand Up @@ -95,7 +101,8 @@ def __call__(cls, *args, **kwargs):
"""Create one instance of the class and reinstantiate as necessary."""
if not cls.__instance__:
cls.__instance__ = super(IdempotentSingleton, cls).__call__(
*args, **kwargs)
*args, **kwargs
)
else:
try:
cls.__instance__.__init__(*args, **kwargs) # type: ignore
Expand All @@ -113,4 +120,4 @@ class Uninstantiable(type):
def __call__(cls, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Do not allow the class to be instantiated."""
raise TypeError('Type {} cannot be instantiated.'.format(cls.__name__))
raise TypeError("Type {} cannot be instantiated.".format(cls.__name__))
Loading

0 comments on commit 62afa5f

Please sign in to comment.