Skip to content

Commit

Permalink
Deprecate application var and remove Application.properties (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
kmagusiak authored Oct 19, 2022
1 parent 3cddb5d commit 7def0c3
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 34 deletions.
26 changes: 23 additions & 3 deletions alphaconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,28 @@
#######################################
# APPLICATION CONTEXT

"""The application context"""
application: ContextVar[Application] = ContextVar('application')
# DEPRECATED: reomove application
_application: ContextVar[Application] = ContextVar('application')


class DeprecatedWrapper(object):
def __init__(self, obj):
self._wrapped_obj = obj

def set_internal(self, app):
return self._wrapped_obj.set(app)

def __getattribute__(self, name):
import warnings

if name in ('set_internal', '__init__', '_wrapped_obj'):
return object.__getattribute__(self, name)
warnings.warn('alphaconf.application will be removed', DeprecationWarning)
return getattr(self._wrapped_obj, name)


application = DeprecatedWrapper(_application)
# END OF DEPRECATION
"""The current configuration"""
configuration: ContextVar[DictConfig] = ContextVar('configuration', default=OmegaConf.create())
"""Additional helpers for the application"""
Expand Down Expand Up @@ -193,7 +213,7 @@ def set_application(app: Application, merge: bool = False):
:param app: The application
:param merge: Wether to merge the current configuration with the application (default false)
"""
application.set(app)
application.set_internal(app)
config = app.configuration
if merge:
# merging 2 DictConfig objects
Expand Down
25 changes: 15 additions & 10 deletions alphaconf/internal/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ class Application:
"""

__config: Optional[DictConfig]
properties: Dict[str, str]
__name: str
version: Optional[str]
description: Optional[str]
short_description: Optional[str]
parsed: Optional[arg_parser.ParseResult]
argument_parser: arg_parser.ArgumentParser

def __init__(self, **properties) -> None:
def __init__(
self, *, name=None, version=None, description=None, short_description=None
) -> None:
"""Initialize the application.
Properties:
Expand All @@ -37,9 +42,10 @@ def __init__(self, **properties) -> None:
:param properties: Properties for the app
"""
self.__config = None # initialize
if not properties.get('name'):
properties['name'] = self.__get_default_name()
self.properties = properties
self.__name = name or self.__get_default_name()
self.version = version
self.description = description
self.short_description = short_description
# Add argument parser
self.__initialize_parser()

Expand Down Expand Up @@ -68,7 +74,7 @@ def _app_configuration(self) -> DictConfig:
{
'application': {
'name': self.name,
'version': self.properties.get('version'),
'version': self.version or '',
'uuid': str(uuid.uuid4()),
},
}
Expand All @@ -77,7 +83,7 @@ def _app_configuration(self) -> DictConfig:
@property
def name(self) -> str:
"""Get the name of the application"""
return self.properties['name']
return self.__name

@property
def configuration(self) -> DictConfig:
Expand Down Expand Up @@ -337,14 +343,13 @@ def __mask_config(obj, check, replace, path=''):
def print_help(self, *, usage=None, description=None, arguments=True):
"""Print the help message
Set the arguments to False to disable printing them."""
p = self.properties
if usage is None:
usage = f"usage: {p.get('name') or 'app'}"
usage = f"usage: {self.name or 'app'}"
usage += " [arguments] [key=value ...]"
if isinstance(usage, str):
print(usage)
if description is None:
description = p.get('description')
description = self.description
if isinstance(description, str):
print()
print(description)
Expand Down
9 changes: 4 additions & 5 deletions alphaconf/internal/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,10 @@ class VersionAction(Action):
"""Version action"""

def run(self, app):
p = app.properties
prog = p.get('name')
version = p.get('version')
prog = app.name
version = app.version
print(f"{prog} {version}")
desc = p.get('short_description')
desc = app.short_description
if desc:
print(desc)
raise ExitApplication
Expand Down Expand Up @@ -289,7 +288,7 @@ def configure_parser(parser: ArgumentParser, *, app=None):
'--help',
help="Show the help",
)
if app and app.properties.get('version'):
if app and app.version:
parser.add_argument(
VersionAction,
'-V',
Expand Down
22 changes: 6 additions & 16 deletions tests/test_alphaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ def application():
return alphaconf.Application(name='test', version='1.0.0', description='test description')


def test_default_app_and_configuration():
with pytest.raises(LookupError):
alphaconf.application.get()
def test_default_configuration():
config = alphaconf.configuration.get()
assert isinstance(config, DictConfig)
assert 'base' in config
Expand All @@ -26,16 +24,9 @@ def test_run():

def test_run_application_init():
name = 'testinit'
assert alphaconf.get('application') is None
r = alphaconf.run(lambda: alphaconf.get('application.name'), arguments=False, name=name)
assert name == r
# after a run, the application is not set
with pytest.raises(LookupError):
alphaconf.application.get()


def test_run_application_app(application):
r = alphaconf.run(lambda: alphaconf.application.get(), app=application, arguments=False)
assert r is application


def test_run_application_help(capsys):
Expand All @@ -49,15 +40,15 @@ def test_run_application_help(capsys):
assert 'usage:' in out[0]
assert application.name in out[0]
desc = '\n'.join(out[1:5])
assert application.properties['description'] in desc
assert application.description in desc
assert 'HELPER_TEST' in captured.out


def test_run_application_version(capsys, application):
alphaconf.run(lambda: 'n', app=application, arguments=['--version'], should_exit=False)
captured = capsys.readouterr()
out = captured.out
assert application.name + ' ' + application.properties['version'] in out
assert (application.name + ' ' + application.version) in out


def test_run_application_show_configuration(capsys, application):
Expand All @@ -81,13 +72,12 @@ def test_run_application_select_logging():


def test_set_application(application):
token = alphaconf.application.set(None)
token = alphaconf.configuration.set(OmegaConf.create())
try:
alphaconf.set_application(application)
assert alphaconf.application.get() is application
assert alphaconf.configuration.get() == application.configuration
finally:
alphaconf.application.reset(token)
alphaconf.configuration.reset(token)


def test_setup_configuration():
Expand Down

0 comments on commit 7def0c3

Please sign in to comment.