Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle More Types #1

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/myapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def start(self):
print("app.config:")
print(self.config)
print("try running with --help-all to see all available flags")
assert self.log is not None
self.log.info("Info Mesage")
self.log.debug("DebugMessage")
self.log.critical("Warning")
Expand Down
23 changes: 14 additions & 9 deletions traitlets/config/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
PyFileConfigLoader,
)
from traitlets.traitlets import (
Any,
Bool,
Dict,
Enum,
Expand Down Expand Up @@ -94,8 +95,10 @@

IS_PYTHONW = sys.executable and sys.executable.endswith("pythonw.exe")

T = t.TypeVar("T", bound=t.Callable[..., t.Any])

def catch_config_error(method):

def catch_config_error(method: T) -> T:
"""Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

On a TraitError (generally caused by bad config), this will print the trait's
Expand All @@ -113,7 +116,7 @@ def inner(app, *args, **kwargs):
app.log.debug("Config at the time: %s", app.config)
app.exit(1)

return inner
return t.cast(T, inner)


class ApplicationError(Exception):
Expand Down Expand Up @@ -148,6 +151,8 @@ class Application(SingletonConfigurable):
# line application
name: t.Union[str, Unicode] = Unicode("application")

log = Any(help="Logger or LoggerAdapter instance", allow_none=False)

# The description of the application that is printed at the beginning
# of the help.
description: t.Union[str, Unicode] = Unicode("This is an application.")
Expand Down Expand Up @@ -198,19 +203,19 @@ def _classes_inc_parents(self, classes=None):
)

# The log level for the application
log_level: t.Union[str, int, Enum] = Enum(
log_level: t.Union[str, int, Enum] = Enum( # type:ignore[assignment]
(0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"),
default_value=logging.WARN,
help="Set the log level by value or name.",
).tag(config=True)

_log_formatter_cls = LevelFormatter

log_datefmt: t.Union[str, Unicode] = Unicode(
log_datefmt: t.Union[str, Unicode] = Unicode( # type:ignore[assignment]
"%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s"
).tag(config=True)

log_format: t.Union[str, Unicode] = Unicode(
log_format: t.Union[str, Unicode] = Unicode( # type:ignore[assignment]
"[%(name)s]%(highlevel)s %(message)s",
help="The Logging format template",
).tag(config=True)
Expand All @@ -234,7 +239,7 @@ def get_default_logging_config(self):
"console": {
"class": "logging.StreamHandler",
"formatter": "console",
"level": logging.getLevelName(self.log_level),
"level": logging.getLevelName(self.log_level), # type:ignore[arg-type]
"stream": "ext://sys.stderr",
},
},
Expand Down Expand Up @@ -393,7 +398,7 @@ def _log_default(self):
# and the second being the help string for the subcommand
subcommands: t.Union[t.Dict[str, t.Tuple[str, str]], Dict] = Dict()
# parse_command_line will initialize a subapp, if requested
subapp = Instance("traitlets.config.application.Application", allow_none=True)
subapp: Instance[t.Any] = Instance("traitlets.config.application.Application", allow_none=True)

# extra command-line arguments that don't set config values
extra_args: t.Union[t.List[str], List] = List(Unicode())
Expand All @@ -411,11 +416,11 @@ def _log_default(self):

_loaded_config_files = List()

show_config: t.Union[bool, Bool] = Bool(
show_config: t.Union[bool, Bool] = Bool( # type:ignore[assignment]
help="Instead of starting the Application, dump configuration to stdout"
).tag(config=True)

show_config_json: t.Union[bool, Bool] = Bool(
show_config_json: t.Union[bool, Bool] = Bool( # type:ignore[assignment]
help="Instead of starting the Application, dump configuration to stdout (as JSON)"
).tag(config=True)

Expand Down
9 changes: 7 additions & 2 deletions traitlets/config/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@


import logging
import typing as t
import warnings
from copy import deepcopy
from textwrap import dedent
Expand Down Expand Up @@ -44,8 +45,10 @@ class MultipleInstanceError(ConfigurableError):

class Configurable(HasTraits):

config = Instance(Config, (), {})
parent = Instance("traitlets.config.configurable.Configurable", allow_none=True)
config: Instance[Config] = Instance(Config, (), {})
parent: Instance[t.Any] = Instance(
"traitlets.config.configurable.Configurable", allow_none=True
)

def __init__(self, **kwargs):
"""Create a configurable given a config config.
Expand Down Expand Up @@ -183,6 +186,7 @@ def _load_config(self, cfg, section_names=None, traits=None):
from difflib import get_close_matches

if isinstance(self, LoggingConfigurable):
assert self.log is not None
warn = self.log.warning
else:
warn = lambda msg: warnings.warn(msg, stacklevel=9) # noqa[E371]
Expand Down Expand Up @@ -460,6 +464,7 @@ def _validate_log(self, proposal):
@default("log")
def _log_default(self):
if isinstance(self.parent, LoggingConfigurable):
assert self.parent is not None
return self.parent.log
from traitlets import log

Expand Down
6 changes: 3 additions & 3 deletions traitlets/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ class LazyConfigValue(HasTraits):
_value = None

# list methods
_extend = List()
_prepend = List()
_inserts = List()
_extend: List = List()
_prepend: List = List()
_inserts: List = List()

def append(self, obj):
"""Append an item to a List"""
Expand Down
3 changes: 1 addition & 2 deletions traitlets/tests/test_typing.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from lib2to3 import pytree

import pytest
from typing_extensions import reveal_type

from traitlets import Bool, HasTraits, TCPAddress
from traitlets.config import Application


@pytest.mark.mypy_testing
Expand Down
Loading