Skip to content

Commit 2627f79

Browse files
committed
remove Option setter/getter with current property
this makes it more similar to the Ref interface
1 parent c9e6869 commit 2627f79

File tree

12 files changed

+70
-53
lines changed

12 files changed

+70
-53
lines changed

src/idom/_option.py

+25-20
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ def __init__(
3333
self._mutable = mutable
3434
self._validator = validator
3535
if name in os.environ:
36-
self._value = validator(os.environ[name])
37-
logger.debug(f"{self._name}={self.get()}")
36+
self._current = validator(os.environ[name])
37+
logger.debug(f"{self._name}={self.current}")
3838
ALL_OPTIONS.add(self)
3939

4040
@property
@@ -52,39 +52,44 @@ def default(self) -> _O:
5252
"""This option's default value"""
5353
return self._default
5454

55+
@property
56+
def current(self) -> _O:
57+
try:
58+
return self._current
59+
except AttributeError:
60+
return self._default
61+
62+
@current.setter
63+
def current(self, new: _O) -> None:
64+
self.set_current(new)
65+
return None
66+
5567
def is_set(self) -> bool:
5668
"""Whether this option has a value other than its default."""
57-
return hasattr(self, "_value")
58-
59-
def get(self) -> _O:
60-
"""Get the current value of this option."""
61-
return cast(_O, getattr(self, "_value", self._default))
69+
return hasattr(self, "_current")
6270

63-
def set(self, new: Any) -> None:
71+
def set_current(self, new: Any) -> None:
6472
"""Set the value of this option
6573
6674
Raises a ``TypeError`` if this option is not :attr:`Option.mutable`.
6775
"""
6876
if not self._mutable:
6977
raise TypeError(f"{self} cannot be modified after initial load")
70-
self._value = self._validator(new)
71-
logger.debug(f"{self._name}={self._value}")
78+
self._current = self._validator(new)
79+
logger.debug(f"{self._name}={self._current}")
7280

7381
def set_default(self, new: _O) -> _O:
7482
"""Set the value of this option if not :meth:`Option.is_set`
7583
7684
Returns the current value (a la :meth:`dict.set_default`)
7785
"""
78-
if not hasattr(self, "_value"):
79-
self.set(new)
80-
return self._value
86+
if not hasattr(self, "_current"):
87+
self.set_current(new)
88+
return self._current
8189

8290
def reload(self) -> None:
83-
"""Reload this option from its environment variable
84-
85-
Returns the old value of the option.
86-
"""
87-
self.set(os.environ.get(self._name, self._default))
91+
"""Reload this option from its environment variable"""
92+
self.set_current(os.environ.get(self._name, self._default))
8893

8994
def reset(self) -> None:
9095
"""Reset the value of this option to its default setting
@@ -93,7 +98,7 @@ def reset(self) -> None:
9398
"""
9499
if not self._mutable:
95100
raise TypeError(f"{self} cannot be modified after initial load")
96-
delattr(self, "_value")
101+
delattr(self, "_current")
97102

98103
def __repr__(self) -> str:
99-
return f"Option({self._name}={self.get()!r})"
104+
return f"Option({self._name}={self.current!r})"

src/idom/cli.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ def options() -> None:
7070
table.add_column("Mutable")
7171

7272
for opt in options:
73-
value, default, mutable = list(map(str, [opt.get(), opt.default, opt.mutable]))
73+
value, default, mutable = list(
74+
map(str, [opt.current, opt.default, opt.mutable])
75+
)
7476
table.add_row(opt.name, value, default, mutable)
7577

7678
console.print(table)

src/idom/client/_private.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,24 @@
1616

1717

1818
def web_modules_dir() -> Path:
19-
return IDOM_CLIENT_BUILD_DIR.get().joinpath(
19+
return IDOM_CLIENT_BUILD_DIR.current.joinpath(
2020
*IDOM_CLIENT_IMPORT_SOURCE_URL_INFIX[1:].split("/")
2121
)
2222

2323

24-
if not IDOM_CLIENT_BUILD_DIR.get().exists(): # pragma: no cover
25-
shutil.copytree(BACKUP_BUILD_DIR, IDOM_CLIENT_BUILD_DIR.get(), symlinks=True)
24+
if not IDOM_CLIENT_BUILD_DIR.current.exists(): # pragma: no cover
25+
shutil.copytree(BACKUP_BUILD_DIR, IDOM_CLIENT_BUILD_DIR.current, symlinks=True)
2626

2727

2828
def restore_build_dir_from_backup() -> None:
29-
target = IDOM_CLIENT_BUILD_DIR.get()
29+
target = IDOM_CLIENT_BUILD_DIR.current
3030
if target.exists():
3131
shutil.rmtree(target)
3232
shutil.copytree(BACKUP_BUILD_DIR, target, symlinks=True)
3333

3434

3535
def replace_build_dir(source: Path) -> None:
36-
target = IDOM_CLIENT_BUILD_DIR.get()
36+
target = IDOM_CLIENT_BUILD_DIR.current
3737
if target.exists():
3838
shutil.rmtree(target)
3939
shutil.copytree(source, target, symlinks=True)
@@ -59,7 +59,7 @@ def split_package_name_and_version(pkg: str) -> Tuple[str, str]:
5959

6060

6161
def build_dependencies() -> Dict[str, str]:
62-
package_json = IDOM_CLIENT_BUILD_DIR.get() / "package.json"
62+
package_json = IDOM_CLIENT_BUILD_DIR.current / "package.json"
6363
return cast(Dict[str, str], json.loads(package_json.read_text())["dependencies"])
6464

6565

src/idom/client/manage.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def web_module_url(package_name: str) -> str:
4343
"""
4444
web_module_path(package_name, must_exist=True)
4545
return (
46-
IDOM_CLIENT_IMPORT_SOURCE_URL.get()
46+
IDOM_CLIENT_IMPORT_SOURCE_URL.current
4747
+ f"{_private.IDOM_CLIENT_IMPORT_SOURCE_URL_INFIX}/{package_name}.js"
4848
)
4949

src/idom/core/layout.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ async def render(self) -> LayoutUpdate:
121121
f"Did not render component - {component} already unmounted or does not belong to this layout"
122122
)
123123

124-
if IDOM_DEBUG_MODE.get():
124+
if IDOM_DEBUG_MODE.current:
125125
# If in debug mode inject a function that ensures all returned updates
126126
# contain valid VDOM models. We only do this in debug mode in order to
127127
# avoid unnecessarily impacting performance.
@@ -482,7 +482,7 @@ def _process_child_type_and_key(
482482
yield (child, child_type, key)
483483

484484

485-
if IDOM_FEATURE_INDEX_AS_DEFAULT_KEY.get():
485+
if IDOM_FEATURE_INDEX_AS_DEFAULT_KEY.current:
486486

487487
def _default_key(index: int) -> Any: # pragma: no cover
488488
return index

src/idom/log.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def logging_config_defaults() -> Any:
2121
"disable_existing_loggers": False,
2222
"loggers": {
2323
"idom": {
24-
"level": "DEBUG" if IDOM_DEBUG_MODE.get() else "INFO",
24+
"level": "DEBUG" if IDOM_DEBUG_MODE.current else "INFO",
2525
"handlers": ["console"],
2626
},
2727
},

src/idom/server/fastapi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def _setup_static_files(self, config: Config, app: FastAPI) -> None:
125125
app.mount(
126126
f"{url_prefix}/client",
127127
StaticFiles(
128-
directory=str(IDOM_CLIENT_BUILD_DIR.get()),
128+
directory=str(IDOM_CLIENT_BUILD_DIR.current),
129129
html=True,
130130
check_dir=True,
131131
),

src/idom/server/flask.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def _setup_blueprint_routes(self, config: Config, blueprint: Blueprint) -> None:
110110

111111
@blueprint.route("/client/<path:path>")
112112
def send_build_dir(path: str) -> Any:
113-
return send_from_directory(str(IDOM_CLIENT_BUILD_DIR.get()), path)
113+
return send_from_directory(str(IDOM_CLIENT_BUILD_DIR.current), path)
114114

115115
if config["redirect_root_to_index"]:
116116

src/idom/server/sanic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ async def sock_recv() -> LayoutEvent:
105105
await self._run_dispatcher(sock_send, sock_recv, component_params)
106106

107107
if config["serve_static_files"]:
108-
blueprint.static("/client", str(IDOM_CLIENT_BUILD_DIR.get()))
108+
blueprint.static("/client", str(IDOM_CLIENT_BUILD_DIR.current))
109109

110110
if config["redirect_root_to_index"]:
111111

src/idom/server/tornado.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def _create_route_handlers(self, config: Config) -> _RouteHandlerSpecs:
9797
(
9898
r"/client/(.*)",
9999
StaticFileHandler,
100-
{"path": str(IDOM_CLIENT_BUILD_DIR.get())},
100+
{"path": str(IDOM_CLIENT_BUILD_DIR.current)},
101101
)
102102
)
103103
if config["redirect_root_to_index"]:

tests/test__option.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -15,57 +15,57 @@ def test_option_repr():
1515
@mock.patch.dict(os.environ, {"A_FAKE_OPTION": "value-from-environ"})
1616
def test_option_from_os_environ():
1717
opt = Option("A_FAKE_OPTION", "default-value")
18-
assert opt.get() == "value-from-environ"
18+
assert opt.current == "value-from-environ"
1919

2020

2121
def test_option_from_default():
2222
opt = Option("A_FAKE_OPTION", "default-value")
23-
assert opt.get() == "default-value"
24-
assert opt.get() is opt.default
23+
assert opt.current == "default-value"
24+
assert opt.current is opt.default
2525

2626

2727
@mock.patch.dict(os.environ, {"A_FAKE_OPTION": "1"})
2828
def test_option_validator():
2929
opt = Option("A_FAKE_OPTION", False, validator=lambda x: bool(int(x)))
3030

31-
assert opt.get() is True
31+
assert opt.current is True
3232

33-
opt.set("0")
34-
assert opt.get() is False
33+
opt.current = "0"
34+
assert opt.current is False
3535

3636
with pytest.raises(ValueError, match="invalid literal for int"):
37-
opt.set("not-an-int")
37+
opt.current = "not-an-int"
3838

3939

4040
def test_immutable_option():
4141
opt = Option("A_FAKE_OPTION", "default-value", mutable=False)
4242
assert not opt.mutable
4343
with pytest.raises(TypeError, match="cannot be modified after initial load"):
44-
opt.set("a-new-value")
44+
opt.current = "a-new-value"
4545
with pytest.raises(TypeError, match="cannot be modified after initial load"):
4646
opt.reset()
4747

4848

4949
def test_option_reset():
5050
opt = Option("A_FAKE_OPTION", "default-value")
51-
opt.set("a-new-value")
51+
opt.current = "a-new-value"
5252
opt.reset()
53-
assert opt.get() is opt.default
53+
assert opt.current is opt.default
5454
assert not opt.is_set()
5555

5656

5757
@mock.patch.dict(os.environ, {"A_FAKE_OPTION": "value-from-environ"})
5858
def test_option_reload():
5959
opt = Option("A_FAKE_OPTION", "default-value")
60-
opt.set("some-other-value")
60+
opt.current = "some-other-value"
6161
opt.reload()
62-
assert opt.get() == "value-from-environ"
62+
assert opt.current == "value-from-environ"
6363

6464

6565
def test_option_set():
6666
opt = Option("A_FAKE_OPTION", "default-value")
6767
assert not opt.is_set()
68-
opt.set("a-new-value")
68+
opt.current = "a-new-value"
6969
assert opt.is_set()
7070

7171

tests/test_cli.py

+15-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import idom
77
from idom.cli import main
88
from idom.client.manage import _private, web_module_exists
9-
from idom.config import IDOM_CLIENT_BUILD_DIR
9+
from idom.config import IDOM_CLIENT_BUILD_DIR, IDOM_DEBUG_MODE
1010

1111

1212
cli_runner = CliRunner()
@@ -26,7 +26,8 @@ def assert_rich_table_equals(stdout, expected_header, expected_rows):
2626

2727
actual_header, *actual_rows = parsed_lines
2828

29-
assert actual_header == expected_header and actual_rows == expected_rows
29+
assert actual_header == list(map(str, expected_header))
30+
assert actual_rows == [list(map(str, row)) for row in expected_rows]
3031

3132

3233
@with_large_console
@@ -70,14 +71,23 @@ def test_show_version():
7071

7172
@with_large_console
7273
def test_show_options():
73-
build_dir = str(IDOM_CLIENT_BUILD_DIR.get())
7474
assert_rich_table_equals(
7575
cli_runner.invoke(main, ["options"]).stdout,
7676
["Name", "Value", "Default", "Mutable"],
7777
[
78-
["IDOM_CLIENT_BUILD_DIR", build_dir, build_dir, "True"],
78+
[
79+
"IDOM_CLIENT_BUILD_DIR",
80+
IDOM_CLIENT_BUILD_DIR.current,
81+
IDOM_CLIENT_BUILD_DIR.default,
82+
"True",
83+
],
7984
["IDOM_CLIENT_IMPORT_SOURCE_URL", "/client", "/client", "True"],
80-
["IDOM_DEBUG_MODE", "False", "False", "False"],
85+
[
86+
"IDOM_DEBUG_MODE",
87+
IDOM_DEBUG_MODE.current,
88+
IDOM_DEBUG_MODE.default,
89+
"False",
90+
],
8191
["IDOM_FEATURE_INDEX_AS_DEFAULT_KEY", "False", "False", "False"],
8292
],
8393
)

0 commit comments

Comments
 (0)