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

Find incorrect context managers #76

Open
nedbat opened this issue Nov 21, 2018 · 0 comments
Open

Find incorrect context managers #76

nedbat opened this issue Nov 21, 2018 · 0 comments

Comments

@nedbat
Copy link
Contributor

nedbat commented Nov 21, 2018

At Python Study Group this week, we looked at context managers. When we got to @contextlib.contextmanager, we learned that this is wrong:

@contextmanager
def my_context_manager():
    #... set up
    yield
    #... clean up

because the clean up won't execute if an exception happens inside the caller's with-statement.

I grepped edx-platform to see if this happens, and it does! here and here for example.

We also have instances of pointless context managers with no clean up at all (here):

@contextmanager
def lti_consumer_fields_editing_flag(course_id, enabled_for_course=False):
    """
    Yields CourseEditLTIFieldsEnabledFlag record for unit tests

    Arguments:
        course_id (CourseLocator): course locator to control this feature for.
        enabled_for_course (bool): whether feature is enabled for 'course_id'
    """
    RequestCache.clear_all_namespaces()
    CourseEditLTIFieldsEnabledFlag.objects.create(course_id=course_id, enabled=enabled_for_course)
    yield

It would be cool to lint for these mistakes.

BTW: A reason to have a cleanup-less context manager is in a method overriding a correct context manager, but the subclass needs no clean up. If we write this linter, that case can use a disabling pragma.

/cc @cpennington @jmbowman @bessiesteinberg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant