Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
EvaluationWorker.run_attack_work | (self, work_id) | Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
| Runs one attack work. | def run_attack_work(self, work_id):
"""Runs one attack work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
""... | [
"def",
"run_attack_work",
"(",
"self",
",",
"work_id",
")",
":",
"adv_batch_id",
"=",
"self",
".",
"attack_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"\"output_adversarial_batch_id\"",
"]",
"adv_batch",
"=",
"self",
".",
"adv_batches",
"[",
"adv_batch_id",
... | [
663,
4
] | [
768,
46
] | python | en | ['en', 'de', 'en'] | True |
EvaluationWorker.run_attacks | (self) | Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
| Method which evaluates all attack work. | def run_attacks(self):
"""Method which evaluates all attack work.
In a loop this method queries not completed attack work, picks one
attack work and runs it.
"""
logging.info("******** Start evaluation of attacks ********")
prev_submission_id = None
while True:
... | [
"def",
"run_attacks",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"******** Start evaluation of attacks ********\"",
")",
"prev_submission_id",
"=",
"None",
"while",
"True",
":",
"# wait until work is available",
"self",
".",
"attack_work",
".",
"read_all_from... | [
770,
4
] | [
820,
72
] | python | en | ['en', 'en', 'en'] | True |
EvaluationWorker.fetch_defense_data | (self) | Lazy initialization of data necessary to execute defenses. | Lazy initialization of data necessary to execute defenses. | def fetch_defense_data(self):
"""Lazy initialization of data necessary to execute defenses."""
if self.defenses_data_initialized:
return
logging.info("Fetching defense data from datastore")
# init data from datastore
self.submissions.init_from_datastore()
self... | [
"def",
"fetch_defense_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"defenses_data_initialized",
":",
"return",
"logging",
".",
"info",
"(",
"\"Fetching defense data from datastore\"",
")",
"# init data from datastore",
"self",
".",
"submissions",
".",
"init_from_dat... | [
822,
4
] | [
834,
45
] | python | en | ['en', 'en', 'en'] | True |
EvaluationWorker.run_defense_work | (self, work_id) | Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
| Runs one defense work. | def run_defense_work(self, work_id):
"""Runs one defense work.
Args:
work_id: ID of the piece of work to run
Returns:
elapsed_time_sec, submission_id - elapsed time and id of the submission
Raises:
WorkerError: if error occurred during execution.
... | [
"def",
"run_defense_work",
"(",
"self",
",",
"work_id",
")",
":",
"class_batch_id",
"=",
"self",
".",
"defense_work",
".",
"work",
"[",
"work_id",
"]",
"[",
"\"output_classification_batch_id\"",
"]",
"class_batch",
"=",
"self",
".",
"class_batches",
".",
"read_b... | [
836,
4
] | [
936,
60
] | python | en | ['en', 'de', 'en'] | True |
EvaluationWorker.run_defenses | (self) | Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
| Method which evaluates all defense work. | def run_defenses(self):
"""Method which evaluates all defense work.
In a loop this method queries not completed defense work,
picks one defense work and runs it.
"""
logging.info("******** Start evaluation of defenses ********")
prev_submission_id = None
need_rel... | [
"def",
"run_defenses",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"******** Start evaluation of defenses ********\"",
")",
"prev_submission_id",
"=",
"None",
"need_reload_work",
"=",
"True",
"while",
"True",
":",
"# wait until work is available",
"if",
"need_... | [
938,
4
] | [
1019,
73
] | python | en | ['en', 'en', 'en'] | True |
EvaluationWorker.run_work | (self) | Run attacks and defenses | Run attacks and defenses | def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | [
"def",
"run_work",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
"self",
".",
"run_attacks",
"(",
")",
"self",
".",
"run_defenses",
"(",
")"
] | [
1021,
4
] | [
1026,
27
] | python | en | ['en', 'fil', 'en'] | True |
EarliestOrLatestTests.tearDown | (self) | Makes sure Article has a get_latest_by | Makes sure Article has a get_latest_by | def tearDown(self):
"""Makes sure Article has a get_latest_by"""
if not Article._meta.get_latest_by:
Article._meta.get_latest_by = 'pub_date' | [
"def",
"tearDown",
"(",
"self",
")",
":",
"if",
"not",
"Article",
".",
"_meta",
".",
"get_latest_by",
":",
"Article",
".",
"_meta",
".",
"get_latest_by",
"=",
"'pub_date'"
] | [
12,
4
] | [
15,
52
] | python | en | ['en', 'en', 'en'] | True |
TestFirstLast.test_index_error_not_suppressed | (self) |
#23555 -- Unexpected IndexError exceptions in QuerySet iteration
shouldn't be suppressed.
|
#23555 -- Unexpected IndexError exceptions in QuerySet iteration
shouldn't be suppressed.
| def test_index_error_not_suppressed(self):
"""
#23555 -- Unexpected IndexError exceptions in QuerySet iteration
shouldn't be suppressed.
"""
def check():
# We know that we've broken the __iter__ method, so the queryset
# should always raise an exception.
... | [
"def",
"test_index_error_not_suppressed",
"(",
"self",
")",
":",
"def",
"check",
"(",
")",
":",
"# We know that we've broken the __iter__ method, so the queryset",
"# should always raise an exception.",
"self",
".",
"assertRaises",
"(",
"IndexError",
",",
"lambda",
":",
"In... | [
158,
4
] | [
177,
15
] | python | en | ['en', 'error', 'th'] | False |
to_list | (value) |
Put value into a list if it's not already one. Return an empty list if
value is None.
|
Put value into a list if it's not already one. Return an empty list if
value is None.
| def to_list(value):
"""
Put value into a list if it's not already one. Return an empty list if
value is None.
"""
if value is None:
value = []
elif not isinstance(value, list):
value = [value]
return value | [
"def",
"to_list",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"value"
] | [
47,
0
] | [
56,
16
] | python | en | ['en', 'error', 'th'] | False |
connections_support_transactions | (aliases=None) |
Return whether or not all (or specified) connections support
transactions.
|
Return whether or not all (or specified) connections support
transactions.
| def connections_support_transactions(aliases=None):
"""
Return whether or not all (or specified) connections support
transactions.
"""
conns = connections.all() if aliases is None else (connections[alias] for alias in aliases)
return all(conn.features.supports_transactions for conn in conns) | [
"def",
"connections_support_transactions",
"(",
"aliases",
"=",
"None",
")",
":",
"conns",
"=",
"connections",
".",
"all",
"(",
")",
"if",
"aliases",
"is",
"None",
"else",
"(",
"connections",
"[",
"alias",
"]",
"for",
"alias",
"in",
"aliases",
")",
"return... | [
1068,
0
] | [
1074,
69
] | python | en | ['en', 'error', 'th'] | False |
skipIfDBFeature | (*features) | Skip a test if a database has at least one of the named features. | Skip a test if a database has at least one of the named features. | def skipIfDBFeature(*features):
"""Skip a test if a database has at least one of the named features."""
return _deferredSkip(
lambda: any(getattr(connection.features, feature, False) for feature in features),
"Database has feature(s) %s" % ", ".join(features),
'skipIfDBFeature',
) | [
"def",
"skipIfDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"any",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",",
"\"Database... | [
1254,
0
] | [
1260,
5
] | python | en | ['en', 'en', 'en'] | True |
skipUnlessDBFeature | (*features) | Skip a test unless a database has all the named features. | Skip a test unless a database has all the named features. | def skipUnlessDBFeature(*features):
"""Skip a test unless a database has all the named features."""
return _deferredSkip(
lambda: not all(getattr(connection.features, feature, False) for feature in features),
"Database doesn't support feature(s): %s" % ", ".join(features),
'skipUnlessDBF... | [
"def",
"skipUnlessDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"not",
"all",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",",
... | [
1263,
0
] | [
1269,
5
] | python | en | ['en', 'en', 'en'] | True |
skipUnlessAnyDBFeature | (*features) | Skip a test unless a database has any of the named features. | Skip a test unless a database has any of the named features. | def skipUnlessAnyDBFeature(*features):
"""Skip a test unless a database has any of the named features."""
return _deferredSkip(
lambda: not any(getattr(connection.features, feature, False) for feature in features),
"Database doesn't support any of the feature(s): %s" % ", ".join(features),
... | [
"def",
"skipUnlessAnyDBFeature",
"(",
"*",
"features",
")",
":",
"return",
"_deferredSkip",
"(",
"lambda",
":",
"not",
"any",
"(",
"getattr",
"(",
"connection",
".",
"features",
",",
"feature",
",",
"False",
")",
"for",
"feature",
"in",
"features",
")",
",... | [
1272,
0
] | [
1278,
5
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.__call__ | (self, result=None) |
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
|
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
| def __call__(self, result=None):
"""
Wrapper around default __call__ method to perform common Django test
set up. This means that user-defined Test Cases aren't required to
include a call to super().setUp().
"""
testMethod = getattr(self, self._testMethodName)
ski... | [
"def",
"__call__",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"testMethod",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"_testMethodName",
")",
"skipped",
"=",
"(",
"getattr",
"(",
"self",
".",
"__class__",
",",
"\"__unittest_skip__\"",
",",
"... | [
252,
4
] | [
276,
22
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase._pre_setup | (self) |
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
|
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
| def _pre_setup(self):
"""
Perform pre-test setup:
* Create a test client.
* Clear the mail test outbox.
"""
self.client = self.client_class()
mail.outbox = [] | [
"def",
"_pre_setup",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"self",
".",
"client_class",
"(",
")",
"mail",
".",
"outbox",
"=",
"[",
"]"
] | [
278,
4
] | [
285,
24
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase._post_teardown | (self) | Perform post-test things. | Perform post-test things. | def _post_teardown(self):
"""Perform post-test things."""
pass | [
"def",
"_post_teardown",
"(",
"self",
")",
":",
"pass"
] | [
287,
4
] | [
289,
12
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.settings | (self, **kwargs) |
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
|
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
| def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
"""
return override_settings(**kwargs) | [
"def",
"settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"override_settings",
"(",
"*",
"*",
"kwargs",
")"
] | [
291,
4
] | [
296,
42
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.modify_settings | (self, **kwargs) |
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
|
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
| def modify_settings(self, **kwargs):
"""
A context manager that temporarily applies changes a list setting and
reverts back to the original value when exiting the context.
"""
return modify_settings(**kwargs) | [
"def",
"modify_settings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"modify_settings",
"(",
"*",
"*",
"kwargs",
")"
] | [
298,
4
] | [
303,
40
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertRedirects | (self, response, expected_url, status_code=302,
target_status_code=200, msg_prefix='',
fetch_redirect_response=True) |
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't work for external links since it uses the test client to do a
request (use fetch_redirect_response=False to check such links without
fetching them).
|
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded. | def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, msg_prefix='',
fetch_redirect_response=True):
"""
Assert that a response redirected to a specific URL and that the
redirect URL can be loaded.
Won't... | [
"def",
"assertRedirects",
"(",
"self",
",",
"response",
",",
"expected_url",
",",
"status_code",
"=",
"302",
",",
"target_status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"fetch_redirect_response",
"=",
"True",
")",
":",
"if",
"msg_prefix",
":",
... | [
305,
4
] | [
383,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertURLEqual | (self, url1, url2, msg_prefix='') |
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
/path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
|
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name. | def assertURLEqual(self, url1, url2, msg_prefix=''):
"""
Assert that two URLs are the same, ignoring the order of query string
parameters except for parameters with the same name.
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
/path/?a=1&a=2 isn't equal to /path/?a=... | [
"def",
"assertURLEqual",
"(",
"self",
",",
"url1",
",",
"url2",
",",
"msg_prefix",
"=",
"''",
")",
":",
"def",
"normalize",
"(",
"url",
")",
":",
"\"\"\"Sort the URL's query string parameters.\"\"\"",
"url",
"=",
"str",
"(",
"url",
")",
"# Coerce reverse_lazy() ... | [
385,
4
] | [
403,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertContains | (self, response, text, count=None, status_code=200, msg_prefix='', html=False) |
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text... |
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the response.
If ``count`` is None, the count doesn't matter - the assertion is true
if the text... | def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` occurs ``count`` times in the content of the... | [
"def",
"assertContains",
"(",
"self",
",",
"response",
",",
"text",
",",
"count",
"=",
"None",
",",
"status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"html",
"=",
"False",
")",
":",
"text_repr",
",",
"real_count",
",",
"msg_prefix",
"=",
"s... | [
436,
4
] | [
453,
101
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertNotContains | (self, response, text, status_code=200, msg_prefix='', html=False) |
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
|
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
| def assertNotContains(self, response, text, status_code=200, msg_prefix='', html=False):
"""
Assert that a response indicates that some content was retrieved
successfully, (i.e., the HTTP status code was as expected) and that
``text`` doesn't occurs in the content of the response.
... | [
"def",
"assertNotContains",
"(",
"self",
",",
"response",
",",
"text",
",",
"status_code",
"=",
"200",
",",
"msg_prefix",
"=",
"''",
",",
"html",
"=",
"False",
")",
":",
"text_repr",
",",
"real_count",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_contains... | [
455,
4
] | [
464,
98
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFormError | (self, response, form, field, errors, msg_prefix='') |
Assert that a form used to render the response has a specific field
error.
|
Assert that a form used to render the response has a specific field
error.
| def assertFormError(self, response, form, field, errors, msg_prefix=''):
"""
Assert that a form used to render the response has a specific field
error.
"""
if msg_prefix:
msg_prefix += ": "
# Put context(s) into a list to simplify processing.
contexts... | [
"def",
"assertFormError",
"(",
"self",
",",
"response",
",",
"form",
",",
"field",
",",
"errors",
",",
"msg_prefix",
"=",
"''",
")",
":",
"if",
"msg_prefix",
":",
"msg_prefix",
"+=",
"\": \"",
"# Put context(s) into a list to simplify processing.",
"contexts",
"="... | [
466,
4
] | [
519,
94
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFormsetError | (self, response, formset, form_index, field, errors,
msg_prefix='') |
Assert that a formset used to render the response has a specific error.
For field errors, specify the ``form_index`` and the ``field``.
For non-field errors, specify the ``form_index`` and the ``field`` as
None.
For non-form errors, specify ``form_index`` as None and the ``fiel... |
Assert that a formset used to render the response has a specific error. | def assertFormsetError(self, response, formset, form_index, field, errors,
msg_prefix=''):
"""
Assert that a formset used to render the response has a specific error.
For field errors, specify the ``form_index`` and the ``field``.
For non-field errors, specify... | [
"def",
"assertFormsetError",
"(",
"self",
",",
"response",
",",
"formset",
",",
"form_index",
",",
"field",
",",
"errors",
",",
"msg_prefix",
"=",
"''",
")",
":",
"# Add punctuation to msg_prefix",
"if",
"msg_prefix",
":",
"msg_prefix",
"+=",
"\": \"",
"# Put co... | [
521,
4
] | [
599,
100
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertTemplateUsed | (self, response=None, template_name=None, msg_prefix='', count=None) |
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
|
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
| def assertTemplateUsed(self, response=None, template_name=None, msg_prefix='', count=None):
"""
Assert that the template with the provided name was used in rendering
the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_... | [
"def",
"assertTemplateUsed",
"(",
"self",
",",
"response",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"msg_prefix",
"=",
"''",
",",
"count",
"=",
"None",
")",
":",
"context_mgr_template",
",",
"template_names",
",",
"msg_prefix",
"=",
"self",
".",
... | [
625,
4
] | [
652,
13
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertTemplateNotUsed | (self, response=None, template_name=None, msg_prefix='') |
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
|
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
| def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''):
"""
Assert that the template with the provided name was NOT used in
rendering the response. Also usable as context manager.
"""
context_mgr_template, template_names, msg_prefix = self._assert_templ... | [
"def",
"assertTemplateNotUsed",
"(",
"self",
",",
"response",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"msg_prefix",
"=",
"''",
")",
":",
"context_mgr_template",
",",
"template_names",
",",
"msg_prefix",
"=",
"self",
".",
"_assert_template_used",
"("... | [
654,
4
] | [
669,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertRaisesMessage | (self, expected_exception, expected_message, *args, **kwargs) |
Assert that expected_message is found in the message of a raised
exception.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
args: Function to be called and extra positional args.
... |
Assert that expected_message is found in the message of a raised
exception. | def assertRaisesMessage(self, expected_exception, expected_message, *args, **kwargs):
"""
Assert that expected_message is found in the message of a raised
exception.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error... | [
"def",
"assertRaisesMessage",
"(",
"self",
",",
"expected_exception",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_assertFooMessage",
"(",
"self",
".",
"assertRaises",
",",
"'exception'",
",",
"expected... | [
689,
4
] | [
703,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertWarnsMessage | (self, expected_warning, expected_message, *args, **kwargs) |
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
|
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
| def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs):
"""
Same as assertRaisesMessage but for assertWarns() instead of
assertRaises().
"""
return self._assertFooMessage(
self.assertWarns, 'warning', expected_warning, expected_message,
... | [
"def",
"assertWarnsMessage",
"(",
"self",
",",
"expected_warning",
",",
"expected_message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_assertFooMessage",
"(",
"self",
".",
"assertWarns",
",",
"'warning'",
",",
"expected_warni... | [
705,
4
] | [
713,
9
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertFieldOutput | (self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value='') |
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one ... |
Assert that a form field behaves correctly with various inputs. | def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dict... | [
"def",
"assertFieldOutput",
"(",
"self",
",",
"fieldclass",
",",
"valid",
",",
"invalid",
",",
"field_args",
"=",
"None",
",",
"field_kwargs",
"=",
"None",
",",
"empty_value",
"=",
"''",
")",
":",
"if",
"field_args",
"is",
"None",
":",
"field_args",
"=",
... | [
715,
4
] | [
759,
86
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertHTMLEqual | (self, html1, html2, msg=None) |
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
|
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
| def assertHTMLEqual(self, html1, html2, msg=None):
"""
Assert that two HTML snippets are semantically the same.
Whitespace in most cases is ignored, and attribute ordering is not
significant. The arguments must be valid HTML.
"""
dom1 = assert_and_parse_html(self, html1, ... | [
"def",
"assertHTMLEqual",
"(",
"self",
",",
"html1",
",",
"html2",
",",
"msg",
"=",
"None",
")",
":",
"dom1",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html1",
",",
"msg",
",",
"'First argument is not valid HTML:'",
")",
"dom2",
"=",
"assert_and_parse_h... | [
761,
4
] | [
777,
60
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertHTMLNotEqual | (self, html1, html2, msg=None) | Assert that two HTML snippets are not semantically equivalent. | Assert that two HTML snippets are not semantically equivalent. | def assertHTMLNotEqual(self, html1, html2, msg=None):
"""Assert that two HTML snippets are not semantically equivalent."""
dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')
... | [
"def",
"assertHTMLNotEqual",
"(",
"self",
",",
"html1",
",",
"html2",
",",
"msg",
"=",
"None",
")",
":",
"dom1",
"=",
"assert_and_parse_html",
"(",
"self",
",",
"html1",
",",
"msg",
",",
"'First argument is not valid HTML:'",
")",
"dom2",
"=",
"assert_and_pars... | [
779,
4
] | [
787,
60
] | python | en | ['en', 'en', 'en'] | True |
SimpleTestCase.assertJSONEqual | (self, raw, expected_data, msg=None) |
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
|
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
| def assertJSONEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.loads(raw)
... | [
"def",
"assertJSONEqual",
"(",
"self",
",",
"raw",
",",
"expected_data",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"raw",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"self",
".",
"fail",
"(",
"\"Fi... | [
801,
4
] | [
816,
54
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertJSONNotEqual | (self, raw, expected_data, msg=None) |
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
|
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
| def assertJSONNotEqual(self, raw, expected_data, msg=None):
"""
Assert that the JSON fragments raw and expected_data are not equal.
Usual JSON non-significant whitespace rules apply as the heavyweight
is delegated to the json library.
"""
try:
data = json.load... | [
"def",
"assertJSONNotEqual",
"(",
"self",
",",
"raw",
",",
"expected_data",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"raw",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"self",
".",
"fail",
"(",
"\... | [
818,
4
] | [
833,
57
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertXMLEqual | (self, xml1, xml2, msg=None) |
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
|
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
| def assertXMLEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are semantically the same.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(xml1, xml2... | [
"def",
"assertXMLEqual",
"(",
"self",
",",
"xml1",
",",
"xml2",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"compare_xml",
"(",
"xml1",
",",
"xml2",
")",
"except",
"Exception",
"as",
"e",
":",
"standardMsg",
"=",
"'First or second argum... | [
835,
4
] | [
853,
64
] | python | en | ['en', 'error', 'th'] | False |
SimpleTestCase.assertXMLNotEqual | (self, xml1, xml2, msg=None) |
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
|
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
| def assertXMLNotEqual(self, xml1, xml2, msg=None):
"""
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
"""
try:
result = compare_xml(x... | [
"def",
"assertXMLNotEqual",
"(",
"self",
",",
"xml1",
",",
"xml2",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"compare_xml",
"(",
"xml1",
",",
"xml2",
")",
"except",
"Exception",
"as",
"e",
":",
"standardMsg",
"=",
"'First or second ar... | [
855,
4
] | [
869,
64
] | python | en | ['en', 'error', 'th'] | False |
TransactionTestCase._pre_setup | (self) |
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, inst... |
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class has a 'fixtures' attribute, inst... | def _pre_setup(self):
"""
Perform pre-test setup:
* If the class has an 'available_apps' attribute, restrict the app
registry to these applications, then fire the post_migrate signal --
it must run with the correct set of applications for the test case.
* If the class... | [
"def",
"_pre_setup",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_pre_setup",
"(",
")",
"if",
"self",
".",
"available_apps",
"is",
"not",
"None",
":",
"apps",
".",
"set_available_apps",
"(",
"self",
".",
"available_apps",
")",
"setting_changed",
".",
... | [
917,
4
] | [
952,
52
] | python | en | ['en', 'error', 'th'] | False |
TransactionTestCase._post_teardown | (self) |
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
|
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
| def _post_teardown(self):
"""
Perform post-test things:
* Flush the contents of the database to leave a clean slate. If the
class has an 'available_apps' attribute, don't fire post_migrate.
* Force-close the connection so the next test gets a clean cursor.
"""
t... | [
"def",
"_post_teardown",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_fixture_teardown",
"(",
")",
"super",
"(",
")",
".",
"_post_teardown",
"(",
")",
"if",
"self",
".",
"_should_reload_connections",
"(",
")",
":",
"# Some DB cursors include SQL statements ... | [
1000,
4
] | [
1025,
49
] | python | en | ['en', 'error', 'th'] | False |
TestCase._enter_atomics | (cls) | Open atomic blocks for multiple databases. | Open atomic blocks for multiple databases. | def _enter_atomics(cls):
"""Open atomic blocks for multiple databases."""
atomics = {}
for db_name in cls._databases_names():
atomics[db_name] = transaction.atomic(using=db_name)
atomics[db_name].__enter__()
return atomics | [
"def",
"_enter_atomics",
"(",
"cls",
")",
":",
"atomics",
"=",
"{",
"}",
"for",
"db_name",
"in",
"cls",
".",
"_databases_names",
"(",
")",
":",
"atomics",
"[",
"db_name",
"]",
"=",
"transaction",
".",
"atomic",
"(",
"using",
"=",
"db_name",
")",
"atomi... | [
1101,
4
] | [
1107,
22
] | python | en | ['en', 'no', 'en'] | True |
TestCase._rollback_atomics | (cls, atomics) | Rollback atomic blocks opened by the previous method. | Rollback atomic blocks opened by the previous method. | def _rollback_atomics(cls, atomics):
"""Rollback atomic blocks opened by the previous method."""
for db_name in reversed(cls._databases_names()):
transaction.set_rollback(True, using=db_name)
atomics[db_name].__exit__(None, None, None) | [
"def",
"_rollback_atomics",
"(",
"cls",
",",
"atomics",
")",
":",
"for",
"db_name",
"in",
"reversed",
"(",
"cls",
".",
"_databases_names",
"(",
")",
")",
":",
"transaction",
".",
"set_rollback",
"(",
"True",
",",
"using",
"=",
"db_name",
")",
"atomics",
... | [
1110,
4
] | [
1114,
55
] | python | en | ['en', 'en', 'en'] | True |
TestCase.setUpTestData | (cls) | Load initial data for the TestCase. | Load initial data for the TestCase. | def setUpTestData(cls):
"""Load initial data for the TestCase."""
pass | [
"def",
"setUpTestData",
"(",
"cls",
")",
":",
"pass"
] | [
1151,
4
] | [
1153,
12
] | python | en | ['en', 'en', 'en'] | True |
FSFilesHandler._should_handle | (self, path) |
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
|
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
| def _should_handle(self, path):
"""
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
"""
return path.startswith(self.base_url[2]) and not self.base_url[1] | [
"def",
"_should_handle",
"(",
"self",
",",
"path",
")",
":",
"return",
"path",
".",
"startswith",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
"and",
"not",
"self",
".",
"base_url",
"[",
"1",
"]"
] | [
1300,
4
] | [
1306,
73
] | python | en | ['en', 'error', 'th'] | False |
FSFilesHandler.file_path | (self, url) | Return the relative path to the file on disk for the given URL. | Return the relative path to the file on disk for the given URL. | def file_path(self, url):
"""Return the relative path to the file on disk for the given URL."""
relative_url = url[len(self.base_url[2]):]
return url2pathname(relative_url) | [
"def",
"file_path",
"(",
"self",
",",
"url",
")",
":",
"relative_url",
"=",
"url",
"[",
"len",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
":",
"]",
"return",
"url2pathname",
"(",
"relative_url",
")"
] | [
1308,
4
] | [
1311,
41
] | python | en | ['en', 'en', 'en'] | True |
LiveServerThread.run | (self) |
Set up the live server and databases, and then loop over handling
HTTP requests.
|
Set up the live server and databases, and then loop over handling
HTTP requests.
| def run(self):
"""
Set up the live server and databases, and then loop over handling
HTTP requests.
"""
if self.connections_override:
# Override this thread's database connections with the ones
# provided by the main thread.
for alias, conn in ... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"connections_override",
":",
"# Override this thread's database connections with the ones",
"# provided by the main thread.",
"for",
"alias",
",",
"conn",
"in",
"self",
".",
"connections_override",
".",
"items",
"(... | [
1374,
4
] | [
1398,
35
] | python | en | ['en', 'error', 'th'] | False |
register_check | (check, codes=None) | Register a new check object. | Register a new check object. | def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
... | [
"def",
"register_check",
"(",
"check",
",",
"codes",
"=",
"None",
")",
":",
"def",
"_add_check",
"(",
"check",
",",
"kind",
",",
"codes",
",",
"args",
")",
":",
"if",
"check",
"in",
"_checks",
"[",
"kind",
"]",
":",
"_checks",
"[",
"kind",
"]",
"["... | [
178,
0
] | [
194,
16
] | python | en | ['en', 'en', 'en'] | True |
tabs_or_spaces | (physical_line, indent_char) | r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoking the Python command line interpreter with
the ... | r"""Never mix tabs and spaces. | def tabs_or_spaces(physical_line, indent_char):
r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoki... | [
"def",
"tabs_or_spaces",
"(",
"physical_line",
",",
"indent_char",
")",
":",
"indent",
"=",
"INDENT_REGEX",
".",
"match",
"(",
"physical_line",
")",
".",
"group",
"(",
"1",
")",
"for",
"offset",
",",
"char",
"in",
"enumerate",
"(",
"indent",
")",
":",
"i... | [
202,
0
] | [
219,
76
] | python | en | ['en', 'en', 'en'] | True |
tabs_obsolete | (physical_line) | r"""On new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
| r"""On new projects, spaces-only are strongly recommended over tabs. | def tabs_obsolete(physical_line):
r"""On new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
"""
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tab... | [
"def",
"tabs_obsolete",
"(",
"physical_line",
")",
":",
"indent",
"=",
"INDENT_REGEX",
".",
"match",
"(",
"physical_line",
")",
".",
"group",
"(",
"1",
")",
"if",
"'\\t'",
"in",
"indent",
":",
"return",
"indent",
".",
"index",
"(",
"'\\t'",
")",
",",
"... | [
223,
0
] | [
231,
67
] | python | en | ['en', 'en', 'en'] | True |
trailing_whitespace | (physical_line) | r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
| r"""Trailing whitespace is superfluous. | def trailing_whitespace(physical_line):
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank,
for easier filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12... | [
"def",
"trailing_whitespace",
"(",
"physical_line",
")",
":",
"physical_line",
"=",
"physical_line",
".",
"rstrip",
"(",
"'\\n'",
")",
"# chr(10), newline",
"physical_line",
"=",
"physical_line",
".",
"rstrip",
"(",
"'\\r'",
")",
"# chr(13), carriage return",
"physica... | [
235,
0
] | [
253,
59
] | python | en | ['en', 'en', 'en'] | True |
trailing_blank_lines | (physical_line, lines, line_number, total_lines) | r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292).
| r"""Trailing blank lines are superfluous. | def trailing_blank_lines(physical_line, lines, line_number, total_lines):
r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292).
"""
if line_number == total_lines:
stripped_last_line = physical_line.rstri... | [
"def",
"trailing_blank_lines",
"(",
"physical_line",
",",
"lines",
",",
"line_number",
",",
"total_lines",
")",
":",
"if",
"line_number",
"==",
"total_lines",
":",
"stripped_last_line",
"=",
"physical_line",
".",
"rstrip",
"(",
")",
"if",
"physical_line",
"and",
... | [
257,
0
] | [
270,
67
] | python | en | ['en', 'en', 'en'] | True |
maximum_line_length | (physical_line, max_line_length, multiline,
line_number, noqa) | r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to
have several windows side-by-side. The default wrapping on such
devices looks ugly. Therefore, please limit all l... | r"""Limit all lines to a maximum of 79 characters. | def maximum_line_length(physical_line, max_line_length, multiline,
line_number, noqa):
r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to
have... | [
"def",
"maximum_line_length",
"(",
"physical_line",
",",
"max_line_length",
",",
"multiline",
",",
"line_number",
",",
"noqa",
")",
":",
"line",
"=",
"physical_line",
".",
"rstrip",
"(",
")",
"length",
"=",
"len",
"(",
"line",
")",
"if",
"length",
">",
"ma... | [
274,
0
] | [
309,
71
] | python | en | ['en', 'en', 'en'] | True |
blank_lines | (logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines) | r"""Separate top-level function and class definitions with two blank
lines.
Method definitions inside a class are separated by a single blank
line.
Extra blank lines may be used (sparingly) to separate groups of
related functions. Blank lines may be omitted between a bunch of
related one-line... | r"""Separate top-level function and class definitions with two blank
lines. | def blank_lines(logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines):
r"""Separate top-level function and class definitions with two blank
lines.
Method definitio... | [
"def",
"blank_lines",
"(",
"logical_line",
",",
"blank_lines",
",",
"indent_level",
",",
"line_number",
",",
"blank_before",
",",
"previous_logical",
",",
"previous_unindented_logical_line",
",",
"previous_indent_level",
",",
"lines",
")",
":",
"# noqa",
"top_level_line... | [
353,
0
] | [
435,
46
] | python | en | ['en', 'en', 'en'] | True |
extraneous_whitespace | (logical_line) | r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in these situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
Okay: spam(ham[1], {eggs: 2})
E201: spam( ham[1], {eggs: 2})
E201: spam(ham[ 1], {eggs: 2})
E201: spam(... | r"""Avoid extraneous whitespace. | def extraneous_whitespace(logical_line):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in these situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
Okay: spam(ham[1], {eggs: 2})
E201: spam( ham[1], {eggs: 2})
E... | [
"def",
"extraneous_whitespace",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"match",
"in",
"EXTRANEOUS_WHITESPACE_REGEX",
".",
"finditer",
"(",
"line",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"char",
"=",
"text",
".",
... | [
439,
0
] | [
468,
67
] | python | el-Latn | ['en', 'el-Latn', 'it'] | False |
whitespace_around_keywords | (logical_line) | r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False
| r"""Avoid extraneous whitespace around keywords. | def whitespace_around_keywords(logical_line):
r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False
"""
for match in KEYWORD_REGEX.finditer(logical_line):
before, after = matc... | [
"def",
"whitespace_around_keywords",
"(",
"logical_line",
")",
":",
"for",
"match",
"in",
"KEYWORD_REGEX",
".",
"finditer",
"(",
"logical_line",
")",
":",
"before",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"'\\t'",
"in",
"before",
":",
"y... | [
472,
0
] | [
492,
70
] | python | en | ['en', 'el-Latn', 'en'] | True |
missing_whitespace_after_import_keyword | (logical_line) | r"""Multiple imports in form from x import (a, b, c) should have
space between import statement and parenthesised name list.
Okay: from foo import (bar, baz)
E275: from foo import(bar, baz)
E275: from importable.module import(bar, baz)
| r"""Multiple imports in form from x import (a, b, c) should have
space between import statement and parenthesised name list. | def missing_whitespace_after_import_keyword(logical_line):
r"""Multiple imports in form from x import (a, b, c) should have
space between import statement and parenthesised name list.
Okay: from foo import (bar, baz)
E275: from foo import(bar, baz)
E275: from importable.module import(bar, baz)
... | [
"def",
"missing_whitespace_after_import_keyword",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"indicator",
"=",
"' import('",
"if",
"line",
".",
"startswith",
"(",
"'from '",
")",
":",
"found",
"=",
"line",
".",
"find",
"(",
"indicator",
")",
"... | [
496,
0
] | [
510,
62
] | python | en | ['en', 'en', 'en'] | True |
missing_whitespace | (logical_line) | r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
| r"""Each comma, semicolon or colon should be followed by whitespace. | def missing_whitespace(logical_line):
r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
"""
line = logical_line
for ind... | [
"def",
"missing_whitespace",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"line",
")",
"-",
"1",
")",
":",
"char",
"=",
"line",
"[",
"index",
"]",
"next_char",
"=",
"line",
"[",
"index",
... | [
514,
0
] | [
540,
68
] | python | en | ['en', 'en', 'en'] | True |
indentation | (logical_line, previous_logical, indent_char,
indent_level, previous_indent_level) | r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue
to use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\n pass
E112: for item in items:\npass
E115: for item ... | r"""Use 4 spaces per indentation level. | def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level):
r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue
to use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a... | [
"def",
"indentation",
"(",
"logical_line",
",",
"previous_logical",
",",
"indent_char",
",",
"indent_level",
",",
"previous_indent_level",
")",
":",
"c",
"=",
"0",
"if",
"logical_line",
"else",
"3",
"tmpl",
"=",
"\"E11%d %s\"",
"if",
"logical_line",
"else",
"\"E... | [
544,
0
] | [
578,
48
] | python | ca | ['ca', 'en', 'it'] | False |
continued_indentation | (logical_line, tokens, indent_level, hang_closing,
indent_char, noqa, verbose) | r"""Continuation lines indentation.
Continuation lines should align wrapped elements either vertically
using Python's implicit line joining inside parentheses, brackets
and braces, or using a hanging indent.
When using a hanging indent these considerations should be applied:
- there should be no a... | r"""Continuation lines indentation. | def continued_indentation(logical_line, tokens, indent_level, hang_closing,
indent_char, noqa, verbose):
r"""Continuation lines indentation.
Continuation lines should align wrapped elements either vertically
using Python's implicit line joining inside parentheses, brackets
and... | [
"def",
"continued_indentation",
"(",
"logical_line",
",",
"tokens",
",",
"indent_level",
",",
"hang_closing",
",",
"indent_char",
",",
"noqa",
",",
"verbose",
")",
":",
"first_row",
"=",
"tokens",
"[",
"0",
"]",
"[",
"2",
"]",
"[",
"0",
"]",
"nrows",
"="... | [
582,
0
] | [
783,
68
] | python | en | ['es', 'en', 'nl'] | False |
whitespace_before_parameters | (logical_line, tokens) | r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in the following situations:
- before the open parenthesis that starts the argument list of a
function call.
- before the open parenthesis that starts an indexing or slicing.
Okay: spam(1)
E211: spam (1)
Okay: dict['key'] = li... | r"""Avoid extraneous whitespace. | def whitespace_before_parameters(logical_line, tokens):
r"""Avoid extraneous whitespace.
Avoid extraneous whitespace in the following situations:
- before the open parenthesis that starts the argument list of a
function call.
- before the open parenthesis that starts an indexing or slicing.
... | [
"def",
"whitespace_before_parameters",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_type",
",",
"prev_text",
",",
"__",
",",
"prev_end",
",",
"__",
"=",
"tokens",
"[",
"0",
"]",
"for",
"index",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"tokens",
... | [
787,
0
] | [
816,
22
] | python | el-Latn | ['en', 'el-Latn', 'it'] | False |
whitespace_around_operator | (logical_line) | r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5
| r"""Avoid extraneous whitespace around an operator. | def whitespace_around_operator(logical_line):
r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5
"""
for match in OPERATOR_REGEX.finditer(logical_line):
before, after = match.groups()
... | [
"def",
"whitespace_around_operator",
"(",
"logical_line",
")",
":",
"for",
"match",
"in",
"OPERATOR_REGEX",
".",
"finditer",
"(",
"logical_line",
")",
":",
"before",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"'\\t'",
"in",
"before",
":",
"... | [
820,
0
] | [
840,
71
] | python | en | ['en', 'el-Latn', 'en'] | True |
missing_whitespace_around_operator | (logical_line, tokens) | r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with... | r"""Surround operators with a single space on either side. | def missing_whitespace_around_operator(logical_line, tokens):
r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is... | [
"def",
"missing_whitespace_around_operator",
"(",
"logical_line",
",",
"tokens",
")",
":",
"parens",
"=",
"0",
"need_space",
"=",
"False",
"prev_type",
"=",
"tokenize",
".",
"OP",
"prev_text",
"=",
"prev_end",
"=",
"None",
"operator_types",
"=",
"(",
"tokenize",... | [
844,
0
] | [
948,
22
] | python | en | ['en', 'en', 'en'] | True |
whitespace_around_comma | (logical_line) | r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
| r"""Avoid extraneous whitespace after a comma or a colon. | def whitespace_around_comma(logical_line):
r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
"""
line = logical_line
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
fou... | [
"def",
"whitespace_around_comma",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"m",
"in",
"WHITESPACE_AFTER_COMMA_REGEX",
".",
"finditer",
"(",
"line",
")",
":",
"found",
"=",
"m",
".",
"start",
"(",
")",
"+",
"1",
"if",
"'\\t'",
"in"... | [
952,
0
] | [
967,
73
] | python | en | ['en', 'en', 'en'] | True |
whitespace_around_named_parameter_equals | (logical_line, tokens) | r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value, except when
using a type annotation.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a... | r"""Don't use spaces around the '=' sign in function arguments. | def whitespace_around_named_parameter_equals(logical_line, tokens):
r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value, except when
using a type annotation.
Okay: def complex(rea... | [
"def",
"whitespace_around_named_parameter_equals",
"(",
"logical_line",
",",
"tokens",
")",
":",
"parens",
"=",
"0",
"no_space",
"=",
"False",
"require_space",
"=",
"False",
"prev_end",
"=",
"None",
"annotated_func_arg",
"=",
"False",
"in_def",
"=",
"bool",
"(",
... | [
971,
0
] | [
1033,
22
] | python | en | ['en', 'en', 'en'] | True |
whitespace_before_comment | (logical_line, tokens) | r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement.
Inline comments should be separated by at least two spaces from the
statement. They should start with a # and a single space.
Each line of a block comment starts with a # and a single s... | r"""Separate inline comments by at least two spaces. | def whitespace_before_comment(logical_line, tokens):
r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement.
Inline comments should be separated by at least two spaces from the
statement. They should start with a # and a single space.
Ea... | [
"def",
"whitespace_before_comment",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_end",
"=",
"(",
"0",
",",
"0",
")",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
"in",
"tokens",
":",
"if",
"token_type",
"==",
"tokenize"... | [
1037,
0
] | [
1075,
26
] | python | en | ['en', 'en', 'en'] | True |
imports_on_separate_lines | (logical_line) | r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass
| r"""Place imports on separate lines. | def imports_on_separate_lines(logical_line):
r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import f... | [
"def",
"imports_on_separate_lines",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"if",
"line",
".",
"startswith",
"(",
"'import '",
")",
":",
"found",
"=",
"line",
".",
"find",
"(",
"','",
")",
"if",
"-",
"1",
"<",
"found",
"and",
"';'",
... | [
1079,
0
] | [
1095,
60
] | python | en | ['en', 'en', 'en'] | True |
module_imports_on_top_of_file | (
logical_line, indent_level, checker_state, noqa) | r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module
comments and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is ... | r"""Place imports at the top of the file. | def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module
comments and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is ... | [
"def",
"module_imports_on_top_of_file",
"(",
"logical_line",
",",
"indent_level",
",",
"checker_state",
",",
"noqa",
")",
":",
"# noqa",
"def",
"is_string_literal",
"(",
"line",
")",
":",
"if",
"line",
"[",
"0",
"]",
"in",
"'uUbB'",
":",
"line",
"=",
"line",... | [
1099,
0
] | [
1154,
48
] | python | en | ['en', 'en', 'en'] | True |
compound_statements | (logical_line) | r"""Compound statements (on the same line) are generally
discouraged.
While sometimes it's okay to put an if/for/while with a small body
on the same line, never do this for multi-clause statements.
Also avoid folding such long lines!
Always use a def statement instead of an assignment statement th... | r"""Compound statements (on the same line) are generally
discouraged. | def compound_statements(logical_line):
r"""Compound statements (on the same line) are generally
discouraged.
While sometimes it's okay to put an if/for/while with a small body
on the same line, never do this for multi-clause statements.
Also avoid folding such long lines!
Always use a def stat... | [
"def",
"compound_statements",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"last_char",
"=",
"len",
"(",
"line",
")",
"-",
"1",
"found",
"=",
"line",
".",
"find",
"(",
"':'",
")",
"prev_found",
"=",
"0",
"counts",
"=",
"{",
"char",
":",
... | [
1158,
0
] | [
1218,
41
] | python | en | ['en', 'en', 'en'] | True |
explicit_line_join | (logical_line, tokens) | r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's
implied line continuation inside parentheses, brackets and braces.
Long lines can be broken over multiple lines by wrapping expressions
in parentheses. These should be used in preference to usi... | r"""Avoid explicit line join between brackets. | def explicit_line_join(logical_line, tokens):
r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's
implied line continuation inside parentheses, brackets and braces.
Long lines can be broken over multiple lines by wrapping expressions
in paren... | [
"def",
"explicit_line_join",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_start",
"=",
"prev_end",
"=",
"parens",
"=",
"0",
"comment",
"=",
"False",
"backslash",
"=",
"None",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
... | [
1222,
0
] | [
1259,
27
] | python | en | ['en', 'en', 'en'] | True |
_break_around_binary_operators | (tokens) | Private function to reduce duplication.
This factors out the shared details between
:func:`break_before_binary_operator` and
:func:`break_after_binary_operator`.
| Private function to reduce duplication. | def _break_around_binary_operators(tokens):
"""Private function to reduce duplication.
This factors out the shared details between
:func:`break_before_binary_operator` and
:func:`break_after_binary_operator`.
"""
line_break = False
unary_context = True
# Previous non-newline token types... | [
"def",
"_break_around_binary_operators",
"(",
"tokens",
")",
":",
"line_break",
"=",
"False",
"unary_context",
"=",
"True",
"# Previous non-newline token types and text",
"previous_token_type",
"=",
"None",
"previous_text",
"=",
"None",
"for",
"token_type",
",",
"text",
... | [
1278,
0
] | [
1301,
32
] | python | en | ['en', 'en', 'en'] | True |
break_before_binary_operator | (logical_line, tokens) | r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
W503: var = (1\n & ~2)
W503: var = (1\n / -2)
W503: var = (1\n ... | r"""
Avoid breaks before binary operators. | def break_before_binary_operator(logical_line, tokens):
r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
W503: var = (1\n & ~2... | [
"def",
"break_before_binary_operator",
"(",
"logical_line",
",",
"tokens",
")",
":",
"for",
"context",
"in",
"_break_around_binary_operators",
"(",
"tokens",
")",
":",
"(",
"token_type",
",",
"text",
",",
"previous_token_type",
",",
"previous_text",
",",
"line_break... | [
1305,
0
] | [
1331,
65
] | python | cy | ['en', 'cy', 'hi'] | False |
break_after_binary_operator | (logical_line, tokens) | r"""
Avoid breaks after binary operators.
The preferred place to break around a binary operator is before the
operator, not after it.
W504: (width == 0 +\n height == 0)
W504: (width == 0 and\n height == 0)
W504: var = (1 &\n ~2)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay:... | r"""
Avoid breaks after binary operators. | def break_after_binary_operator(logical_line, tokens):
r"""
Avoid breaks after binary operators.
The preferred place to break around a binary operator is before the
operator, not after it.
W504: (width == 0 +\n height == 0)
W504: (width == 0 and\n height == 0)
W504: var = (1 &\n ~2)
... | [
"def",
"break_after_binary_operator",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_start",
"=",
"None",
"for",
"context",
"in",
"_break_around_binary_operators",
"(",
"tokens",
")",
":",
"(",
"token_type",
",",
"text",
",",
"previous_token_type",
",",
"prev... | [
1335,
0
] | [
1366,
26
] | python | cy | ['en', 'cy', 'hi'] | False |
comparison_to_singleton | (logical_line, noqa) | r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E712: if arg == True:
E712: if False == arg:
A... | r"""Comparison to singletons should use "is" or "is not". | def comparison_to_singleton(logical_line, noqa):
r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E7... | [
"def",
"comparison_to_singleton",
"(",
"logical_line",
",",
"noqa",
")",
":",
"match",
"=",
"not",
"noqa",
"and",
"COMPARE_SINGLETON_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
":",
"singleton",
"=",
"match",
".",
"group",
"(",
"1",
")",
... | [
1370,
0
] | [
1401,
54
] | python | en | ['en', 'en', 'en'] | True |
comparison_negative | (logical_line) | r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if not X is Y:\n pass
E714: Z = not X.... | r"""Negative comparison should be done using "not in" and "is not". | def comparison_negative(logical_line):
r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if... | [
"def",
"comparison_negative",
"(",
"logical_line",
")",
":",
"match",
"=",
"COMPARE_NEGATIVE_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
":",
"pos",
"=",
"match",
".",
"start",
"(",
"1",
")",
"if",
"match",
".",
"group",
"(",
"2",
")"... | [
1405,
0
] | [
1423,
73
] | python | en | ['en', 'en', 'en'] | True |
comparison_type | (logical_line, noqa) | r"""Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int):
E721: if type(obj) is type(1):
When checking if an object is a string, keep in mind that it might
be a unicode string too! In Python 2.3, str and unicode have a
common bas... | r"""Object type comparisons should always use isinstance(). | def comparison_type(logical_line, noqa):
r"""Object type comparisons should always use isinstance().
Do not compare types directly.
Okay: if isinstance(obj, int):
E721: if type(obj) is type(1):
When checking if an object is a string, keep in mind that it might
be a unicode string too! In Pyth... | [
"def",
"comparison_type",
"(",
"logical_line",
",",
"noqa",
")",
":",
"match",
"=",
"COMPARE_TYPE_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
"and",
"not",
"noqa",
":",
"inst",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"inst",
... | [
1427,
0
] | [
1447,
76
] | python | en | ['en', 'en', 'en'] | True |
bare_except | (logical_line, noqa) | r"""When catching exceptions, mention specific exceptions when
possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
| r"""When catching exceptions, mention specific exceptions when
possible. | def bare_except(logical_line, noqa):
r"""When catching exceptions, mention specific exceptions when
possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
"""
if noqa:
return
regex = re.compile(r"except\s*:")
match = regex.match(logical_line)
if mat... | [
"def",
"bare_except",
"(",
"logical_line",
",",
"noqa",
")",
":",
"if",
"noqa",
":",
"return",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"except\\s*:\"",
")",
"match",
"=",
"regex",
".",
"match",
"(",
"logical_line",
")",
"if",
"match",
":",
"yield",
... | [
1451,
0
] | [
1465,
60
] | python | en | ['en', 'en', 'en'] | True |
ambiguous_identifier | (logical_line, tokens) | r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the
numerals one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = 0
E741: O = 123
E741: I = 42
Variables ... | r"""Never use the characters 'l', 'O', or 'I' as variable names. | def ambiguous_identifier(logical_line, tokens):
r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the
numerals one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = ... | [
"def",
"ambiguous_identifier",
"(",
"logical_line",
",",
"tokens",
")",
":",
"is_func_def",
"=",
"False",
"# Set to true if 'def' is found",
"parameter_parentheses_level",
"=",
"0",
"idents_to_avoid",
"=",
"(",
"'l'",
",",
"'O'",
",",
"'I'",
")",
"prev_type",
",",
... | [
1469,
0
] | [
1549,
26
] | python | en | ['en', 'en', 'en'] | True |
python_3000_has_key | (logical_line, noqa) | r"""The {}.has_key() method is removed in Python 3: use the 'in'
operator.
Okay: if "alph" in d:\n print d["alph"]
W601: assert d.has_key('alph')
| r"""The {}.has_key() method is removed in Python 3: use the 'in'
operator. | def python_3000_has_key(logical_line, noqa):
r"""The {}.has_key() method is removed in Python 3: use the 'in'
operator.
Okay: if "alph" in d:\n print d["alph"]
W601: assert d.has_key('alph')
"""
pos = logical_line.find('.has_key(')
if pos > -1 and not noqa:
yield pos, "W601 .has_... | [
"def",
"python_3000_has_key",
"(",
"logical_line",
",",
"noqa",
")",
":",
"pos",
"=",
"logical_line",
".",
"find",
"(",
"'.has_key('",
")",
"if",
"pos",
">",
"-",
"1",
"and",
"not",
"noqa",
":",
"yield",
"pos",
",",
"\"W601 .has_key() is deprecated, use 'in'\"... | [
1553,
0
] | [
1562,
60
] | python | en | ['en', 'en', 'en'] | True |
python_3000_raise_comma | (logical_line) | r"""When raising an exception, use "raise ValueError('message')".
The older form is removed in Python 3.
Okay: raise DummyError("Message")
W602: raise DummyError, "Message"
| r"""When raising an exception, use "raise ValueError('message')". | def python_3000_raise_comma(logical_line):
r"""When raising an exception, use "raise ValueError('message')".
The older form is removed in Python 3.
Okay: raise DummyError("Message")
W602: raise DummyError, "Message"
"""
match = RAISE_COMMA_REGEX.match(logical_line)
if match and not RERAISE... | [
"def",
"python_3000_raise_comma",
"(",
"logical_line",
")",
":",
"match",
"=",
"RAISE_COMMA_REGEX",
".",
"match",
"(",
"logical_line",
")",
"if",
"match",
"and",
"not",
"RERAISE_COMMA_REGEX",
".",
"match",
"(",
"logical_line",
")",
":",
"yield",
"match",
".",
... | [
1566,
0
] | [
1576,
74
] | python | en | ['en', 'en', 'en'] | True |
python_3000_not_equal | (logical_line) | r"""New code should always use != instead of <>.
The older syntax is removed in Python 3.
Okay: if a != 'no':
W603: if a <> 'no':
| r"""New code should always use != instead of <>. | def python_3000_not_equal(logical_line):
r"""New code should always use != instead of <>.
The older syntax is removed in Python 3.
Okay: if a != 'no':
W603: if a <> 'no':
"""
pos = logical_line.find('<>')
if pos > -1:
yield pos, "W603 '<>' is deprecated, use '!='" | [
"def",
"python_3000_not_equal",
"(",
"logical_line",
")",
":",
"pos",
"=",
"logical_line",
".",
"find",
"(",
"'<>'",
")",
"if",
"pos",
">",
"-",
"1",
":",
"yield",
"pos",
",",
"\"W603 '<>' is deprecated, use '!='\""
] | [
1580,
0
] | [
1590,
54
] | python | en | ['en', 'en', 'en'] | True |
python_3000_backticks | (logical_line) | r"""Use repr() instead of backticks in Python 3.
Okay: val = repr(1 + 2)
W604: val = `1 + 2`
| r"""Use repr() instead of backticks in Python 3. | def python_3000_backticks(logical_line):
r"""Use repr() instead of backticks in Python 3.
Okay: val = repr(1 + 2)
W604: val = `1 + 2`
"""
pos = logical_line.find('`')
if pos > -1:
yield pos, "W604 backticks are deprecated, use 'repr()'" | [
"def",
"python_3000_backticks",
"(",
"logical_line",
")",
":",
"pos",
"=",
"logical_line",
".",
"find",
"(",
"'`'",
")",
"if",
"pos",
">",
"-",
"1",
":",
"yield",
"pos",
",",
"\"W604 backticks are deprecated, use 'repr()'\""
] | [
1594,
0
] | [
1602,
64
] | python | en | ['en', 'en', 'en'] | True |
python_3000_invalid_escape_sequence | (logical_line, tokens, noqa) | r"""Invalid escape sequences are deprecated in Python 3.6.
Okay: regex = r'\.png$'
W605: regex = '\.png$'
| r"""Invalid escape sequences are deprecated in Python 3.6. | def python_3000_invalid_escape_sequence(logical_line, tokens, noqa):
r"""Invalid escape sequences are deprecated in Python 3.6.
Okay: regex = r'\.png$'
W605: regex = '\.png$'
"""
if noqa:
return
# https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
v... | [
"def",
"python_3000_invalid_escape_sequence",
"(",
"logical_line",
",",
"tokens",
",",
"noqa",
")",
":",
"if",
"noqa",
":",
"return",
"# https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals",
"valid",
"=",
"[",
"'\\n'",
",",
"'\\\\'",
",",
"... | [
1606,
0
] | [
1662,
52
] | python | en | ['en', 'en', 'it'] | True |
python_3000_async_await_keywords | (logical_line, tokens) | async' and 'await' are reserved keywords starting at Python 3.7.
W606: async = 42
W606: await = 42
Okay: async def read(db):\n data = await db.fetch('SELECT ...')
| async' and 'await' are reserved keywords starting at Python 3.7. | def python_3000_async_await_keywords(logical_line, tokens):
"""'async' and 'await' are reserved keywords starting at Python 3.7.
W606: async = 42
W606: await = 42
Okay: async def read(db):\n data = await db.fetch('SELECT ...')
"""
# The Python tokenize library before Python 3.5 recognizes
... | [
"def",
"python_3000_async_await_keywords",
"(",
"logical_line",
",",
"tokens",
")",
":",
"# The Python tokenize library before Python 3.5 recognizes",
"# async/await as a NAME token. Therefore, use a state machine to",
"# look for the possible async/await constructs as defined by the",
"# Pyth... | [
1666,
0
] | [
1732,
9
] | python | en | ['en', 'en', 'en'] | True |
maximum_doc_length | (logical_line, max_doc_length, noqa, tokens) | r"""Limit all doc lines to a maximum of 72 characters.
For flowing long blocks of text (docstrings or comments), limiting
the length to 72 characters is recommended.
Reports warning W505
| r"""Limit all doc lines to a maximum of 72 characters. | def maximum_doc_length(logical_line, max_doc_length, noqa, tokens):
r"""Limit all doc lines to a maximum of 72 characters.
For flowing long blocks of text (docstrings or comments), limiting
the length to 72 characters is recommended.
Reports warning W505
"""
if max_doc_length is None or noqa:
... | [
"def",
"maximum_doc_length",
"(",
"logical_line",
",",
"max_doc_length",
",",
"noqa",
",",
"tokens",
")",
":",
"if",
"max_doc_length",
"is",
"None",
"or",
"noqa",
":",
"return",
"prev_token",
"=",
"None",
"skip_lines",
"=",
"set",
"(",
")",
"# Skip lines that"... | [
1737,
0
] | [
1787,
31
] | python | en | ['en', 'en', 'en'] | True |
expand_indent | (line) | r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
| r"""Return the amount of indentation. | def expand_indent(line):
r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
"""
line = line.rstrip('\n\r')
if '\... | [
"def",
"expand_indent",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\n\\r'",
")",
"if",
"'\\t'",
"not",
"in",
"line",
":",
"return",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"result",
... | [
1825,
0
] | [
1850,
17
] | python | en | ['en', 'da', 'en'] | True |
mute_string | (text) | Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'"
| Replace contents with 'xxx' to prevent syntax matching. | def mute_string(text):
"""Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'"
"""
# String modifiers (e.g. u or r)
start = text.index(text[-1]) + 1
end = len(text... | [
"def",
"mute_string",
"(",
"text",
")",
":",
"# String modifiers (e.g. u or r)",
"start",
"=",
"text",
".",
"index",
"(",
"text",
"[",
"-",
"1",
"]",
")",
"+",
"1",
"end",
"=",
"len",
"(",
"text",
")",
"-",
"1",
"# Triple quotes",
"if",
"text",
"[",
... | [
1853,
0
] | [
1870,
58
] | python | en | ['en', 'en', 'en'] | True |
parse_udiff | (diff, patterns=None, parent='.') | Return a dictionary of matching lines. | Return a dictionary of matching lines. | def parse_udiff(diff, patterns=None, parent='.'):
"""Return a dictionary of matching lines."""
# For each file of the diff, the entry key is the filename,
# and the value is a set of row numbers to consider.
rv = {}
path = nrows = None
for line in diff.splitlines():
if nrows:
... | [
"def",
"parse_udiff",
"(",
"diff",
",",
"patterns",
"=",
"None",
",",
"parent",
"=",
"'.'",
")",
":",
"# For each file of the diff, the entry key is the filename,",
"# and the value is a set of row numbers to consider.",
"rv",
"=",
"{",
"}",
"path",
"=",
"nrows",
"=",
... | [
1873,
0
] | [
1899,
5
] | python | en | ['en', 'en', 'en'] | True |
normalize_paths | (value, parent=os.curdir) | Parse a comma-separated list of paths.
Return a list of absolute paths.
| Parse a comma-separated list of paths. | def normalize_paths(value, parent=os.curdir):
"""Parse a comma-separated list of paths.
Return a list of absolute paths.
"""
if not value:
return []
if isinstance(value, list):
return value
paths = []
for path in value.split(','):
path = path.strip()
if '/' i... | [
"def",
"normalize_paths",
"(",
"value",
",",
"parent",
"=",
"os",
".",
"curdir",
")",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"value",
"paths",
"=",
"[",
"]",
"for",
"pa... | [
1902,
0
] | [
1917,
16
] | python | en | ['en', 'en', 'en'] | True |
filename_match | (filename, patterns, default=True) | Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True.
| Check if patterns contains a pattern that matches filename. | def filename_match(filename, patterns, default=True):
"""Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True.
"""
if not patterns:
return default
return any(fnmatch(filename, pattern) for pattern in patterns) | [
"def",
"filename_match",
"(",
"filename",
",",
"patterns",
",",
"default",
"=",
"True",
")",
":",
"if",
"not",
"patterns",
":",
"return",
"default",
"return",
"any",
"(",
"fnmatch",
"(",
"filename",
",",
"pattern",
")",
"for",
"pattern",
"in",
"patterns",
... | [
1920,
0
] | [
1927,
66
] | python | en | ['en', 'en', 'en'] | True |
update_counts | (s, counts) | r"""Adds one to the counts of each appearance of characters in s,
for characters in counts | r"""Adds one to the counts of each appearance of characters in s,
for characters in counts | def update_counts(s, counts):
r"""Adds one to the counts of each appearance of characters in s,
for characters in counts"""
for char in s:
if char in counts:
counts[char] += 1 | [
"def",
"update_counts",
"(",
"s",
",",
"counts",
")",
":",
"for",
"char",
"in",
"s",
":",
"if",
"char",
"in",
"counts",
":",
"counts",
"[",
"char",
"]",
"+=",
"1"
] | [
1930,
0
] | [
1935,
29
] | python | en | ['en', 'en', 'en'] | True |
get_parser | (prog='pycodestyle', version=__version__) | Create the parser for the program. | Create the parser for the program. | def get_parser(prog='pycodestyle', version=__version__):
"""Create the parser for the program."""
parser = OptionParser(prog=prog, version=version,
usage="%prog [options] input ...")
parser.config_options = [
'exclude', 'filename', 'select', 'ignore', 'max-line-length',
... | [
"def",
"get_parser",
"(",
"prog",
"=",
"'pycodestyle'",
",",
"version",
"=",
"__version__",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"prog",
"=",
"prog",
",",
"version",
"=",
"version",
",",
"usage",
"=",
"\"%prog [options] input ...\"",
")",
"parser",
... | [
2515,
0
] | [
2578,
17
] | python | en | ['en', 'en', 'en'] | True |
read_config | (options, args, arglist, parser) | Read and parse configurations.
If a config file is specified on the command line with the
"--config" option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any
local configurations in the current directory or above will be
merged together (in ... | Read and parse configurations. | def read_config(options, args, arglist, parser):
"""Read and parse configurations.
If a config file is specified on the command line with the
"--config" option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any
local configurations in the cur... | [
"def",
"read_config",
"(",
"options",
",",
"args",
",",
"arglist",
",",
"parser",
")",
":",
"config",
"=",
"RawConfigParser",
"(",
")",
"cli_conf",
"=",
"options",
".",
"config",
"local_dir",
"=",
"os",
".",
"curdir",
"if",
"USER_CONFIG",
"and",
"os",
".... | [
2581,
0
] | [
2653,
18
] | python | en | ['en', 'en', 'en'] | True |
Checker.report_invalid_syntax | (self) | Check if the syntax is valid. | Check if the syntax is valid. | def report_invalid_syntax(self):
"""Check if the syntax is valid."""
(exc_type, exc) = sys.exc_info()[:2]
if len(exc.args) > 1:
offset = exc.args[1]
if len(offset) > 2:
offset = offset[1:3]
else:
offset = (1, 0)
self.report_erro... | [
"def",
"report_invalid_syntax",
"(",
"self",
")",
":",
"(",
"exc_type",
",",
"exc",
")",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
"if",
"len",
"(",
"exc",
".",
"args",
")",
">",
"1",
":",
"offset",
"=",
"exc",
".",
"args",
"["... | [
1994,
4
] | [
2005,
53
] | python | en | ['en', 'en', 'en'] | True |
Checker.readline | (self) | Get the next line from the input buffer. | Get the next line from the input buffer. | def readline(self):
"""Get the next line from the input buffer."""
if self.line_number >= self.total_lines:
return ''
line = self.lines[self.line_number]
self.line_number += 1
if self.indent_char is None and line[:1] in WHITESPACE:
self.indent_char = line[... | [
"def",
"readline",
"(",
"self",
")",
":",
"if",
"self",
".",
"line_number",
">=",
"self",
".",
"total_lines",
":",
"return",
"''",
"line",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"line_number",
"]",
"self",
".",
"line_number",
"+=",
"1",
"if",
"... | [
2007,
4
] | [
2015,
19
] | python | en | ['en', 'en', 'en'] | True |
Checker.run_check | (self, check, argument_names) | Run a check plugin. | Run a check plugin. | def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | [
"def",
"run_check",
"(",
"self",
",",
"check",
",",
"argument_names",
")",
":",
"arguments",
"=",
"[",
"]",
"for",
"name",
"in",
"argument_names",
":",
"arguments",
".",
"append",
"(",
"getattr",
"(",
"self",
",",
"name",
")",
")",
"return",
"check",
"... | [
2017,
4
] | [
2022,
32
] | python | en | ['it', 'gl', 'en'] | False |
Checker.init_checker_state | (self, name, argument_names) | Prepare custom state for the specific checker plugin. | Prepare custom state for the specific checker plugin. | def init_checker_state(self, name, argument_names):
"""Prepare custom state for the specific checker plugin."""
if 'checker_state' in argument_names:
self.checker_state = self._checker_states.setdefault(name, {}) | [
"def",
"init_checker_state",
"(",
"self",
",",
"name",
",",
"argument_names",
")",
":",
"if",
"'checker_state'",
"in",
"argument_names",
":",
"self",
".",
"checker_state",
"=",
"self",
".",
"_checker_states",
".",
"setdefault",
"(",
"name",
",",
"{",
"}",
")... | [
2024,
4
] | [
2027,
74
] | python | en | ['en', 'it', 'en'] | True |
Checker.check_physical | (self, line) | Run all physical checks on a raw input line. | Run all physical checks on a raw input line. | def check_physical(self, line):
"""Run all physical checks on a raw input line."""
self.physical_line = line
for name, check, argument_names in self._physical_checks:
self.init_checker_state(name, argument_names)
result = self.run_check(check, argument_names)
... | [
"def",
"check_physical",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"physical_line",
"=",
"line",
"for",
"name",
",",
"check",
",",
"argument_names",
"in",
"self",
".",
"_physical_checks",
":",
"self",
".",
"init_checker_state",
"(",
"name",
",",
"ar... | [
2029,
4
] | [
2039,
46
] | python | en | ['en', 'en', 'en'] | True |
Checker.build_tokens_line | (self) | Build a logical line from tokens. | Build a logical line from tokens. | def build_tokens_line(self):
"""Build a logical line from tokens."""
logical = []
comments = []
length = 0
prev_row = prev_col = mapping = None
for token_type, text, start, end, line in self.tokens:
if token_type in SKIP_TOKENS:
continue
... | [
"def",
"build_tokens_line",
"(",
"self",
")",
":",
"logical",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"length",
"=",
"0",
"prev_row",
"=",
"prev_col",
"=",
"mapping",
"=",
"None",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"li... | [
2041,
4
] | [
2072,
22
] | python | en | ['en', 'en', 'en'] | True |
Checker.check_logical | (self) | Build a line from tokens and run all logical checks on it. | Build a line from tokens and run all logical checks on it. | def check_logical(self):
"""Build a line from tokens and run all logical checks on it."""
self.report.increment_logical_line()
mapping = self.build_tokens_line()
if not mapping:
return
mapping_offsets = [offset for offset, _ in mapping]
(start_row, start_col)... | [
"def",
"check_logical",
"(",
"self",
")",
":",
"self",
".",
"report",
".",
"increment_logical_line",
"(",
")",
"mapping",
"=",
"self",
".",
"build_tokens_line",
"(",
")",
"if",
"not",
"mapping",
":",
"return",
"mapping_offsets",
"=",
"[",
"offset",
"for",
... | [
2074,
4
] | [
2107,
24
] | python | en | ['en', 'en', 'en'] | True |
Checker.check_ast | (self) | Build the file's AST and run all AST checks. | Build the file's AST and run all AST checks. | def check_ast(self):
"""Build the file's AST and run all AST checks."""
try:
tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
except (ValueError, SyntaxError, TypeError):
return self.report_invalid_syntax()
for name, cls, __ in self._ast_checks:
... | [
"def",
"check_ast",
"(",
"self",
")",
":",
"try",
":",
"tree",
"=",
"compile",
"(",
"''",
".",
"join",
"(",
"self",
".",
"lines",
")",
",",
"''",
",",
"'exec'",
",",
"PyCF_ONLY_AST",
")",
"except",
"(",
"ValueError",
",",
"SyntaxError",
",",
"TypeErr... | [
2109,
4
] | [
2119,
66
] | python | en | ['en', 'en', 'en'] | True |
Checker.generate_tokens | (self) | Tokenize file, run physical line checks and yield tokens. | Tokenize file, run physical line checks and yield tokens. | def generate_tokens(self):
"""Tokenize file, run physical line checks and yield tokens."""
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
tokengen = tokenize.generate_tokens(self.readline)
try:
for token in tokengen:
... | [
"def",
"generate_tokens",
"(",
"self",
")",
":",
"if",
"self",
".",
"_io_error",
":",
"self",
".",
"report_error",
"(",
"1",
",",
"0",
",",
"'E902 %s'",
"%",
"self",
".",
"_io_error",
",",
"readlines",
")",
"tokengen",
"=",
"tokenize",
".",
"generate_tok... | [
2121,
4
] | [
2134,
40
] | python | en | ['en', 'en', 'en'] | True |
Checker.maybe_check_physical | (self, token) | If appropriate for token, check current physical line(s). | If appropriate for token, check current physical line(s). | def maybe_check_physical(self, token):
"""If appropriate for token, check current physical line(s)."""
# Called after every token, but act only on end of line.
if _is_eol_token(token):
# Obviously, a newline token ends a single physical line.
self.check_physical(token[4])... | [
"def",
"maybe_check_physical",
"(",
"self",
",",
"token",
")",
":",
"# Called after every token, but act only on end of line.",
"if",
"_is_eol_token",
"(",
"token",
")",
":",
"# Obviously, a newline token ends a single physical line.",
"self",
".",
"check_physical",
"(",
"tok... | [
2136,
4
] | [
2167,
34
] | python | en | ['en', 'en', 'en'] | True |
Checker.check_all | (self, expected=None, line_offset=0) | Run all checks on the input file. | Run all checks on the input file. | def check_all(self, expected=None, line_offset=0):
"""Run all checks on the input file."""
self.report.init_file(self.filename, self.lines, expected, line_offset)
self.total_lines = len(self.lines)
if self._ast_checks:
self.check_ast()
self.line_number = 0
sel... | [
"def",
"check_all",
"(",
"self",
",",
"expected",
"=",
"None",
",",
"line_offset",
"=",
"0",
")",
":",
"self",
".",
"report",
".",
"init_file",
"(",
"self",
".",
"filename",
",",
"self",
".",
"lines",
",",
"expected",
",",
"line_offset",
")",
"self",
... | [
2169,
4
] | [
2212,
45
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.