Skip to content

Commit

Permalink
Allow to set dunder attributes in FrozenSpaceMeta (#178)
Browse files Browse the repository at this point in the history
  • Loading branch information
janluke committed Mar 4, 2024
1 parent 00d6501 commit c375313
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 7 additions & 1 deletion cloup/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,13 @@ def __init__(cls, *args: Any):
type.__setattr__(cls, '_dict', d)

def __setattr__(cls, key: str, value: Any) -> None:
raise Exception("you can't set attributes on this class")
if key.startswith("__"):
return super().__setattr__(key, value)
else:
raise Exception(
"you can't set attributes on this class; only special dunder attributes "
"(e.g. __annotations__) are allowed to be set for compatibility reasons."
)

def asdict(cls) -> Dict[str, Any]:
return cls._dict # type: ignore
Expand Down
14 changes: 11 additions & 3 deletions tests/test_styling.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
from cloup.styling import Color, HelpTheme, Style


def test_help_theme_copywith():
def test_help_theme_copy_with():
s1, s2 = Style(), Style()
r1, r2 = Style(), Style()
theme = HelpTheme(heading=s1, col1=s2).with_(col1=r1, col2=r2)
assert theme == HelpTheme(heading=s1, col1=r1, col2=r2)


def test_help_theme_copywith_takes_the_same_parameters_of_constructor():
def test_help_theme_copy_with_takes_the_same_parameters_of_constructor():
def get_param_names(func):
params = inspect.signature(func).parameters
return list(params.keys())
Expand All @@ -38,17 +38,25 @@ def test_unsupported_style_args_are_ignored_in_click_7():
Style(overline=True, italic=True, strikethrough=True)


def test_Color():
def test_color_class():
# Check values of some attributes
assert Color.red == 'red'
assert Color.bright_blue == 'bright_blue'

# Check it's not instantiable
with pytest.raises(Exception, match="it's not instantiable"):
Color()

# Check only __dunder__ fields are settable
Color.__annotations__ = "whatever"
with pytest.raises(Exception, match="you can't set attributes on this class"):
Color.red = 'blue'

# Test __contains__
assert 'red' in Color
assert 'pippo' not in Color

# Test Color.asdict()
d = Color.asdict()
for k, v in d.items():
assert k in Color
Expand Down

0 comments on commit c375313

Please sign in to comment.