Skip to content

Commit d01dc42

Browse files
aliniknejadjhamrick
authored andcommitted
Further Python 3 type annotations
1 parent 15f610f commit d01dc42

37 files changed

+293
-161
lines changed

nbgrader/apps/autogradeapp.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
from .baseapp import NbGrader, nbgrader_aliases, nbgrader_flags
88
from ..converters import BaseConverter, Autograde, NbGraderException
9+
from traitlets.traitlets import MetaHasTraits
10+
from traitlets.config.loader import Config
11+
from typing import List
912

1013
aliases = {
1114
'course': 'CourseDirectory.course_id'
@@ -95,12 +98,12 @@ class AutogradeApp(NbGrader):
9598
"""
9699

97100
@default("classes")
98-
def _classes_default(self):
101+
def _classes_default(self) -> List[MetaHasTraits]:
99102
classes = super(AutogradeApp, self)._classes_default()
100103
classes.extend([BaseConverter, Autograde])
101104
return classes
102105

103-
def _load_config(self, cfg, **kwargs):
106+
def _load_config(self, cfg: Config, **kwargs: dict) -> None:
104107
if 'AutogradeApp' in cfg:
105108
self.log.warning(
106109
"Use Autograde in config, not AutogradeApp. Outdated config:\n%s",
@@ -114,8 +117,8 @@ def _load_config(self, cfg, **kwargs):
114117

115118
super(AutogradeApp, self)._load_config(cfg, **kwargs)
116119

117-
def start(self):
118-
super(AutogradeApp, self).start()
120+
def start(self) -> None:
121+
super().start()
119122

120123
if len(self.extra_args) > 1:
121124
self.fail("Only one argument (the assignment id) may be specified")

nbgrader/apps/baseapp.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
from .. import plugins
2323
from .. import exchange
2424
from .. import converters
25+
from traitlets.traitlets import MetaHasTraits
26+
from typing import List as TypingList
27+
from io import StringIO
28+
from typing import Any
2529

2630

2731
nbgrader_aliases = {
@@ -62,15 +66,15 @@ class NbGrader(JupyterApp):
6266
_log_formatter_cls = LogFormatter
6367

6468
@default("log_level")
65-
def _log_level_default(self):
69+
def _log_level_default(self) -> int:
6670
return logging.INFO
6771

6872
@default("log_datefmt")
69-
def _log_datefmt_default(self):
73+
def _log_datefmt_default(self) -> str:
7074
return "%Y-%m-%d %H:%M:%S"
7175

7276
@default("log_format")
73-
def _log_format_default(self):
77+
def _log_format_default(self) -> str:
7478
return "%(color)s[%(name)s | %(levelname)s]%(end_color)s %(message)s"
7579

7680
logfile = Unicode(
@@ -83,7 +87,11 @@ def _log_format_default(self):
8387
)
8488
).tag(config=True)
8589

86-
def init_logging(self, handler_class, handler_args, color=True, subapps=False):
90+
def init_logging(self,
91+
handler_class: type,
92+
handler_args: TypingList[StringIO],
93+
color: bool = True,
94+
subapps: bool = False) -> None:
8795
handler = handler_class(*handler_args)
8896

8997
if color:
@@ -101,7 +109,7 @@ def init_logging(self, handler_class, handler_args, color=True, subapps=False):
101109
if subapps and self.subapp:
102110
self.subapp.init_logging(handler_class, handler_args, color=color, subapps=subapps)
103111

104-
def deinit_logging(self):
112+
def deinit_logging(self) -> None:
105113
if len(self.log.handlers) > 1:
106114
for handler in self.log.handlers[1:]:
107115
handler.close()
@@ -115,10 +123,10 @@ def deinit_logging(self):
115123
classes = List()
116124

117125
@default("classes")
118-
def _classes_default(self):
126+
def _classes_default(self) -> TypingList[MetaHasTraits]:
119127
return [NbGrader, CourseDirectory]
120128

121-
def all_configurable_classes(self):
129+
def all_configurable_classes(self) -> TypingList[MetaHasTraits]:
122130
"""Get a list of all configurable classes for nbgrader
123131
"""
124132
# Call explicitly the method on this class, to avoid infinite recursion
@@ -163,10 +171,10 @@ def all_configurable_classes(self):
163171
return classes
164172

165173
@default("config_file_name")
166-
def _config_file_name_default(self):
174+
def _config_file_name_default(self) -> str:
167175
return u'nbgrader_config'
168176

169-
def _load_config(self, cfg, **kwargs):
177+
def _load_config(self, cfg: Config, **kwargs: Any) -> None:
170178
if 'NbGraderConfig' in cfg:
171179
self.log.warning(
172180
"Use NbGrader in config, not NbGraderConfig. Outdated config:\n%s",
@@ -286,14 +294,14 @@ def fail(self, msg, *args):
286294
self.log.error(msg, *args)
287295
sys.exit(1)
288296

289-
def build_extra_config(self):
297+
def build_extra_config(self) -> Config:
290298
return Config()
291299

292300
def excepthook(self, etype, evalue, tb):
293301
format_excepthook(etype, evalue, tb)
294302

295303
@catch_config_error
296-
def initialize(self, argv=None):
304+
def initialize(self, argv: TypingList[str] = None) -> None:
297305
self.update_config(self.build_extra_config())
298306
self.init_syspath()
299307
self.coursedir = CourseDirectory(parent=self)
@@ -305,11 +313,11 @@ def initialize(self, argv=None):
305313
if self.logfile:
306314
self.init_logging(logging.FileHandler, [self.logfile], color=False)
307315

308-
def init_syspath(self):
316+
def init_syspath(self) -> None:
309317
"""Add the cwd to the sys.path ($PYTHONPATH)"""
310318
sys.path.insert(0, os.getcwd())
311319

312-
def reset(self):
320+
def reset(self) -> None:
313321
# stop logging
314322
self.deinit_logging()
315323

@@ -325,7 +333,7 @@ def print_subcommands(self):
325333
for key, (app, desc) in self.subcommands.items():
326334
print(" {}\n{}\n".format(key, desc))
327335

328-
def load_config_file(self, **kwargs):
336+
def load_config_file(self, **kwargs: Any) -> None:
329337
"""Load the config file.
330338
By default, errors in loading config are handled, and a warning
331339
printed on screen. For testing, the suppress_errors option is set
@@ -341,6 +349,6 @@ def load_config_file(self, **kwargs):
341349

342350
super(NbGrader, self).load_config_file(**kwargs)
343351

344-
def start(self):
352+
def start(self) -> None:
345353
super(NbGrader, self).start()
346354
self.authenticator = Authenticator(parent=self)

nbgrader/apps/generateassignmentapp.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
from .baseapp import NbGrader, nbgrader_aliases, nbgrader_flags
88
from ..converters import BaseConverter, GenerateAssignment, NbGraderException
9+
from traitlets.traitlets import MetaHasTraits
10+
from typing import List, Any
11+
from traitlets.config.loader import Config
912

1013
aliases = {
1114
'course': 'CourseDirectory.course_id'
@@ -107,12 +110,12 @@ class GenerateAssignmentApp(NbGrader):
107110
"""
108111

109112
@default("classes")
110-
def _classes_default(self):
113+
def _classes_default(self) -> List[MetaHasTraits]:
111114
classes = super(GenerateAssignmentApp, self)._classes_default()
112115
classes.extend([BaseConverter, GenerateAssignment])
113116
return classes
114117

115-
def _load_config(self, cfg, **kwargs):
118+
def _load_config(self, cfg: Config, **kwargs: Any) -> None:
116119
if 'AssignApp' in cfg:
117120
self.log.warning(
118121
"Use GenerateAssignment in config, not AssignApp. Outdated config:\n%s",
@@ -124,10 +127,10 @@ def _load_config(self, cfg, **kwargs):
124127
cfg.GenerateAssignment.merge(cfg.AssignApp)
125128
del cfg.AssignApp
126129

127-
super(GenerateAssignmentApp, self)._load_config(cfg, **kwargs)
130+
super()._load_config(cfg, **kwargs)
128131

129-
def start(self):
130-
super(GenerateAssignmentApp, self).start()
132+
def start(self) -> None:
133+
super().start()
131134

132135
if len(self.extra_args) > 1:
133136
self.fail("Only one argument (the assignment id) may be specified")

nbgrader/apps/nbgraderapp.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838
ZipCollectApp,
3939
GenerateConfigApp
4040
)
41+
from traitlets.traitlets import MetaHasTraits
42+
from typing import List
4143

4244
aliases = {}
4345
aliases.update(nbgrader_aliases)
@@ -294,14 +296,14 @@ class NbGraderApp(NbGrader):
294296
)
295297

296298
@default("classes")
297-
def _classes_default(self):
299+
def _classes_default(self) -> List[MetaHasTraits]:
298300
return self.all_configurable_classes()
299301

300302
@catch_config_error
301-
def initialize(self, argv=None):
303+
def initialize(self, argv: List[str] = None) -> None:
302304
super(NbGraderApp, self).initialize(argv)
303305

304-
def start(self):
306+
def start(self) -> None:
305307
# check: is there a subapp given?
306308
if self.subapp is None:
307309
print("No command given (run with --help for options). List of subcommands:\n")

nbgrader/auth/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from traitlets import Instance, Type
22
from traitlets.config import LoggingConfigurable
3+
from typing import Any
34

45

56
class BaseAuthPlugin(LoggingConfigurable):
@@ -67,7 +68,6 @@ def remove_student_from_course(self, student_id, course_id):
6768
pass
6869

6970

70-
7171
class Authenticator(LoggingConfigurable):
7272

7373
plugin_class = Type(
@@ -78,8 +78,8 @@ class Authenticator(LoggingConfigurable):
7878

7979
plugin = Instance(BaseAuthPlugin).tag(config=False)
8080

81-
def __init__(self, *args, **kwargs):
82-
super(Authenticator, self).__init__(*args, **kwargs)
81+
def __init__(self, *args: Any, **kwargs: Any) -> None:
82+
super().__init__(*args, **kwargs)
8383
self.log.debug("Using authenticator: %s", self.plugin_class.__name__)
8484
self.plugin = self.plugin_class(parent=self)
8585

@@ -121,7 +121,7 @@ def has_access(self, student_id, course_id):
121121
return True
122122
return course_id in courses
123123

124-
def add_student_to_course(self, student_id, course_id):
124+
def add_student_to_course(self, student_id: str, course_id: str) -> Any:
125125
"""Grants a student access to a given course.
126126
127127
Arguments

nbgrader/auth/jupyterhub.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import requests
33

44
from .base import BaseAuthPlugin
5+
from typing import Optional
56

67

78
class JupyterhubEnvironmentError(Exception):
@@ -12,14 +13,14 @@ class JupyterhubApiError(Exception):
1213
pass
1314

1415

15-
def get_jupyterhub_user():
16+
def get_jupyterhub_user() -> str:
1617
if os.getenv('JUPYTERHUB_USER'):
1718
return os.environ['JUPYTERHUB_USER']
1819
else:
1920
raise JupyterhubEnvironmentError("JUPYTERHUB_USER env is required to run the exchange features of nbgrader.")
2021

2122

22-
def get_jupyterhub_api_url():
23+
def get_jupyterhub_api_url() -> str:
2324
return os.environ.get('JUPYTERHUB_API_URL') or 'http://127.0.0.1:8081/hub/api'
2425

2526

@@ -33,23 +34,23 @@ def get_jupyterhub_authorization():
3334
}
3435

3536

36-
def _query_jupyterhub_api(method, api_path, post_data=None):
37+
def _query_jupyterhub_api(method: str, api_path: str, post_data: Optional[dict] = None) -> dict:
3738
"""Query Jupyterhub api
3839
3940
Detects Jupyterhub environment variables and makes a call to the Hub API
4041
4142
Parameters
4243
----------
43-
method : string
44+
method:
4445
HTTP method, e.g. GET or POST
45-
api_path : string
46+
api_path:
4647
relative path, for example /users/
47-
post_data : dict
48+
post_data:
4849
JSON arguments for the API call
4950
5051
Returns
5152
-------
52-
response : dict
53+
response:
5354
JSON response converted to dictionary
5455
5556
"""
@@ -92,7 +93,7 @@ def get_student_courses(self, student_id):
9293
courses.add(course)
9394
return list(courses)
9495

95-
def add_student_to_course(self, student_id, course_id):
96+
def add_student_to_course(self, student_id: str, course_id: str) -> None:
9697
if not course_id:
9798
self.log.error(
9899
"Could not add student to course because the course_id has not "

nbgrader/converters/autograde.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,14 @@ class Autograde(BaseConverter):
4040
_sanitizing = True
4141

4242
@property
43-
def _input_directory(self):
43+
def _input_directory(self) -> str:
4444
if self._sanitizing:
4545
return self.coursedir.submitted_directory
4646
else:
4747
return self.coursedir.autograded_directory
4848

4949
@property
50-
def _output_directory(self):
50+
def _output_directory(self) -> str:
5151
return self.coursedir.autograded_directory
5252

5353
sanitize_preprocessors = List([
@@ -67,7 +67,7 @@ def _output_directory(self):
6767

6868
preprocessors = List([])
6969

70-
def init_assignment(self, assignment_id, student_id):
70+
def init_assignment(self, assignment_id: str, student_id: str) -> None:
7171
super(Autograde, self).init_assignment(assignment_id, student_id)
7272
# try to get the student from the database, and throw an error if it
7373
# doesn't exist
@@ -167,7 +167,7 @@ def init_assignment(self, assignment_id, student_id):
167167
grade.needs_manual_grade = False
168168
gb.db.commit()
169169

170-
def _init_preprocessors(self):
170+
def _init_preprocessors(self) -> None:
171171
self.exporter._preprocessors = []
172172
if self._sanitizing:
173173
preprocessors = self.sanitize_preprocessors
@@ -177,7 +177,7 @@ def _init_preprocessors(self):
177177
for pp in preprocessors:
178178
self.exporter.register_preprocessor(pp)
179179

180-
def convert_single_notebook(self, notebook_filename):
180+
def convert_single_notebook(self, notebook_filename: str) -> None:
181181
self.log.info("Sanitizing %s", notebook_filename)
182182
self._sanitizing = True
183183
self._init_preprocessors()

0 commit comments

Comments
 (0)