Skip to content

Commit a8fa22a

Browse files
committed
Fixup docstrings & comments
- Typo fixes - Better (but not perfect!) PEP 257 & PEP 8 compliance
1 parent be208c1 commit a8fa22a

File tree

10 files changed

+209
-131
lines changed

10 files changed

+209
-131
lines changed

naucse/cli.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55

66

77
def cli(app, *, base_url=None, freezer=None):
8-
""" Extends the elsa command line interface with a new command which prints all courses and runs
9-
which are present with basic info about them.
8+
"""Return the elsa CLI extended with naucse-specific commands.
109
"""
1110
elsa_group = elsa.cli(app, base_url=base_url, freezer=freezer, invoke_cli=False)
1211

@@ -18,14 +17,16 @@ def naucse():
1817
@click.option("--forks-only", default=False, is_flag=True,
1918
help="Only list courses and runs from forks")
2019
def list_courses(forks_only):
21-
""" List all courses and runs and info about them.
20+
"""List all courses and runs and info about them.
2221
23-
Mainly useful for courses from forks, shows where do they sourced from and if
24-
they return even the most basic information and will therefore be included in
22+
Mainly useful for courses from forks.
23+
Shows where they are sourced from and if they return even the
24+
most basic information and will therefore be included in
2525
list of courses/runs.
2626
27-
A practical benefit is that on Travis CI the docker images are pulled/built
28-
in this command and the freezing won't timeout after the 10 minute limit if things are taking particularly long.
27+
A practical benefit is that on Travis CI, the docker images are
28+
pulled/built by this command, so freezing won't timeout after
29+
the 10 minute limit if things are taking particularly long.
2930
"""
3031
from naucse.views import model
3132

naucse/freezer.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,30 @@
66

77

88
class AllLinksLogger(UrlForLogger):
9-
""" AllLinksLogger primarily logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well.
9+
"""Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well.
1010
"""
1111

1212
def iter_calls(self):
13-
""" Yields all logged urls and links parsed from content.
14-
Unfortunately, ``yield from`` cannot be used as the queues are modified on the go.
13+
"""Yield all logged urls and links parsed from content.
1514
"""
15+
# Unfortunately, ``yield from`` cannot be used as the queues are
16+
# modified on the go.
1617
while self.logged_calls or absolute_urls_to_freeze:
1718
if self.logged_calls:
1819
yield self.logged_calls.popleft()
19-
# prefer urls from :atrr:`logged_calls` - so, ideally, cache is populated from the base repository
20+
# prefer urls from :atrr:`logged_calls` - so, ideally,
21+
# cache is populated from the base repository
2022
continue
2123
if absolute_urls_to_freeze:
2224
yield absolute_urls_to_freeze.popleft()
2325

2426

2527
@contextlib.contextmanager
2628
def temporary_url_for_logger(app):
27-
""" A context manager which temporary adds a new UrlForLogger to the app and yields it, so it can be used
28-
to get logged calls.
29+
"""Context manager which temporary adds a new UrlForLogger to the app.
30+
31+
The logger is yielded as the context object, so it can be used
32+
to get logged calls.
2933
"""
3034
logger = UrlForLogger(app)
3135

@@ -40,4 +44,6 @@ class NaucseFreezer(Freezer):
4044

4145
def __init__(self, app):
4246
super().__init__(app)
43-
self.url_for_logger = AllLinksLogger(app) # override the default url_for_logger with our modified version
47+
48+
# override the default url_for_logger with our modified version
49+
self.url_for_logger = AllLinksLogger(app)

naucse/models.py

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,10 @@ def latex(self):
8383

8484
@reify
8585
def css(self):
86-
""" Returns lesson-specific extra CSS.
86+
"""Return lesson-specific extra CSS.
8787
88-
If the lesson defines extra css, the scope of the styles is limited to ``.lesson-content``,
89-
a div which contains the actual lesson content.
88+
If the lesson defines extra CSS, the scope of the styles is limited
89+
to ``.lesson-content``, which contains the actual lesson content.
9090
"""
9191
css = self.info.get("css")
9292

@@ -200,7 +200,7 @@ def convert_url(url):
200200

201201
@staticmethod
202202
def limit_css_to_lesson_content(css):
203-
""" Returns ``css`` limited just to the ``.lesson-content`` element.
203+
"""Return ``css`` limited just to the ``.lesson-content`` element.
204204
205205
This doesn't protect against malicious input.
206206
"""
@@ -468,7 +468,7 @@ def _get_sessions(course, plan):
468468

469469

470470
class CourseMixin:
471-
""" Couple of methods common for both :class:`Course` and :class:`CourseLink`.
471+
"""Methods common for both :class:`Course` and :class:`CourseLink`.
472472
"""
473473

474474
@reify
@@ -506,10 +506,13 @@ def __str__(self):
506506

507507
data_filename = "info.yml" # for MultipleModelDirProperty
508508

509-
# These two class attributes define what the function ``naucse.utils.forks:course_info`` returns from forks,
510-
# meaning, the function in the fork looks at these lists that are in the fork and returns those.
511-
# If you're adding an attribute to these lists, you have to make sure that you provide a default in
512-
# the CourseLink attribute since the forks already forked will not be returning the value.
509+
# These two class attributes define what the function
510+
# ``naucse.utils.forks:course_info`` returns from forks,
511+
# meaning, the function in the fork looks at these lists
512+
# that are in the fork and returns those.
513+
# If you're adding an attribute to these lists, you have to
514+
# make sure that you provide a default in the CourseLink
515+
# attribute since existing forks don't contain the value.
513516
COURSE_INFO = ["title", "description", "vars", "canonical"]
514517
RUN_INFO = ["title", "description", "start_date", "end_date", "canonical", "subtitle", "derives", "vars",
515518
"default_start_time", "default_end_time"]
@@ -583,7 +586,7 @@ def optional_convert_time(timestr):
583586

584587

585588
class CourseLink(CourseMixin, Model):
586-
""" A link to a course from a separate git repo.
589+
"""A link to a course from a separate git repo.
587590
"""
588591

589592
link = YamlProperty()
@@ -619,7 +622,9 @@ def base_course(self):
619622
return None
620623

621624
def render(self, page_type, *args, **kwargs):
622-
""" Renders a page in the fork, checks the content and registers urls to freeze.
625+
"""Render a page in the fork.
626+
627+
Check the content and registers URLs to freeze.
623628
"""
624629
naucse.utils.views.forks_raise_if_disabled()
625630

@@ -635,7 +640,8 @@ def render(self, page_type, *args, **kwargs):
635640
allowed_elements_parser.reset_and_feed(result.output["content"])
636641

637642
if "urls" in result.output:
638-
# freeze urls generated by the code in fork, but only if they start with the slug of the course
643+
# Freeze URLs generated by the code in fork, but only if
644+
# they start with the slug of the course
639645
absolute_urls_to_freeze.extend([url for url in result.output["urls"] if url.startswith(f"/{self.slug}/")])
640646

641647
return result.output
@@ -662,12 +668,14 @@ def lesson_static(self, lesson_slug, path):
662668
return filename.parent, filename.name
663669

664670
def get_footer_links(self, lesson_slug, page, **kwargs):
665-
""" Returns links to previous page, to current session and to the next page. Each link
666-
is either a dict with url and title keys or ``None``.
671+
"""Return links to previous page, current session and the next page.
672+
673+
Each link is either a dict with 'url' and 'title' keys or ``None``.
667674
668-
If :meth:`render_page` fails and a canonical versions is in the base repo, it's used instead
669-
with a warning. This method provides the correct footer links for the page, since ``sessions``
670-
is not included in the info provided by forks.
675+
If :meth:`render_page` fails and a canonical version is in the
676+
base repo, it's used instead with a warning.
677+
This method provides the correct footer links for the page,
678+
since ``sessions`` is not included in the info provided by forks.
671679
"""
672680
naucse.utils.views.forks_raise_if_disabled()
673681

@@ -728,7 +736,8 @@ def __str__(self):
728736

729737

730738
class MetaInfo:
731-
""" Info about the current repository. """
739+
"""Info about the current repository.
740+
"""
732741

733742
def __str__(self):
734743
return "Meta Information"
@@ -738,8 +747,10 @@ def __str__(self):
738747

739748
@reify
740749
def slug(self):
741-
""" Returns the slug of the repository based on the current branch. Returns the default if not on a branch,
742-
the branch doesn't have a remote or the remote url can't be parsed.
750+
"""Return the slug of the repository based on the current branch.
751+
752+
Returns the default if not on a branch, the branch doesn't
753+
have a remote, or the remote url can't be parsed.
743754
"""
744755
from naucse.views import logger
745756

@@ -780,7 +791,7 @@ def slug(self):
780791

781792
@reify
782793
def branch(self):
783-
""" Returns the active branch name or master if not on a branch.
794+
"""Return the active branch name, or 'master' if not on a branch.
784795
"""
785796
from naucse.views import logger
786797

@@ -831,9 +842,10 @@ def meta(self):
831842

832843
@reify
833844
def safe_run_years(self):
834-
# since even the basic info about the forked runs can be broken, we need to make sure the required info
835-
# is provided. If ``RAISE_FORK_ERRORS`` is set, exceptions are raised here, otherwise the run is
836-
# ignored completely.
845+
# since even the basic info about the forked runs can be broken,
846+
# we need to make sure the required info is provided.
847+
# If ``RAISE_FORK_ERRORS`` is set, exceptions are raised here.
848+
# Otherwise the run is ignored completely.
837849
safe_years = {}
838850
for year, run_years in self.run_years.items():
839851
safe_run_years = []

naucse/urlconverters.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def to_url(self, value):
4242
value = "course/"+value
4343
value = self.to_python(value)
4444

45-
if isinstance(value, dict): # since the converter can be called with a dict mimicking a course
45+
# the converter can be called with a dict mimicking a course
46+
if isinstance(value, dict):
4647
return value["slug"]
4748

4849
return value.slug
@@ -56,7 +57,8 @@ def to_url(self, value):
5657
if isinstance(value, Lesson):
5758
return value.slug
5859

59-
elif isinstance(value, dict): # since the converter can be called with a dict mimicking a lesson
60+
# the converter can be called with a dict mimicking a lesson
61+
elif isinstance(value, dict):
6062
return value["slug"]
6163

6264
return value
@@ -72,7 +74,8 @@ def to_python(self, value):
7274
abort(404)
7375

7476
def to_url(self, value):
75-
if isinstance(value, dict): # since the converter can be called with a dict mimicking a lesson
77+
# the converter can be called with a dict mimicking a lesson
78+
if isinstance(value, dict):
7679
return value["slug"]
7780

7881
if isinstance(value, str):

naucse/utils/forks.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ def get_course_from_slug(slug: str) -> Course:
2222

2323

2424
def course_info(slug: str, *args, **kwargs) -> Dict[str, Any]:
25-
""" Returns info about the course/run. Returns some extra info when it's a run (based on COURSE_INFO/RUN_INFO)
25+
"""Return info about the given course.
26+
27+
Return some extra info when it's a run (based on COURSE_INFO/RUN_INFO)
2628
"""
2729
course = get_course_from_slug(slug)
2830

@@ -48,7 +50,7 @@ def course_info(slug: str, *args, **kwargs) -> Dict[str, Any]:
4850

4951

5052
def serialize_license(license) -> Optional[Dict[str, str]]:
51-
""" Serializes a License instance into a dict
53+
"""Serialize a License instance into a dict.
5254
"""
5355
if license:
5456
return {
@@ -60,7 +62,7 @@ def serialize_license(license) -> Optional[Dict[str, str]]:
6062

6163

6264
def render(page_type: str, slug: str, *args, **kwargs) -> Dict[str, Any]:
63-
""" Returns a rendered page for a course, based on page_type and slug.
65+
"""Return a rendered page for a course, based on page_type and slug.
6466
"""
6567
course = get_course_from_slug(slug)
6668

naucse/utils/links.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" These functions serve as validation and further processing of metadata from forks.
1+
"""Functions for validation and further processing of metadata from forks.
22
"""
33
from xml.dom import SyntaxErr
44

naucse/utils/models.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,13 @@ def compute(self, instance):
9090

9191

9292
class ForkProperty(LazyProperty):
93-
""" Populated from the fork the model is pointing to.
93+
"""Populated from the fork the model is pointing to.
9494
95-
``repo`` and ``branch`` indicate from which attribute of the instance the property should take info about the fork.
96-
``**kwargs`` are for `arca.Task` - the values can be callable (they get the instance as a parameter)
95+
``repo`` and ``branch`` indicate from which attribute of the instance
96+
the property should take info about the fork.
97+
98+
``**kwargs`` are for `arca.Task`. The values can be callable, in which
99+
case they are called with the instance as a parameter.
97100
"""
98101
def __init__(self, repo, branch, **kwargs):
99102
self.repo_prop = repo
@@ -158,8 +161,12 @@ def __get__(self, instance, cls):
158161
class DirProperty(LazyProperty):
159162
"""Ordered dict of models from a subdirectory
160163
161-
If ``info.yml`` is present in the subdirectory, use it for the order
162-
of the models. The rest is appended alphabetically.
164+
If ``info.yml`` is present in the subdirectory, it must contain a dict
165+
with an "order" key, which is used to order the models.
166+
The rest is appended in alphabetical order.
167+
168+
If ``keyfunc`` is given, it is used to create keys from directory names.
169+
The default is ``str``, i.e. the directory name is used as dict key.
163170
"""
164171
def __init__(self, cls, *subdir, keyfunc=str):
165172
self.cls = cls
@@ -190,16 +197,19 @@ def compute(self, instance):
190197

191198

192199
class MultipleModelDirProperty(DirProperty):
193-
""" Ordered dict of models from a subdirectory.
200+
"""Ordered dict of models from a subdirectory.
194201
195202
For directories that have different models inside of them.
196-
The models which are supposed to be used are defined by files they load their content out of
197-
and the definition prioritizes them - first come first serve. If none of the models is present in the folders
198-
a exception is raised.
199-
Each of the models has to have an attribute ``data_filename`` with the filename used for defining them.
200203
201-
The prioritization is important in forks - if the base repo is merged to forks and the definitions
202-
would exclusive, info.yml and link.yml would be in conflict and further actions would be needed.
204+
The models which are supposed to be used are defined by files they
205+
load their content out of and the definition prioritizes them - first
206+
come first serve.
207+
If none of the models is present in the folders, an exception is raised.
208+
Each of the models must have an attribute ``data_filename`` with
209+
the filename used for defining them.
210+
211+
The prioritization is important in forks, since many directories
212+
contain both info.yml and link.yml.
203213
204214
Possible to order by ``info.yml`` just like DirProperty.
205215
"""

0 commit comments

Comments
 (0)