Skip to content

Commit

Permalink
Format
Browse files Browse the repository at this point in the history
  • Loading branch information
maffoo committed Nov 30, 2020
1 parent 2496fc9 commit a61e51b
Show file tree
Hide file tree
Showing 683 changed files with 35,581 additions and 35,308 deletions.
5 changes: 4 additions & 1 deletion cirq/__init__.py
Expand Up @@ -25,6 +25,7 @@
_doc,
type_workarounds,
)

with _import.delay_import('cirq.protocols'):
from cirq import (
# Core
Expand Down Expand Up @@ -55,6 +56,7 @@
testing,
contrib,
)

# End dependency order list of sub-modules

from cirq._version import (
Expand Down Expand Up @@ -537,7 +539,8 @@
)

from cirq.vis import (
Heatmap,)
Heatmap,
)

from cirq.work import (
CircuitSampleJob,
Expand Down
98 changes: 52 additions & 46 deletions cirq/_compat.py
Expand Up @@ -31,10 +31,7 @@ def proper_repr(value: Any) -> str:

# HACK: work around https://github.com/sympy/sympy/issues/16074
# (only handles a few cases)
fixed_tokens = [
'Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float',
'Rational'
]
fixed_tokens = ['Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float', 'Rational']
for token in fixed_tokens:
result = result.replace(token, 'sympy.' + token)

Expand All @@ -44,22 +41,27 @@ def proper_repr(value: Any) -> str:
return 'np.array({!r}, dtype=np.{})'.format(value.tolist(), value.dtype)

if isinstance(value, pd.MultiIndex):
return (f'pd.MultiIndex.from_tuples({repr(list(value))}, '
f'names={repr(list(value.names))})')
return (
f'pd.MultiIndex.from_tuples({repr(list(value))}, ' f'names={repr(list(value.names))})'
)

if isinstance(value, pd.Index):
return (f'pd.Index({repr(list(value))}, '
f'name={repr(value.name)}, '
f'dtype={repr(str(value.dtype))})')
return (
f'pd.Index({repr(list(value))}, '
f'name={repr(value.name)}, '
f'dtype={repr(str(value.dtype))})'
)

if isinstance(value, pd.DataFrame):
cols = [value[col].tolist() for col in value.columns]
rows = list(zip(*cols))
return (f'pd.DataFrame('
f'\n columns={proper_repr(value.columns)}, '
f'\n index={proper_repr(value.index)}, '
f'\n data={repr(rows)}'
f'\n)')
return (
f'pd.DataFrame('
f'\n columns={proper_repr(value.columns)}, '
f'\n index={proper_repr(value.index)}, '
f'\n data={repr(rows)}'
f'\n)'
)

return repr(value)

Expand All @@ -77,13 +79,13 @@ def proper_eq(a: Any, b: Any) -> bool:
if isinstance(a, (pd.DataFrame, pd.Index, pd.MultiIndex)):
return a.equals(b)
if isinstance(a, (tuple, list)):
return len(a) == len(b) and all(
proper_eq(x, y) for x, y in zip(a, b))
return len(a) == len(b) and all(proper_eq(x, y) for x, y in zip(a, b))
return a == b


def deprecated(*, deadline: str, fix: str,
name: Optional[str] = None) -> Callable[[Callable], Callable]:
def deprecated(
*, deadline: str, fix: str, name: Optional[str] = None
) -> Callable[[Callable], Callable]:
"""Marks a function as deprecated.
Args:
Expand All @@ -98,32 +100,34 @@ def deprecated(*, deadline: str, fix: str,
"""

def decorator(func: Callable) -> Callable:

@functools.wraps(func)
def decorated_func(*args, **kwargs) -> Any:
qualname = (func.__qualname__ if name is None else name)
qualname = func.__qualname__ if name is None else name
warnings.warn(
f'{qualname} was used but is deprecated.\n'
f'It will be removed in cirq {deadline}.\n'
f'{fix}\n',
DeprecationWarning,
stacklevel=2)
stacklevel=2,
)

return func(*args, **kwargs)

decorated_func.__doc__ = (
f'THIS FUNCTION IS DEPRECATED.\n\n'
f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n'
f'{fix}\n\n'
f'{decorated_func.__doc__ or ""}')
f'{decorated_func.__doc__ or ""}'
)

return decorated_func

return decorator


def deprecated_class(*, deadline: str, fix: str,
name: Optional[str] = None) -> Callable[[Type], Type]:
def deprecated_class(
*, deadline: str, fix: str, name: Optional[str] = None
) -> Callable[[Type], Type]:
"""Marks a class as deprecated.
Args:
Expand All @@ -141,37 +145,40 @@ def decorator(clazz: Type) -> Type:
clazz_new = clazz.__new__

def patched_new(cls, *args, **kwargs):
qualname = (clazz.__qualname__ if name is None else name)
qualname = clazz.__qualname__ if name is None else name
warnings.warn(
f'{qualname} was used but is deprecated.\n'
f'It will be removed in cirq {deadline}.\n'
f'{fix}\n',
DeprecationWarning,
stacklevel=2)
stacklevel=2,
)

return clazz_new(cls)

setattr(clazz, '__new__', patched_new)
clazz.__doc__ = (f'THIS CLASS IS DEPRECATED.\n\n'
f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n'
f'{fix}\n\n'
f'{clazz.__doc__ or ""}')
clazz.__doc__ = (
f'THIS CLASS IS DEPRECATED.\n\n'
f'IT WILL BE REMOVED IN `cirq {deadline}`.\n\n'
f'{fix}\n\n'
f'{clazz.__doc__ or ""}'
)

return clazz

return decorator


def deprecated_parameter(
*,
deadline: str,
fix: str,
func_name: Optional[str] = None,
parameter_desc: str,
match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool],
rewrite: Optional[
Callable[[Tuple[Any, ...], Dict[str, Any]],
Tuple[Tuple[Any, ...], Dict[str, Any]]]] = None,
*,
deadline: str,
fix: str,
func_name: Optional[str] = None,
parameter_desc: str,
match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool],
rewrite: Optional[
Callable[[Tuple[Any, ...], Dict[str, Any]], Tuple[Tuple[Any, ...], Dict[str, Any]]]
] = None,
) -> Callable[[Callable], Callable]:
"""Marks a function parameter as deprecated.
Expand Down Expand Up @@ -199,22 +206,21 @@ def deprecated_parameter(
"""

def decorator(func: Callable) -> Callable:

@functools.wraps(func)
def decorated_func(*args, **kwargs) -> Any:
if match(args, kwargs):
if rewrite is not None:
args, kwargs = rewrite(args, kwargs)

qualname = (func.__qualname__
if func_name is None else func_name)
qualname = func.__qualname__ if func_name is None else func_name
warnings.warn(
f'The {parameter_desc} parameter of {qualname} was '
f'used but is deprecated.\n'
f'It will be removed in cirq {deadline}.\n'
f'{fix}\n',
DeprecationWarning,
stacklevel=2)
stacklevel=2,
)

return func(*args, **kwargs)

Expand All @@ -223,8 +229,7 @@ def decorated_func(*args, **kwargs) -> Any:
return decorator


def wrap_module(module: ModuleType,
deprecated_attributes: Dict[str, Tuple[str, str]]):
def wrap_module(module: ModuleType, deprecated_attributes: Dict[str, Tuple[str, str]]):
"""Wrap a module with deprecated attributes that give warnings.
Args:
Expand All @@ -251,7 +256,8 @@ def __getattr__(self, name):
f'It will be removed in cirq {deadline}.\n'
f'{fix}\n',
DeprecationWarning,
stacklevel=2)
stacklevel=2,
)
return getattr(module, name)

return Wrapped(module.__name__, module.__doc__)
72 changes: 39 additions & 33 deletions cirq/_compat_test.py
Expand Up @@ -19,8 +19,14 @@
import sympy

import cirq.testing
from cirq._compat import (proper_repr, deprecated, deprecated_parameter,
proper_eq, wrap_module, deprecated_class)
from cirq._compat import (
proper_repr,
deprecated,
deprecated_parameter,
proper_eq,
wrap_module,
deprecated_class,
)


def test_proper_repr():
Expand All @@ -35,24 +41,27 @@ def test_proper_repr():


def test_proper_repr_data_frame():
df = pd.DataFrame(index=[1, 2, 3],
data=[[11, 21.0], [12, 22.0], [13, 23.0]],
columns=['a', 'b'])
df = pd.DataFrame(
index=[1, 2, 3], data=[[11, 21.0], [12, 22.0], [13, 23.0]], columns=['a', 'b']
)
df2 = eval(proper_repr(df))
assert df2['a'].dtype == np.int64
assert df2['b'].dtype == np.float
pd.testing.assert_frame_equal(df2, df)

df = pd.DataFrame(index=pd.Index([1, 2, 3], name='test'),
data=[[11, 21.0], [12, 22.0], [13, 23.0]],
columns=['a', 'b'])
df = pd.DataFrame(
index=pd.Index([1, 2, 3], name='test'),
data=[[11, 21.0], [12, 22.0], [13, 23.0]],
columns=['a', 'b'],
)
df2 = eval(proper_repr(df))
pd.testing.assert_frame_equal(df2, df)

df = pd.DataFrame(index=pd.MultiIndex.from_tuples([(1, 2), (2, 3), (3, 4)],
names=['x', 'y']),
data=[[11, 21.0], [12, 22.0], [13, 23.0]],
columns=pd.Index(['a', 'b'], name='c'))
df = pd.DataFrame(
index=pd.MultiIndex.from_tuples([(1, 2), (2, 3), (3, 4)], names=['x', 'y']),
data=[[11, 21.0], [12, 22.0], [13, 23.0]],
columns=pd.Index(['a', 'b'], name='c'),
)
df2 = eval(proper_repr(df))
pd.testing.assert_frame_equal(df2, df)

Expand All @@ -72,43 +81,39 @@ def test_proper_eq():


def test_deprecated_with_name():

@deprecated(deadline='vNever', fix='Roll some dice.', name='test_func')
def f(a, b):
return a + b

with cirq.testing.assert_logs('test_func was used',
'will be removed in cirq vNever',
'Roll some dice.'):
with cirq.testing.assert_logs(
'test_func was used', 'will be removed in cirq vNever', 'Roll some dice.'
):
assert f(1, 2) == 3


def test_deprecated():

def new_func(a, b):
return a + b

@deprecated(deadline='vNever', fix='Roll some dice.')
def old_func(*args, **kwargs):
return new_func(*args, **kwargs)

with cirq.testing.assert_logs('old_func was used',
'will be removed in cirq vNever',
'Roll some dice.'):
with cirq.testing.assert_logs(
'old_func was used', 'will be removed in cirq vNever', 'Roll some dice.'
):
assert old_func(1, 2) == 3


def test_deprecated_parameter():

@deprecated_parameter(
deadline='vAlready',
fix='Double it yourself.',
func_name='test_func',
parameter_desc='double_count',
match=lambda args, kwargs: 'double_count' in kwargs,
rewrite=lambda args, kwargs: (args, {
'new_count': kwargs['double_count'] * 2
}))
rewrite=lambda args, kwargs: (args, {'new_count': kwargs['double_count'] * 2}),
)
def f(new_count):
return new_count

Expand All @@ -118,8 +123,10 @@ def f(new_count):
assert f(new_count=1) == 1

with cirq.testing.assert_logs(
'double_count parameter of test_func was used',
'will be removed in cirq vAlready', 'Double it yourself.'):
'double_count parameter of test_func was used',
'will be removed in cirq vAlready',
'Double it yourself.',
):
# pylint: disable=unexpected-keyword-arg
# pylint: disable=no-value-for-parameter
assert f(double_count=1) == 2
Expand All @@ -145,19 +152,17 @@ def test_wrap_module():
assert 'zoo' not in wrapped.__dict__

# Deprecation capability.
with cirq.testing.assert_logs('foo was used but is deprecated.',
'will be removed in cirq 0.6.0',
'use bar instead'):
with cirq.testing.assert_logs(
'foo was used but is deprecated.', 'will be removed in cirq 0.6.0', 'use bar instead'
):
_ = wrapped.foo

with cirq.testing.assert_logs(count=0):
_ = wrapped.bar


def test_deprecated_class():

class NewClass:

def __init__(self, a):
self._a = a

Expand All @@ -179,8 +184,9 @@ class OldClass(NewClass):
assert OldClass.__doc__.startswith("THIS CLASS IS DEPRECATED")
assert "OldClass docs" in OldClass.__doc__

with cirq.testing.assert_logs('foo was used but is deprecated',
'will be removed in cirq deadline', 'theFix'):
with cirq.testing.assert_logs(
'foo was used but is deprecated', 'will be removed in cirq deadline', 'theFix'
):
old_obj = OldClass("1")
assert repr(old_obj) == "NewClass: 1"
assert "OldClass" in old_obj.hello()

0 comments on commit a61e51b

Please sign in to comment.