partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
send_payload
|
Sends a payload object, (the result of calling _build_payload() + _serialize_payload()).
Uses the configured handler from SETTINGS['handler']
Available handlers:
- 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it
- 'thread': starts a single-use thread that will call _send_payload(). returns immediately.
- 'agent': writes to a log file to be processed by rollbar-agent
- 'tornado': calls _send_payload_tornado() (which makes an async HTTP request using tornado's AsyncHTTPClient)
- 'gae': calls _send_payload_appengine() (which makes a blocking call to Google App Engine)
- 'twisted': calls _send_payload_twisted() (which makes an async HTTP reqeust using Twisted and Treq)
|
rollbar/__init__.py
|
def send_payload(payload, access_token):
"""
Sends a payload object, (the result of calling _build_payload() + _serialize_payload()).
Uses the configured handler from SETTINGS['handler']
Available handlers:
- 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it
- 'thread': starts a single-use thread that will call _send_payload(). returns immediately.
- 'agent': writes to a log file to be processed by rollbar-agent
- 'tornado': calls _send_payload_tornado() (which makes an async HTTP request using tornado's AsyncHTTPClient)
- 'gae': calls _send_payload_appengine() (which makes a blocking call to Google App Engine)
- 'twisted': calls _send_payload_twisted() (which makes an async HTTP reqeust using Twisted and Treq)
"""
payload = events.on_payload(payload)
if payload is False:
return
payload_str = _serialize_payload(payload)
handler = SETTINGS.get('handler')
if handler == 'blocking':
_send_payload(payload_str, access_token)
elif handler == 'agent':
agent_log.error(payload_str)
elif handler == 'tornado':
if TornadoAsyncHTTPClient is None:
log.error('Unable to find tornado')
return
_send_payload_tornado(payload_str, access_token)
elif handler == 'gae':
if AppEngineFetch is None:
log.error('Unable to find AppEngine URLFetch module')
return
_send_payload_appengine(payload_str, access_token)
elif handler == 'twisted':
if treq is None:
log.error('Unable to find Treq')
return
_send_payload_twisted(payload_str, access_token)
else:
# default to 'thread'
thread = threading.Thread(target=_send_payload, args=(payload_str, access_token))
_threads.put(thread)
thread.start()
|
def send_payload(payload, access_token):
"""
Sends a payload object, (the result of calling _build_payload() + _serialize_payload()).
Uses the configured handler from SETTINGS['handler']
Available handlers:
- 'blocking': calls _send_payload() (which makes an HTTP request) immediately, blocks on it
- 'thread': starts a single-use thread that will call _send_payload(). returns immediately.
- 'agent': writes to a log file to be processed by rollbar-agent
- 'tornado': calls _send_payload_tornado() (which makes an async HTTP request using tornado's AsyncHTTPClient)
- 'gae': calls _send_payload_appengine() (which makes a blocking call to Google App Engine)
- 'twisted': calls _send_payload_twisted() (which makes an async HTTP reqeust using Twisted and Treq)
"""
payload = events.on_payload(payload)
if payload is False:
return
payload_str = _serialize_payload(payload)
handler = SETTINGS.get('handler')
if handler == 'blocking':
_send_payload(payload_str, access_token)
elif handler == 'agent':
agent_log.error(payload_str)
elif handler == 'tornado':
if TornadoAsyncHTTPClient is None:
log.error('Unable to find tornado')
return
_send_payload_tornado(payload_str, access_token)
elif handler == 'gae':
if AppEngineFetch is None:
log.error('Unable to find AppEngine URLFetch module')
return
_send_payload_appengine(payload_str, access_token)
elif handler == 'twisted':
if treq is None:
log.error('Unable to find Treq')
return
_send_payload_twisted(payload_str, access_token)
else:
# default to 'thread'
thread = threading.Thread(target=_send_payload, args=(payload_str, access_token))
_threads.put(thread)
thread.start()
|
[
"Sends",
"a",
"payload",
"object",
"(",
"the",
"result",
"of",
"calling",
"_build_payload",
"()",
"+",
"_serialize_payload",
"()",
")",
".",
"Uses",
"the",
"configured",
"handler",
"from",
"SETTINGS",
"[",
"handler",
"]"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L436-L479
|
[
"def",
"send_payload",
"(",
"payload",
",",
"access_token",
")",
":",
"payload",
"=",
"events",
".",
"on_payload",
"(",
"payload",
")",
"if",
"payload",
"is",
"False",
":",
"return",
"payload_str",
"=",
"_serialize_payload",
"(",
"payload",
")",
"handler",
"=",
"SETTINGS",
".",
"get",
"(",
"'handler'",
")",
"if",
"handler",
"==",
"'blocking'",
":",
"_send_payload",
"(",
"payload_str",
",",
"access_token",
")",
"elif",
"handler",
"==",
"'agent'",
":",
"agent_log",
".",
"error",
"(",
"payload_str",
")",
"elif",
"handler",
"==",
"'tornado'",
":",
"if",
"TornadoAsyncHTTPClient",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Unable to find tornado'",
")",
"return",
"_send_payload_tornado",
"(",
"payload_str",
",",
"access_token",
")",
"elif",
"handler",
"==",
"'gae'",
":",
"if",
"AppEngineFetch",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Unable to find AppEngine URLFetch module'",
")",
"return",
"_send_payload_appengine",
"(",
"payload_str",
",",
"access_token",
")",
"elif",
"handler",
"==",
"'twisted'",
":",
"if",
"treq",
"is",
"None",
":",
"log",
".",
"error",
"(",
"'Unable to find Treq'",
")",
"return",
"_send_payload_twisted",
"(",
"payload_str",
",",
"access_token",
")",
"else",
":",
"# default to 'thread'",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"_send_payload",
",",
"args",
"=",
"(",
"payload_str",
",",
"access_token",
")",
")",
"_threads",
".",
"put",
"(",
"thread",
")",
"thread",
".",
"start",
"(",
")"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
search_items
|
Searches a project for items that match the input criteria.
title: all or part of the item's title to search for.
return_fields: the fields that should be returned for each item.
e.g. ['id', 'project_id', 'status'] will return a dict containing
only those fields for each item.
access_token: a project access token. If this is not provided,
the one provided to init() will be used instead.
search_fields: additional fields to include in the search.
currently supported: status, level, environment
|
rollbar/__init__.py
|
def search_items(title, return_fields=None, access_token=None, endpoint=None, **search_fields):
"""
Searches a project for items that match the input criteria.
title: all or part of the item's title to search for.
return_fields: the fields that should be returned for each item.
e.g. ['id', 'project_id', 'status'] will return a dict containing
only those fields for each item.
access_token: a project access token. If this is not provided,
the one provided to init() will be used instead.
search_fields: additional fields to include in the search.
currently supported: status, level, environment
"""
if not title:
return []
if return_fields is not None:
return_fields = ','.join(return_fields)
return _get_api('search/',
title=title,
fields=return_fields,
access_token=access_token,
endpoint=endpoint,
**search_fields)
|
def search_items(title, return_fields=None, access_token=None, endpoint=None, **search_fields):
"""
Searches a project for items that match the input criteria.
title: all or part of the item's title to search for.
return_fields: the fields that should be returned for each item.
e.g. ['id', 'project_id', 'status'] will return a dict containing
only those fields for each item.
access_token: a project access token. If this is not provided,
the one provided to init() will be used instead.
search_fields: additional fields to include in the search.
currently supported: status, level, environment
"""
if not title:
return []
if return_fields is not None:
return_fields = ','.join(return_fields)
return _get_api('search/',
title=title,
fields=return_fields,
access_token=access_token,
endpoint=endpoint,
**search_fields)
|
[
"Searches",
"a",
"project",
"for",
"items",
"that",
"match",
"the",
"input",
"criteria",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L482-L506
|
[
"def",
"search_items",
"(",
"title",
",",
"return_fields",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"*",
"*",
"search_fields",
")",
":",
"if",
"not",
"title",
":",
"return",
"[",
"]",
"if",
"return_fields",
"is",
"not",
"None",
":",
"return_fields",
"=",
"','",
".",
"join",
"(",
"return_fields",
")",
"return",
"_get_api",
"(",
"'search/'",
",",
"title",
"=",
"title",
",",
"fields",
"=",
"return_fields",
",",
"access_token",
"=",
"access_token",
",",
"endpoint",
"=",
"endpoint",
",",
"*",
"*",
"search_fields",
")"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_create_agent_log
|
Creates .rollbar log file for use with rollbar-agent
|
rollbar/__init__.py
|
def _create_agent_log():
"""
Creates .rollbar log file for use with rollbar-agent
"""
log_file = SETTINGS['agent.log_file']
if not log_file.endswith('.rollbar'):
log.error("Provided agent log file does not end with .rollbar, which it must. "
"Using default instead.")
log_file = DEFAULTS['agent.log_file']
retval = logging.getLogger('rollbar_agent')
handler = logging.FileHandler(log_file, 'a', 'utf-8')
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
retval.addHandler(handler)
retval.setLevel(logging.WARNING)
return retval
|
def _create_agent_log():
"""
Creates .rollbar log file for use with rollbar-agent
"""
log_file = SETTINGS['agent.log_file']
if not log_file.endswith('.rollbar'):
log.error("Provided agent log file does not end with .rollbar, which it must. "
"Using default instead.")
log_file = DEFAULTS['agent.log_file']
retval = logging.getLogger('rollbar_agent')
handler = logging.FileHandler(log_file, 'a', 'utf-8')
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
retval.addHandler(handler)
retval.setLevel(logging.WARNING)
return retval
|
[
"Creates",
".",
"rollbar",
"log",
"file",
"for",
"use",
"with",
"rollbar",
"-",
"agent"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L609-L625
|
[
"def",
"_create_agent_log",
"(",
")",
":",
"log_file",
"=",
"SETTINGS",
"[",
"'agent.log_file'",
"]",
"if",
"not",
"log_file",
".",
"endswith",
"(",
"'.rollbar'",
")",
":",
"log",
".",
"error",
"(",
"\"Provided agent log file does not end with .rollbar, which it must. \"",
"\"Using default instead.\"",
")",
"log_file",
"=",
"DEFAULTS",
"[",
"'agent.log_file'",
"]",
"retval",
"=",
"logging",
".",
"getLogger",
"(",
"'rollbar_agent'",
")",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_file",
",",
"'a'",
",",
"'utf-8'",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(message)s'",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"retval",
".",
"addHandler",
"(",
"handler",
")",
"retval",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"return",
"retval"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_report_exc_info
|
Called by report_exc_info() wrapper
|
rollbar/__init__.py
|
def _report_exc_info(exc_info, request, extra_data, payload_data, level=None):
"""
Called by report_exc_info() wrapper
"""
if not _check_config():
return
filtered_level = _filtered_level(exc_info[1])
if level is None:
level = filtered_level
filtered_exc_info = events.on_exception_info(exc_info,
request=request,
extra_data=extra_data,
payload_data=payload_data,
level=level)
if filtered_exc_info is False:
return
cls, exc, trace = filtered_exc_info
data = _build_base_data(request)
if level is not None:
data['level'] = level
# walk the trace chain to collect cause and context exceptions
trace_chain = _walk_trace_chain(cls, exc, trace)
extra_trace_data = None
if len(trace_chain) > 1:
data['body'] = {
'trace_chain': trace_chain
}
if payload_data and ('body' in payload_data) and ('trace' in payload_data['body']):
extra_trace_data = payload_data['body']['trace']
del payload_data['body']['trace']
else:
data['body'] = {
'trace': trace_chain[0]
}
if extra_data:
extra_data = extra_data
if not isinstance(extra_data, dict):
extra_data = {'value': extra_data}
if extra_trace_data:
extra_data = dict_merge(extra_data, extra_trace_data)
data['custom'] = extra_data
if extra_trace_data and not extra_data:
data['custom'] = extra_trace_data
request = _get_actual_request(request)
_add_request_data(data, request)
_add_person_data(data, request)
_add_lambda_context_data(data)
data['server'] = _build_server_data()
if payload_data:
data = dict_merge(data, payload_data)
payload = _build_payload(data)
send_payload(payload, payload.get('access_token'))
return data['uuid']
|
def _report_exc_info(exc_info, request, extra_data, payload_data, level=None):
"""
Called by report_exc_info() wrapper
"""
if not _check_config():
return
filtered_level = _filtered_level(exc_info[1])
if level is None:
level = filtered_level
filtered_exc_info = events.on_exception_info(exc_info,
request=request,
extra_data=extra_data,
payload_data=payload_data,
level=level)
if filtered_exc_info is False:
return
cls, exc, trace = filtered_exc_info
data = _build_base_data(request)
if level is not None:
data['level'] = level
# walk the trace chain to collect cause and context exceptions
trace_chain = _walk_trace_chain(cls, exc, trace)
extra_trace_data = None
if len(trace_chain) > 1:
data['body'] = {
'trace_chain': trace_chain
}
if payload_data and ('body' in payload_data) and ('trace' in payload_data['body']):
extra_trace_data = payload_data['body']['trace']
del payload_data['body']['trace']
else:
data['body'] = {
'trace': trace_chain[0]
}
if extra_data:
extra_data = extra_data
if not isinstance(extra_data, dict):
extra_data = {'value': extra_data}
if extra_trace_data:
extra_data = dict_merge(extra_data, extra_trace_data)
data['custom'] = extra_data
if extra_trace_data and not extra_data:
data['custom'] = extra_trace_data
request = _get_actual_request(request)
_add_request_data(data, request)
_add_person_data(data, request)
_add_lambda_context_data(data)
data['server'] = _build_server_data()
if payload_data:
data = dict_merge(data, payload_data)
payload = _build_payload(data)
send_payload(payload, payload.get('access_token'))
return data['uuid']
|
[
"Called",
"by",
"report_exc_info",
"()",
"wrapper"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L628-L693
|
[
"def",
"_report_exc_info",
"(",
"exc_info",
",",
"request",
",",
"extra_data",
",",
"payload_data",
",",
"level",
"=",
"None",
")",
":",
"if",
"not",
"_check_config",
"(",
")",
":",
"return",
"filtered_level",
"=",
"_filtered_level",
"(",
"exc_info",
"[",
"1",
"]",
")",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"filtered_level",
"filtered_exc_info",
"=",
"events",
".",
"on_exception_info",
"(",
"exc_info",
",",
"request",
"=",
"request",
",",
"extra_data",
"=",
"extra_data",
",",
"payload_data",
"=",
"payload_data",
",",
"level",
"=",
"level",
")",
"if",
"filtered_exc_info",
"is",
"False",
":",
"return",
"cls",
",",
"exc",
",",
"trace",
"=",
"filtered_exc_info",
"data",
"=",
"_build_base_data",
"(",
"request",
")",
"if",
"level",
"is",
"not",
"None",
":",
"data",
"[",
"'level'",
"]",
"=",
"level",
"# walk the trace chain to collect cause and context exceptions",
"trace_chain",
"=",
"_walk_trace_chain",
"(",
"cls",
",",
"exc",
",",
"trace",
")",
"extra_trace_data",
"=",
"None",
"if",
"len",
"(",
"trace_chain",
")",
">",
"1",
":",
"data",
"[",
"'body'",
"]",
"=",
"{",
"'trace_chain'",
":",
"trace_chain",
"}",
"if",
"payload_data",
"and",
"(",
"'body'",
"in",
"payload_data",
")",
"and",
"(",
"'trace'",
"in",
"payload_data",
"[",
"'body'",
"]",
")",
":",
"extra_trace_data",
"=",
"payload_data",
"[",
"'body'",
"]",
"[",
"'trace'",
"]",
"del",
"payload_data",
"[",
"'body'",
"]",
"[",
"'trace'",
"]",
"else",
":",
"data",
"[",
"'body'",
"]",
"=",
"{",
"'trace'",
":",
"trace_chain",
"[",
"0",
"]",
"}",
"if",
"extra_data",
":",
"extra_data",
"=",
"extra_data",
"if",
"not",
"isinstance",
"(",
"extra_data",
",",
"dict",
")",
":",
"extra_data",
"=",
"{",
"'value'",
":",
"extra_data",
"}",
"if",
"extra_trace_data",
":",
"extra_data",
"=",
"dict_merge",
"(",
"extra_data",
",",
"extra_trace_data",
")",
"data",
"[",
"'custom'",
"]",
"=",
"extra_data",
"if",
"extra_trace_data",
"and",
"not",
"extra_data",
":",
"data",
"[",
"'custom'",
"]",
"=",
"extra_trace_data",
"request",
"=",
"_get_actual_request",
"(",
"request",
")",
"_add_request_data",
"(",
"data",
",",
"request",
")",
"_add_person_data",
"(",
"data",
",",
"request",
")",
"_add_lambda_context_data",
"(",
"data",
")",
"data",
"[",
"'server'",
"]",
"=",
"_build_server_data",
"(",
")",
"if",
"payload_data",
":",
"data",
"=",
"dict_merge",
"(",
"data",
",",
"payload_data",
")",
"payload",
"=",
"_build_payload",
"(",
"data",
")",
"send_payload",
"(",
"payload",
",",
"payload",
".",
"get",
"(",
"'access_token'",
")",
")",
"return",
"data",
"[",
"'uuid'",
"]"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_report_message
|
Called by report_message() wrapper
|
rollbar/__init__.py
|
def _report_message(message, level, request, extra_data, payload_data):
"""
Called by report_message() wrapper
"""
if not _check_config():
return
filtered_message = events.on_message(message,
request=request,
extra_data=extra_data,
payload_data=payload_data,
level=level)
if filtered_message is False:
return
data = _build_base_data(request, level=level)
# message
data['body'] = {
'message': {
'body': filtered_message
}
}
if extra_data:
extra_data = extra_data
data['body']['message'].update(extra_data)
request = _get_actual_request(request)
_add_request_data(data, request)
_add_person_data(data, request)
_add_lambda_context_data(data)
data['server'] = _build_server_data()
if payload_data:
data = dict_merge(data, payload_data)
payload = _build_payload(data)
send_payload(payload, payload.get('access_token'))
return data['uuid']
|
def _report_message(message, level, request, extra_data, payload_data):
"""
Called by report_message() wrapper
"""
if not _check_config():
return
filtered_message = events.on_message(message,
request=request,
extra_data=extra_data,
payload_data=payload_data,
level=level)
if filtered_message is False:
return
data = _build_base_data(request, level=level)
# message
data['body'] = {
'message': {
'body': filtered_message
}
}
if extra_data:
extra_data = extra_data
data['body']['message'].update(extra_data)
request = _get_actual_request(request)
_add_request_data(data, request)
_add_person_data(data, request)
_add_lambda_context_data(data)
data['server'] = _build_server_data()
if payload_data:
data = dict_merge(data, payload_data)
payload = _build_payload(data)
send_payload(payload, payload.get('access_token'))
return data['uuid']
|
[
"Called",
"by",
"report_message",
"()",
"wrapper"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L727-L768
|
[
"def",
"_report_message",
"(",
"message",
",",
"level",
",",
"request",
",",
"extra_data",
",",
"payload_data",
")",
":",
"if",
"not",
"_check_config",
"(",
")",
":",
"return",
"filtered_message",
"=",
"events",
".",
"on_message",
"(",
"message",
",",
"request",
"=",
"request",
",",
"extra_data",
"=",
"extra_data",
",",
"payload_data",
"=",
"payload_data",
",",
"level",
"=",
"level",
")",
"if",
"filtered_message",
"is",
"False",
":",
"return",
"data",
"=",
"_build_base_data",
"(",
"request",
",",
"level",
"=",
"level",
")",
"# message",
"data",
"[",
"'body'",
"]",
"=",
"{",
"'message'",
":",
"{",
"'body'",
":",
"filtered_message",
"}",
"}",
"if",
"extra_data",
":",
"extra_data",
"=",
"extra_data",
"data",
"[",
"'body'",
"]",
"[",
"'message'",
"]",
".",
"update",
"(",
"extra_data",
")",
"request",
"=",
"_get_actual_request",
"(",
"request",
")",
"_add_request_data",
"(",
"data",
",",
"request",
")",
"_add_person_data",
"(",
"data",
",",
"request",
")",
"_add_lambda_context_data",
"(",
"data",
")",
"data",
"[",
"'server'",
"]",
"=",
"_build_server_data",
"(",
")",
"if",
"payload_data",
":",
"data",
"=",
"dict_merge",
"(",
"data",
",",
"payload_data",
")",
"payload",
"=",
"_build_payload",
"(",
"data",
")",
"send_payload",
"(",
"payload",
",",
"payload",
".",
"get",
"(",
"'access_token'",
")",
")",
"return",
"data",
"[",
"'uuid'",
"]"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_build_person_data
|
Returns a dictionary describing the logged-in user using data from `request.
Try request.rollbar_person first, then 'user', then 'user_id'
|
rollbar/__init__.py
|
def _build_person_data(request):
"""
Returns a dictionary describing the logged-in user using data from `request.
Try request.rollbar_person first, then 'user', then 'user_id'
"""
if hasattr(request, 'rollbar_person'):
rollbar_person_prop = request.rollbar_person
try:
person = rollbar_person_prop()
except TypeError:
person = rollbar_person_prop
if person and isinstance(person, dict):
return person
else:
return None
if hasattr(request, 'user'):
user_prop = request.user
try:
user = user_prop()
except TypeError:
user = user_prop
if not user:
return None
elif isinstance(user, dict):
return user
else:
retval = {}
if getattr(user, 'id', None):
retval['id'] = text(user.id)
elif getattr(user, 'user_id', None):
retval['id'] = text(user.user_id)
# id is required, so only include username/email if we have an id
if retval.get('id'):
username = getattr(user, 'username', None)
email = getattr(user, 'email', None)
retval.update({
'username': username,
'email': email
})
return retval
if hasattr(request, 'user_id'):
user_id_prop = request.user_id
try:
user_id = user_id_prop()
except TypeError:
user_id = user_id_prop
if not user_id:
return None
return {'id': text(user_id)}
|
def _build_person_data(request):
"""
Returns a dictionary describing the logged-in user using data from `request.
Try request.rollbar_person first, then 'user', then 'user_id'
"""
if hasattr(request, 'rollbar_person'):
rollbar_person_prop = request.rollbar_person
try:
person = rollbar_person_prop()
except TypeError:
person = rollbar_person_prop
if person and isinstance(person, dict):
return person
else:
return None
if hasattr(request, 'user'):
user_prop = request.user
try:
user = user_prop()
except TypeError:
user = user_prop
if not user:
return None
elif isinstance(user, dict):
return user
else:
retval = {}
if getattr(user, 'id', None):
retval['id'] = text(user.id)
elif getattr(user, 'user_id', None):
retval['id'] = text(user.user_id)
# id is required, so only include username/email if we have an id
if retval.get('id'):
username = getattr(user, 'username', None)
email = getattr(user, 'email', None)
retval.update({
'username': username,
'email': email
})
return retval
if hasattr(request, 'user_id'):
user_id_prop = request.user_id
try:
user_id = user_id_prop()
except TypeError:
user_id = user_id_prop
if not user_id:
return None
return {'id': text(user_id)}
|
[
"Returns",
"a",
"dictionary",
"describing",
"the",
"logged",
"-",
"in",
"user",
"using",
"data",
"from",
"request",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L821-L876
|
[
"def",
"_build_person_data",
"(",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'rollbar_person'",
")",
":",
"rollbar_person_prop",
"=",
"request",
".",
"rollbar_person",
"try",
":",
"person",
"=",
"rollbar_person_prop",
"(",
")",
"except",
"TypeError",
":",
"person",
"=",
"rollbar_person_prop",
"if",
"person",
"and",
"isinstance",
"(",
"person",
",",
"dict",
")",
":",
"return",
"person",
"else",
":",
"return",
"None",
"if",
"hasattr",
"(",
"request",
",",
"'user'",
")",
":",
"user_prop",
"=",
"request",
".",
"user",
"try",
":",
"user",
"=",
"user_prop",
"(",
")",
"except",
"TypeError",
":",
"user",
"=",
"user_prop",
"if",
"not",
"user",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"user",
",",
"dict",
")",
":",
"return",
"user",
"else",
":",
"retval",
"=",
"{",
"}",
"if",
"getattr",
"(",
"user",
",",
"'id'",
",",
"None",
")",
":",
"retval",
"[",
"'id'",
"]",
"=",
"text",
"(",
"user",
".",
"id",
")",
"elif",
"getattr",
"(",
"user",
",",
"'user_id'",
",",
"None",
")",
":",
"retval",
"[",
"'id'",
"]",
"=",
"text",
"(",
"user",
".",
"user_id",
")",
"# id is required, so only include username/email if we have an id",
"if",
"retval",
".",
"get",
"(",
"'id'",
")",
":",
"username",
"=",
"getattr",
"(",
"user",
",",
"'username'",
",",
"None",
")",
"email",
"=",
"getattr",
"(",
"user",
",",
"'email'",
",",
"None",
")",
"retval",
".",
"update",
"(",
"{",
"'username'",
":",
"username",
",",
"'email'",
":",
"email",
"}",
")",
"return",
"retval",
"if",
"hasattr",
"(",
"request",
",",
"'user_id'",
")",
":",
"user_id_prop",
"=",
"request",
".",
"user_id",
"try",
":",
"user_id",
"=",
"user_id_prop",
"(",
")",
"except",
"TypeError",
":",
"user_id",
"=",
"user_id_prop",
"if",
"not",
"user_id",
":",
"return",
"None",
"return",
"{",
"'id'",
":",
"text",
"(",
"user_id",
")",
"}"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_add_lambda_context_data
|
Attempts to add information from the lambda context if it exists
|
rollbar/__init__.py
|
def _add_lambda_context_data(data):
"""
Attempts to add information from the lambda context if it exists
"""
global _CURRENT_LAMBDA_CONTEXT
context = _CURRENT_LAMBDA_CONTEXT
if context is None:
return
try:
lambda_data = {
'lambda': {
'remaining_time_in_millis': context.get_remaining_time_in_millis(),
'function_name': context.function_name,
'function_version': context.function_version,
'arn': context.invoked_function_arn,
'request_id': context.aws_request_id,
}
}
if 'custom' in data:
data['custom'] = dict_merge(data['custom'], lambda_data)
else:
data['custom'] = lambda_data
except Exception as e:
log.exception("Exception while adding lambda context data: %r", e)
finally:
_CURRENT_LAMBDA_CONTEXT = None
|
def _add_lambda_context_data(data):
"""
Attempts to add information from the lambda context if it exists
"""
global _CURRENT_LAMBDA_CONTEXT
context = _CURRENT_LAMBDA_CONTEXT
if context is None:
return
try:
lambda_data = {
'lambda': {
'remaining_time_in_millis': context.get_remaining_time_in_millis(),
'function_name': context.function_name,
'function_version': context.function_version,
'arn': context.invoked_function_arn,
'request_id': context.aws_request_id,
}
}
if 'custom' in data:
data['custom'] = dict_merge(data['custom'], lambda_data)
else:
data['custom'] = lambda_data
except Exception as e:
log.exception("Exception while adding lambda context data: %r", e)
finally:
_CURRENT_LAMBDA_CONTEXT = None
|
[
"Attempts",
"to",
"add",
"information",
"from",
"the",
"lambda",
"context",
"if",
"it",
"exists"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L987-L1012
|
[
"def",
"_add_lambda_context_data",
"(",
"data",
")",
":",
"global",
"_CURRENT_LAMBDA_CONTEXT",
"context",
"=",
"_CURRENT_LAMBDA_CONTEXT",
"if",
"context",
"is",
"None",
":",
"return",
"try",
":",
"lambda_data",
"=",
"{",
"'lambda'",
":",
"{",
"'remaining_time_in_millis'",
":",
"context",
".",
"get_remaining_time_in_millis",
"(",
")",
",",
"'function_name'",
":",
"context",
".",
"function_name",
",",
"'function_version'",
":",
"context",
".",
"function_version",
",",
"'arn'",
":",
"context",
".",
"invoked_function_arn",
",",
"'request_id'",
":",
"context",
".",
"aws_request_id",
",",
"}",
"}",
"if",
"'custom'",
"in",
"data",
":",
"data",
"[",
"'custom'",
"]",
"=",
"dict_merge",
"(",
"data",
"[",
"'custom'",
"]",
",",
"lambda_data",
")",
"else",
":",
"data",
"[",
"'custom'",
"]",
"=",
"lambda_data",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"\"Exception while adding lambda context data: %r\"",
",",
"e",
")",
"finally",
":",
"_CURRENT_LAMBDA_CONTEXT",
"=",
"None"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_add_request_data
|
Attempts to build request data; if successful, sets the 'request' key on `data`.
|
rollbar/__init__.py
|
def _add_request_data(data, request):
"""
Attempts to build request data; if successful, sets the 'request' key on `data`.
"""
try:
request_data = _build_request_data(request)
except Exception as e:
log.exception("Exception while building request_data for Rollbar payload: %r", e)
else:
if request_data:
_filter_ip(request_data, SETTINGS['capture_ip'])
data['request'] = request_data
|
def _add_request_data(data, request):
"""
Attempts to build request data; if successful, sets the 'request' key on `data`.
"""
try:
request_data = _build_request_data(request)
except Exception as e:
log.exception("Exception while building request_data for Rollbar payload: %r", e)
else:
if request_data:
_filter_ip(request_data, SETTINGS['capture_ip'])
data['request'] = request_data
|
[
"Attempts",
"to",
"build",
"request",
"data",
";",
"if",
"successful",
"sets",
"the",
"request",
"key",
"on",
"data",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L1015-L1026
|
[
"def",
"_add_request_data",
"(",
"data",
",",
"request",
")",
":",
"try",
":",
"request_data",
"=",
"_build_request_data",
"(",
"request",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"\"Exception while building request_data for Rollbar payload: %r\"",
",",
"e",
")",
"else",
":",
"if",
"request_data",
":",
"_filter_ip",
"(",
"request_data",
",",
"SETTINGS",
"[",
"'capture_ip'",
"]",
")",
"data",
"[",
"'request'",
"]",
"=",
"request_data"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_check_add_locals
|
Returns True if we should record local variables for the given frame.
|
rollbar/__init__.py
|
def _check_add_locals(frame, frame_num, total_frames):
"""
Returns True if we should record local variables for the given frame.
"""
# Include the last frames locals
# Include any frame locals that came from a file in the project's root
return any(((frame_num == total_frames - 1),
('root' in SETTINGS and (frame.get('filename') or '').lower().startswith((SETTINGS['root'] or '').lower()))))
|
def _check_add_locals(frame, frame_num, total_frames):
"""
Returns True if we should record local variables for the given frame.
"""
# Include the last frames locals
# Include any frame locals that came from a file in the project's root
return any(((frame_num == total_frames - 1),
('root' in SETTINGS and (frame.get('filename') or '').lower().startswith((SETTINGS['root'] or '').lower()))))
|
[
"Returns",
"True",
"if",
"we",
"should",
"record",
"local",
"variables",
"for",
"the",
"given",
"frame",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L1029-L1036
|
[
"def",
"_check_add_locals",
"(",
"frame",
",",
"frame_num",
",",
"total_frames",
")",
":",
"# Include the last frames locals",
"# Include any frame locals that came from a file in the project's root",
"return",
"any",
"(",
"(",
"(",
"frame_num",
"==",
"total_frames",
"-",
"1",
")",
",",
"(",
"'root'",
"in",
"SETTINGS",
"and",
"(",
"frame",
".",
"get",
"(",
"'filename'",
")",
"or",
"''",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"(",
"SETTINGS",
"[",
"'root'",
"]",
"or",
"''",
")",
".",
"lower",
"(",
")",
")",
")",
")",
")"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_build_request_data
|
Returns a dictionary containing data from the request.
Can handle webob or werkzeug-based request objects.
|
rollbar/__init__.py
|
def _build_request_data(request):
"""
Returns a dictionary containing data from the request.
Can handle webob or werkzeug-based request objects.
"""
# webob (pyramid)
if WebobBaseRequest and isinstance(request, WebobBaseRequest):
return _build_webob_request_data(request)
# django
if DjangoHttpRequest and isinstance(request, DjangoHttpRequest):
return _build_django_request_data(request)
# django rest framework
if RestFrameworkRequest and isinstance(request, RestFrameworkRequest):
return _build_django_request_data(request)
# werkzeug (flask)
if WerkzeugRequest and isinstance(request, WerkzeugRequest):
return _build_werkzeug_request_data(request)
# tornado
if TornadoRequest and isinstance(request, TornadoRequest):
return _build_tornado_request_data(request)
# bottle
if BottleRequest and isinstance(request, BottleRequest):
return _build_bottle_request_data(request)
# Sanic
if SanicRequest and isinstance(request, SanicRequest):
return _build_sanic_request_data(request)
# falcon
if FalconRequest and isinstance(request, FalconRequest):
return _build_falcon_request_data(request)
# Plain wsgi (should be last)
if isinstance(request, dict) and 'wsgi.version' in request:
return _build_wsgi_request_data(request)
return None
|
def _build_request_data(request):
"""
Returns a dictionary containing data from the request.
Can handle webob or werkzeug-based request objects.
"""
# webob (pyramid)
if WebobBaseRequest and isinstance(request, WebobBaseRequest):
return _build_webob_request_data(request)
# django
if DjangoHttpRequest and isinstance(request, DjangoHttpRequest):
return _build_django_request_data(request)
# django rest framework
if RestFrameworkRequest and isinstance(request, RestFrameworkRequest):
return _build_django_request_data(request)
# werkzeug (flask)
if WerkzeugRequest and isinstance(request, WerkzeugRequest):
return _build_werkzeug_request_data(request)
# tornado
if TornadoRequest and isinstance(request, TornadoRequest):
return _build_tornado_request_data(request)
# bottle
if BottleRequest and isinstance(request, BottleRequest):
return _build_bottle_request_data(request)
# Sanic
if SanicRequest and isinstance(request, SanicRequest):
return _build_sanic_request_data(request)
# falcon
if FalconRequest and isinstance(request, FalconRequest):
return _build_falcon_request_data(request)
# Plain wsgi (should be last)
if isinstance(request, dict) and 'wsgi.version' in request:
return _build_wsgi_request_data(request)
return None
|
[
"Returns",
"a",
"dictionary",
"containing",
"data",
"from",
"the",
"request",
".",
"Can",
"handle",
"webob",
"or",
"werkzeug",
"-",
"based",
"request",
"objects",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L1049-L1091
|
[
"def",
"_build_request_data",
"(",
"request",
")",
":",
"# webob (pyramid)",
"if",
"WebobBaseRequest",
"and",
"isinstance",
"(",
"request",
",",
"WebobBaseRequest",
")",
":",
"return",
"_build_webob_request_data",
"(",
"request",
")",
"# django",
"if",
"DjangoHttpRequest",
"and",
"isinstance",
"(",
"request",
",",
"DjangoHttpRequest",
")",
":",
"return",
"_build_django_request_data",
"(",
"request",
")",
"# django rest framework",
"if",
"RestFrameworkRequest",
"and",
"isinstance",
"(",
"request",
",",
"RestFrameworkRequest",
")",
":",
"return",
"_build_django_request_data",
"(",
"request",
")",
"# werkzeug (flask)",
"if",
"WerkzeugRequest",
"and",
"isinstance",
"(",
"request",
",",
"WerkzeugRequest",
")",
":",
"return",
"_build_werkzeug_request_data",
"(",
"request",
")",
"# tornado",
"if",
"TornadoRequest",
"and",
"isinstance",
"(",
"request",
",",
"TornadoRequest",
")",
":",
"return",
"_build_tornado_request_data",
"(",
"request",
")",
"# bottle",
"if",
"BottleRequest",
"and",
"isinstance",
"(",
"request",
",",
"BottleRequest",
")",
":",
"return",
"_build_bottle_request_data",
"(",
"request",
")",
"# Sanic",
"if",
"SanicRequest",
"and",
"isinstance",
"(",
"request",
",",
"SanicRequest",
")",
":",
"return",
"_build_sanic_request_data",
"(",
"request",
")",
"# falcon",
"if",
"FalconRequest",
"and",
"isinstance",
"(",
"request",
",",
"FalconRequest",
")",
":",
"return",
"_build_falcon_request_data",
"(",
"request",
")",
"# Plain wsgi (should be last)",
"if",
"isinstance",
"(",
"request",
",",
"dict",
")",
"and",
"'wsgi.version'",
"in",
"request",
":",
"return",
"_build_wsgi_request_data",
"(",
"request",
")",
"return",
"None"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_build_server_data
|
Returns a dictionary containing information about the server environment.
|
rollbar/__init__.py
|
def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'pid': os.getpid()
}
# argv does not always exist in embedded python environments
argv = getattr(sys, 'argv', None)
if argv:
server_data['argv'] = argv
for key in ['branch', 'root']:
if SETTINGS.get(key):
server_data[key] = SETTINGS[key]
return server_data
|
def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'pid': os.getpid()
}
# argv does not always exist in embedded python environments
argv = getattr(sys, 'argv', None)
if argv:
server_data['argv'] = argv
for key in ['branch', 'root']:
if SETTINGS.get(key):
server_data[key] = SETTINGS[key]
return server_data
|
[
"Returns",
"a",
"dictionary",
"containing",
"information",
"about",
"the",
"server",
"environment",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L1299-L1318
|
[
"def",
"_build_server_data",
"(",
")",
":",
"# server environment",
"server_data",
"=",
"{",
"'host'",
":",
"socket",
".",
"gethostname",
"(",
")",
",",
"'pid'",
":",
"os",
".",
"getpid",
"(",
")",
"}",
"# argv does not always exist in embedded python environments",
"argv",
"=",
"getattr",
"(",
"sys",
",",
"'argv'",
",",
"None",
")",
"if",
"argv",
":",
"server_data",
"[",
"'argv'",
"]",
"=",
"argv",
"for",
"key",
"in",
"[",
"'branch'",
",",
"'root'",
"]",
":",
"if",
"SETTINGS",
".",
"get",
"(",
"key",
")",
":",
"server_data",
"[",
"key",
"]",
"=",
"SETTINGS",
"[",
"key",
"]",
"return",
"server_data"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
_build_payload
|
Returns the full payload as a string.
|
rollbar/__init__.py
|
def _build_payload(data):
"""
Returns the full payload as a string.
"""
for k, v in iteritems(data):
data[k] = _transform(v, key=(k,))
payload = {
'access_token': SETTINGS['access_token'],
'data': data
}
return payload
|
def _build_payload(data):
"""
Returns the full payload as a string.
"""
for k, v in iteritems(data):
data[k] = _transform(v, key=(k,))
payload = {
'access_token': SETTINGS['access_token'],
'data': data
}
return payload
|
[
"Returns",
"the",
"full",
"payload",
"as",
"a",
"string",
"."
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L1328-L1341
|
[
"def",
"_build_payload",
"(",
"data",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"data",
")",
":",
"data",
"[",
"k",
"]",
"=",
"_transform",
"(",
"v",
",",
"key",
"=",
"(",
"k",
",",
")",
")",
"payload",
"=",
"{",
"'access_token'",
":",
"SETTINGS",
"[",
"'access_token'",
"]",
",",
"'data'",
":",
"data",
"}",
"return",
"payload"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
main
|
This runs the protocol on port 8000
|
rollbar/examples/twisted/simpleserv.py
|
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run()
|
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run()
|
[
"This",
"runs",
"the",
"protocol",
"on",
"port",
"8000"
] |
rollbar/pyrollbar
|
python
|
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/examples/twisted/simpleserv.py#L36-L43
|
[
"def",
"main",
"(",
")",
":",
"rollbar",
".",
"init",
"(",
"'ACCESS_TOKEN'",
",",
"environment",
"=",
"'test'",
",",
"handler",
"=",
"'twisted'",
")",
"factory",
"=",
"protocol",
".",
"ServerFactory",
"(",
")",
"factory",
".",
"protocol",
"=",
"Echo",
"reactor",
".",
"listenTCP",
"(",
"8000",
",",
"factory",
")",
"reactor",
".",
"run",
"(",
")"
] |
33ef2e723a33d09dd6302f978f4a3908be95b9d2
|
test
|
compose
|
This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung.
|
hgtk/letter.py
|
def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None: jongsung = u''
try:
chosung_index = CHO.index(chosung)
joongsung_index = JOONG.index(joongsung)
jongsung_index = JONG.index(jongsung)
except Exception:
raise NotHangulException('No valid Hangul character index')
return unichr(0xAC00 + chosung_index * NUM_JOONG * NUM_JONG + joongsung_index * NUM_JONG + jongsung_index)
|
def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None: jongsung = u''
try:
chosung_index = CHO.index(chosung)
joongsung_index = JOONG.index(joongsung)
jongsung_index = JONG.index(jongsung)
except Exception:
raise NotHangulException('No valid Hangul character index')
return unichr(0xAC00 + chosung_index * NUM_JOONG * NUM_JONG + joongsung_index * NUM_JONG + jongsung_index)
|
[
"This",
"function",
"returns",
"a",
"Hangul",
"letter",
"by",
"composing",
"the",
"specified",
"chosung",
"joongsung",
"and",
"jongsung",
"."
] |
bluedisk/hangul-toolkit
|
python
|
https://github.com/bluedisk/hangul-toolkit/blob/f36b534ee339263fb72e687b732697cc7ed290dc/hgtk/letter.py#L17-L32
|
[
"def",
"compose",
"(",
"chosung",
",",
"joongsung",
",",
"jongsung",
"=",
"u''",
")",
":",
"if",
"jongsung",
"is",
"None",
":",
"jongsung",
"=",
"u''",
"try",
":",
"chosung_index",
"=",
"CHO",
".",
"index",
"(",
"chosung",
")",
"joongsung_index",
"=",
"JOONG",
".",
"index",
"(",
"joongsung",
")",
"jongsung_index",
"=",
"JONG",
".",
"index",
"(",
"jongsung",
")",
"except",
"Exception",
":",
"raise",
"NotHangulException",
"(",
"'No valid Hangul character index'",
")",
"return",
"unichr",
"(",
"0xAC00",
"+",
"chosung_index",
"*",
"NUM_JOONG",
"*",
"NUM_JONG",
"+",
"joongsung_index",
"*",
"NUM_JONG",
"+",
"jongsung_index",
")"
] |
f36b534ee339263fb72e687b732697cc7ed290dc
|
test
|
decompose
|
This function returns letters by decomposing the specified Hangul letter.
|
hgtk/letter.py
|
def decompose(hangul_letter):
"""This function returns letters by decomposing the specified Hangul letter."""
from . import checker
if len(hangul_letter) < 1:
raise NotLetterException('')
elif not checker.is_hangul(hangul_letter):
raise NotHangulException('')
if hangul_letter in CHO:
return hangul_letter, '', ''
if hangul_letter in JOONG:
return '', hangul_letter, ''
if hangul_letter in JONG:
return '', '', hangul_letter
code = hangul_index(hangul_letter)
cho, joong, jong = decompose_index(code)
if cho < 0:
cho = 0
try:
return CHO[cho], JOONG[joong], JONG[jong]
except:
print("%d / %d / %d"%(cho, joong, jong))
print("%s / %s " %( JOONG[joong].encode("utf8"), JONG[jong].encode('utf8')))
raise Exception()
|
def decompose(hangul_letter):
"""This function returns letters by decomposing the specified Hangul letter."""
from . import checker
if len(hangul_letter) < 1:
raise NotLetterException('')
elif not checker.is_hangul(hangul_letter):
raise NotHangulException('')
if hangul_letter in CHO:
return hangul_letter, '', ''
if hangul_letter in JOONG:
return '', hangul_letter, ''
if hangul_letter in JONG:
return '', '', hangul_letter
code = hangul_index(hangul_letter)
cho, joong, jong = decompose_index(code)
if cho < 0:
cho = 0
try:
return CHO[cho], JOONG[joong], JONG[jong]
except:
print("%d / %d / %d"%(cho, joong, jong))
print("%s / %s " %( JOONG[joong].encode("utf8"), JONG[jong].encode('utf8')))
raise Exception()
|
[
"This",
"function",
"returns",
"letters",
"by",
"decomposing",
"the",
"specified",
"Hangul",
"letter",
"."
] |
bluedisk/hangul-toolkit
|
python
|
https://github.com/bluedisk/hangul-toolkit/blob/f36b534ee339263fb72e687b732697cc7ed290dc/hgtk/letter.py#L49-L79
|
[
"def",
"decompose",
"(",
"hangul_letter",
")",
":",
"from",
".",
"import",
"checker",
"if",
"len",
"(",
"hangul_letter",
")",
"<",
"1",
":",
"raise",
"NotLetterException",
"(",
"''",
")",
"elif",
"not",
"checker",
".",
"is_hangul",
"(",
"hangul_letter",
")",
":",
"raise",
"NotHangulException",
"(",
"''",
")",
"if",
"hangul_letter",
"in",
"CHO",
":",
"return",
"hangul_letter",
",",
"''",
",",
"''",
"if",
"hangul_letter",
"in",
"JOONG",
":",
"return",
"''",
",",
"hangul_letter",
",",
"''",
"if",
"hangul_letter",
"in",
"JONG",
":",
"return",
"''",
",",
"''",
",",
"hangul_letter",
"code",
"=",
"hangul_index",
"(",
"hangul_letter",
")",
"cho",
",",
"joong",
",",
"jong",
"=",
"decompose_index",
"(",
"code",
")",
"if",
"cho",
"<",
"0",
":",
"cho",
"=",
"0",
"try",
":",
"return",
"CHO",
"[",
"cho",
"]",
",",
"JOONG",
"[",
"joong",
"]",
",",
"JONG",
"[",
"jong",
"]",
"except",
":",
"print",
"(",
"\"%d / %d / %d\"",
"%",
"(",
"cho",
",",
"joong",
",",
"jong",
")",
")",
"print",
"(",
"\"%s / %s \"",
"%",
"(",
"JOONG",
"[",
"joong",
"]",
".",
"encode",
"(",
"\"utf8\"",
")",
",",
"JONG",
"[",
"jong",
"]",
".",
"encode",
"(",
"'utf8'",
")",
")",
")",
"raise",
"Exception",
"(",
")"
] |
f36b534ee339263fb72e687b732697cc7ed290dc
|
test
|
has_jongsung
|
Check whether this letter contains Jongsung
|
hgtk/checker.py
|
def has_jongsung(letter):
"""Check whether this letter contains Jongsung"""
if len(letter) != 1:
raise Exception('The target string must be one letter.')
if not is_hangul(letter):
raise NotHangulException('The target string must be Hangul')
code = lt.hangul_index(letter)
return code % NUM_JONG > 0
|
def has_jongsung(letter):
"""Check whether this letter contains Jongsung"""
if len(letter) != 1:
raise Exception('The target string must be one letter.')
if not is_hangul(letter):
raise NotHangulException('The target string must be Hangul')
code = lt.hangul_index(letter)
return code % NUM_JONG > 0
|
[
"Check",
"whether",
"this",
"letter",
"contains",
"Jongsung"
] |
bluedisk/hangul-toolkit
|
python
|
https://github.com/bluedisk/hangul-toolkit/blob/f36b534ee339263fb72e687b732697cc7ed290dc/hgtk/checker.py#L56-L64
|
[
"def",
"has_jongsung",
"(",
"letter",
")",
":",
"if",
"len",
"(",
"letter",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"'The target string must be one letter.'",
")",
"if",
"not",
"is_hangul",
"(",
"letter",
")",
":",
"raise",
"NotHangulException",
"(",
"'The target string must be Hangul'",
")",
"code",
"=",
"lt",
".",
"hangul_index",
"(",
"letter",
")",
"return",
"code",
"%",
"NUM_JONG",
">",
"0"
] |
f36b534ee339263fb72e687b732697cc7ed290dc
|
test
|
attach
|
add josa at the end of this word
|
hgtk/josa.py
|
def attach(word, josa=EUN_NEUN):
"""add josa at the end of this word"""
last_letter = word.strip()[-1]
try:
_, _, letter_jong = letter.decompose(last_letter)
except NotHangulException:
letter_jong = letter.get_substituent_of(last_letter)
if letter_jong in ('', josa['except']):
return word + josa['has']
return word + josa['not']
|
def attach(word, josa=EUN_NEUN):
"""add josa at the end of this word"""
last_letter = word.strip()[-1]
try:
_, _, letter_jong = letter.decompose(last_letter)
except NotHangulException:
letter_jong = letter.get_substituent_of(last_letter)
if letter_jong in ('', josa['except']):
return word + josa['has']
return word + josa['not']
|
[
"add",
"josa",
"at",
"the",
"end",
"of",
"this",
"word"
] |
bluedisk/hangul-toolkit
|
python
|
https://github.com/bluedisk/hangul-toolkit/blob/f36b534ee339263fb72e687b732697cc7ed290dc/hgtk/josa.py#L34-L45
|
[
"def",
"attach",
"(",
"word",
",",
"josa",
"=",
"EUN_NEUN",
")",
":",
"last_letter",
"=",
"word",
".",
"strip",
"(",
")",
"[",
"-",
"1",
"]",
"try",
":",
"_",
",",
"_",
",",
"letter_jong",
"=",
"letter",
".",
"decompose",
"(",
"last_letter",
")",
"except",
"NotHangulException",
":",
"letter_jong",
"=",
"letter",
".",
"get_substituent_of",
"(",
"last_letter",
")",
"if",
"letter_jong",
"in",
"(",
"''",
",",
"josa",
"[",
"'except'",
"]",
")",
":",
"return",
"word",
"+",
"josa",
"[",
"'has'",
"]",
"return",
"word",
"+",
"josa",
"[",
"'not'",
"]"
] |
f36b534ee339263fb72e687b732697cc7ed290dc
|
test
|
is_inside_except
|
Returns true if node is inside the name of an except handler.
|
pylint/checkers/utils.py
|
def is_inside_except(node):
"""Returns true if node is inside the name of an except handler."""
current = node
while current and not isinstance(current.parent, astroid.ExceptHandler):
current = current.parent
return current and current is current.parent.name
|
def is_inside_except(node):
"""Returns true if node is inside the name of an except handler."""
current = node
while current and not isinstance(current.parent, astroid.ExceptHandler):
current = current.parent
return current and current is current.parent.name
|
[
"Returns",
"true",
"if",
"node",
"is",
"inside",
"the",
"name",
"of",
"an",
"except",
"handler",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L209-L215
|
[
"def",
"is_inside_except",
"(",
"node",
")",
":",
"current",
"=",
"node",
"while",
"current",
"and",
"not",
"isinstance",
"(",
"current",
".",
"parent",
",",
"astroid",
".",
"ExceptHandler",
")",
":",
"current",
"=",
"current",
".",
"parent",
"return",
"current",
"and",
"current",
"is",
"current",
".",
"parent",
".",
"name"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_inside_lambda
|
Return true if given node is inside lambda
|
pylint/checkers/utils.py
|
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:
"""Return true if given node is inside lambda"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Lambda):
return True
parent = parent.parent
return False
|
def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:
"""Return true if given node is inside lambda"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Lambda):
return True
parent = parent.parent
return False
|
[
"Return",
"true",
"if",
"given",
"node",
"is",
"inside",
"lambda"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L218-L225
|
[
"def",
"is_inside_lambda",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"parent",
"=",
"node",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"parent",
",",
"astroid",
".",
"Lambda",
")",
":",
"return",
"True",
"parent",
"=",
"parent",
".",
"parent",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_all_elements
|
Recursively returns all atoms in nested lists and tuples.
|
pylint/checkers/utils.py
|
def get_all_elements(
node: astroid.node_classes.NodeNG
) -> Iterable[astroid.node_classes.NodeNG]:
"""Recursively returns all atoms in nested lists and tuples."""
if isinstance(node, (astroid.Tuple, astroid.List)):
for child in node.elts:
for e in get_all_elements(child):
yield e
else:
yield node
|
def get_all_elements(
node: astroid.node_classes.NodeNG
) -> Iterable[astroid.node_classes.NodeNG]:
"""Recursively returns all atoms in nested lists and tuples."""
if isinstance(node, (astroid.Tuple, astroid.List)):
for child in node.elts:
for e in get_all_elements(child):
yield e
else:
yield node
|
[
"Recursively",
"returns",
"all",
"atoms",
"in",
"nested",
"lists",
"and",
"tuples",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L228-L237
|
[
"def",
"get_all_elements",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Iterable",
"[",
"astroid",
".",
"node_classes",
".",
"NodeNG",
"]",
":",
"if",
"isinstance",
"(",
"node",
",",
"(",
"astroid",
".",
"Tuple",
",",
"astroid",
".",
"List",
")",
")",
":",
"for",
"child",
"in",
"node",
".",
"elts",
":",
"for",
"e",
"in",
"get_all_elements",
"(",
"child",
")",
":",
"yield",
"e",
"else",
":",
"yield",
"node"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
clobber_in_except
|
Checks if an assignment node in an except handler clobbers an existing
variable.
Returns (True, args for W0623) if assignment clobbers an existing variable,
(False, None) otherwise.
|
pylint/checkers/utils.py
|
def clobber_in_except(
node: astroid.node_classes.NodeNG
) -> Tuple[bool, Tuple[str, str]]:
"""Checks if an assignment node in an except handler clobbers an existing
variable.
Returns (True, args for W0623) if assignment clobbers an existing variable,
(False, None) otherwise.
"""
if isinstance(node, astroid.AssignAttr):
return True, (node.attrname, "object %r" % (node.expr.as_string(),))
if isinstance(node, astroid.AssignName):
name = node.name
if is_builtin(name):
return (True, (name, "builtins"))
stmts = node.lookup(name)[1]
if stmts and not isinstance(
stmts[0].assign_type(),
(astroid.Assign, astroid.AugAssign, astroid.ExceptHandler),
):
return True, (name, "outer scope (line %s)" % stmts[0].fromlineno)
return False, None
|
def clobber_in_except(
node: astroid.node_classes.NodeNG
) -> Tuple[bool, Tuple[str, str]]:
"""Checks if an assignment node in an except handler clobbers an existing
variable.
Returns (True, args for W0623) if assignment clobbers an existing variable,
(False, None) otherwise.
"""
if isinstance(node, astroid.AssignAttr):
return True, (node.attrname, "object %r" % (node.expr.as_string(),))
if isinstance(node, astroid.AssignName):
name = node.name
if is_builtin(name):
return (True, (name, "builtins"))
stmts = node.lookup(name)[1]
if stmts and not isinstance(
stmts[0].assign_type(),
(astroid.Assign, astroid.AugAssign, astroid.ExceptHandler),
):
return True, (name, "outer scope (line %s)" % stmts[0].fromlineno)
return False, None
|
[
"Checks",
"if",
"an",
"assignment",
"node",
"in",
"an",
"except",
"handler",
"clobbers",
"an",
"existing",
"variable",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L240-L262
|
[
"def",
"clobber_in_except",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Tuple",
"[",
"bool",
",",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"AssignAttr",
")",
":",
"return",
"True",
",",
"(",
"node",
".",
"attrname",
",",
"\"object %r\"",
"%",
"(",
"node",
".",
"expr",
".",
"as_string",
"(",
")",
",",
")",
")",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"AssignName",
")",
":",
"name",
"=",
"node",
".",
"name",
"if",
"is_builtin",
"(",
"name",
")",
":",
"return",
"(",
"True",
",",
"(",
"name",
",",
"\"builtins\"",
")",
")",
"stmts",
"=",
"node",
".",
"lookup",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"stmts",
"and",
"not",
"isinstance",
"(",
"stmts",
"[",
"0",
"]",
".",
"assign_type",
"(",
")",
",",
"(",
"astroid",
".",
"Assign",
",",
"astroid",
".",
"AugAssign",
",",
"astroid",
".",
"ExceptHandler",
")",
",",
")",
":",
"return",
"True",
",",
"(",
"name",
",",
"\"outer scope (line %s)\"",
"%",
"stmts",
"[",
"0",
"]",
".",
"fromlineno",
")",
"return",
"False",
",",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_super
|
return True if the node is referencing the "super" builtin function
|
pylint/checkers/utils.py
|
def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" builtin function
"""
if getattr(node, "name", None) == "super" and node.root().name == BUILTINS_NAME:
return True
return False
|
def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" builtin function
"""
if getattr(node, "name", None) == "super" and node.root().name == BUILTINS_NAME:
return True
return False
|
[
"return",
"True",
"if",
"the",
"node",
"is",
"referencing",
"the",
"super",
"builtin",
"function"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L265-L270
|
[
"def",
"is_super",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"if",
"getattr",
"(",
"node",
",",
"\"name\"",
",",
"None",
")",
"==",
"\"super\"",
"and",
"node",
".",
"root",
"(",
")",
".",
"name",
"==",
"BUILTINS_NAME",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_error
|
return true if the function does nothing but raising an exception
|
pylint/checkers/utils.py
|
def is_error(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the function does nothing but raising an exception"""
for child_node in node.get_children():
if isinstance(child_node, astroid.Raise):
return True
return False
|
def is_error(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the function does nothing but raising an exception"""
for child_node in node.get_children():
if isinstance(child_node, astroid.Raise):
return True
return False
|
[
"return",
"true",
"if",
"the",
"function",
"does",
"nothing",
"but",
"raising",
"an",
"exception"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L273-L278
|
[
"def",
"is_error",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"for",
"child_node",
"in",
"node",
".",
"get_children",
"(",
")",
":",
"if",
"isinstance",
"(",
"child_node",
",",
"astroid",
".",
"Raise",
")",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_builtin_object
|
Returns True if the given node is an object from the __builtin__ module.
|
pylint/checkers/utils.py
|
def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:
"""Returns True if the given node is an object from the __builtin__ module."""
return node and node.root().name == BUILTINS_NAME
|
def is_builtin_object(node: astroid.node_classes.NodeNG) -> bool:
"""Returns True if the given node is an object from the __builtin__ module."""
return node and node.root().name == BUILTINS_NAME
|
[
"Returns",
"True",
"if",
"the",
"given",
"node",
"is",
"an",
"object",
"from",
"the",
"__builtin__",
"module",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L285-L287
|
[
"def",
"is_builtin_object",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"return",
"node",
"and",
"node",
".",
"root",
"(",
")",
".",
"name",
"==",
"BUILTINS_NAME"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_defined_before
|
return True if the variable node is defined by a parent node (list,
set, dict, or generator comprehension, lambda) or in a previous sibling
node on the same line (statement_defining ; statement_using)
|
pylint/checkers/utils.py
|
def is_defined_before(var_node: astroid.node_classes.NodeNG) -> bool:
"""return True if the variable node is defined by a parent node (list,
set, dict, or generator comprehension, lambda) or in a previous sibling
node on the same line (statement_defining ; statement_using)
"""
varname = var_node.name
_node = var_node.parent
while _node:
if is_defined_in_scope(var_node, varname, _node):
return True
_node = _node.parent
# possibly multiple statements on the same line using semi colon separator
stmt = var_node.statement()
_node = stmt.previous_sibling()
lineno = stmt.fromlineno
while _node and _node.fromlineno == lineno:
for assign_node in _node.nodes_of_class(astroid.AssignName):
if assign_node.name == varname:
return True
for imp_node in _node.nodes_of_class((astroid.ImportFrom, astroid.Import)):
if varname in [name[1] or name[0] for name in imp_node.names]:
return True
_node = _node.previous_sibling()
return False
|
def is_defined_before(var_node: astroid.node_classes.NodeNG) -> bool:
"""return True if the variable node is defined by a parent node (list,
set, dict, or generator comprehension, lambda) or in a previous sibling
node on the same line (statement_defining ; statement_using)
"""
varname = var_node.name
_node = var_node.parent
while _node:
if is_defined_in_scope(var_node, varname, _node):
return True
_node = _node.parent
# possibly multiple statements on the same line using semi colon separator
stmt = var_node.statement()
_node = stmt.previous_sibling()
lineno = stmt.fromlineno
while _node and _node.fromlineno == lineno:
for assign_node in _node.nodes_of_class(astroid.AssignName):
if assign_node.name == varname:
return True
for imp_node in _node.nodes_of_class((astroid.ImportFrom, astroid.Import)):
if varname in [name[1] or name[0] for name in imp_node.names]:
return True
_node = _node.previous_sibling()
return False
|
[
"return",
"True",
"if",
"the",
"variable",
"node",
"is",
"defined",
"by",
"a",
"parent",
"node",
"(",
"list",
"set",
"dict",
"or",
"generator",
"comprehension",
"lambda",
")",
"or",
"in",
"a",
"previous",
"sibling",
"node",
"on",
"the",
"same",
"line",
"(",
"statement_defining",
";",
"statement_using",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L344-L367
|
[
"def",
"is_defined_before",
"(",
"var_node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"varname",
"=",
"var_node",
".",
"name",
"_node",
"=",
"var_node",
".",
"parent",
"while",
"_node",
":",
"if",
"is_defined_in_scope",
"(",
"var_node",
",",
"varname",
",",
"_node",
")",
":",
"return",
"True",
"_node",
"=",
"_node",
".",
"parent",
"# possibly multiple statements on the same line using semi colon separator",
"stmt",
"=",
"var_node",
".",
"statement",
"(",
")",
"_node",
"=",
"stmt",
".",
"previous_sibling",
"(",
")",
"lineno",
"=",
"stmt",
".",
"fromlineno",
"while",
"_node",
"and",
"_node",
".",
"fromlineno",
"==",
"lineno",
":",
"for",
"assign_node",
"in",
"_node",
".",
"nodes_of_class",
"(",
"astroid",
".",
"AssignName",
")",
":",
"if",
"assign_node",
".",
"name",
"==",
"varname",
":",
"return",
"True",
"for",
"imp_node",
"in",
"_node",
".",
"nodes_of_class",
"(",
"(",
"astroid",
".",
"ImportFrom",
",",
"astroid",
".",
"Import",
")",
")",
":",
"if",
"varname",
"in",
"[",
"name",
"[",
"1",
"]",
"or",
"name",
"[",
"0",
"]",
"for",
"name",
"in",
"imp_node",
".",
"names",
"]",
":",
"return",
"True",
"_node",
"=",
"_node",
".",
"previous_sibling",
"(",
")",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_default_argument
|
return true if the given Name node is used in function or lambda
default argument's value
|
pylint/checkers/utils.py
|
def is_default_argument(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the given Name node is used in function or lambda
default argument's value
"""
parent = node.scope()
if isinstance(parent, (astroid.FunctionDef, astroid.Lambda)):
for default_node in parent.args.defaults:
for default_name_node in default_node.nodes_of_class(astroid.Name):
if default_name_node is node:
return True
return False
|
def is_default_argument(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the given Name node is used in function or lambda
default argument's value
"""
parent = node.scope()
if isinstance(parent, (astroid.FunctionDef, astroid.Lambda)):
for default_node in parent.args.defaults:
for default_name_node in default_node.nodes_of_class(astroid.Name):
if default_name_node is node:
return True
return False
|
[
"return",
"true",
"if",
"the",
"given",
"Name",
"node",
"is",
"used",
"in",
"function",
"or",
"lambda",
"default",
"argument",
"s",
"value"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L370-L380
|
[
"def",
"is_default_argument",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"parent",
"=",
"node",
".",
"scope",
"(",
")",
"if",
"isinstance",
"(",
"parent",
",",
"(",
"astroid",
".",
"FunctionDef",
",",
"astroid",
".",
"Lambda",
")",
")",
":",
"for",
"default_node",
"in",
"parent",
".",
"args",
".",
"defaults",
":",
"for",
"default_name_node",
"in",
"default_node",
".",
"nodes_of_class",
"(",
"astroid",
".",
"Name",
")",
":",
"if",
"default_name_node",
"is",
"node",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_func_decorator
|
return true if the name is used in function decorator
|
pylint/checkers/utils.py
|
def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the name is used in function decorator"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Decorators):
return True
if parent.is_statement or isinstance(
parent,
(astroid.Lambda, scoped_nodes.ComprehensionScope, scoped_nodes.ListComp),
):
break
parent = parent.parent
return False
|
def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the name is used in function decorator"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Decorators):
return True
if parent.is_statement or isinstance(
parent,
(astroid.Lambda, scoped_nodes.ComprehensionScope, scoped_nodes.ListComp),
):
break
parent = parent.parent
return False
|
[
"return",
"true",
"if",
"the",
"name",
"is",
"used",
"in",
"function",
"decorator"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L383-L395
|
[
"def",
"is_func_decorator",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"parent",
"=",
"node",
".",
"parent",
"while",
"parent",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"parent",
",",
"astroid",
".",
"Decorators",
")",
":",
"return",
"True",
"if",
"parent",
".",
"is_statement",
"or",
"isinstance",
"(",
"parent",
",",
"(",
"astroid",
".",
"Lambda",
",",
"scoped_nodes",
".",
"ComprehensionScope",
",",
"scoped_nodes",
".",
"ListComp",
")",
",",
")",
":",
"break",
"parent",
"=",
"parent",
".",
"parent",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_ancestor_name
|
return True if `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute
|
pylint/checkers/utils.py
|
def is_ancestor_name(
frame: astroid.node_classes.NodeNG, node: astroid.node_classes.NodeNG
) -> bool:
"""return True if `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute
"""
try:
bases = frame.bases
except AttributeError:
return False
for base in bases:
if node in base.nodes_of_class(astroid.Name):
return True
return False
|
def is_ancestor_name(
frame: astroid.node_classes.NodeNG, node: astroid.node_classes.NodeNG
) -> bool:
"""return True if `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute
"""
try:
bases = frame.bases
except AttributeError:
return False
for base in bases:
if node in base.nodes_of_class(astroid.Name):
return True
return False
|
[
"return",
"True",
"if",
"frame",
"is",
"an",
"astroid",
".",
"Class",
"node",
"with",
"node",
"in",
"the",
"subtree",
"of",
"its",
"bases",
"attribute"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L398-L411
|
[
"def",
"is_ancestor_name",
"(",
"frame",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"try",
":",
"bases",
"=",
"frame",
".",
"bases",
"except",
"AttributeError",
":",
"return",
"False",
"for",
"base",
"in",
"bases",
":",
"if",
"node",
"in",
"base",
".",
"nodes_of_class",
"(",
"astroid",
".",
"Name",
")",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
assign_parent
|
return the higher parent which is not an AssignName, Tuple or List node
|
pylint/checkers/utils.py
|
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:
"""return the higher parent which is not an AssignName, Tuple or List node
"""
while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):
node = node.parent
return node
|
def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:
"""return the higher parent which is not an AssignName, Tuple or List node
"""
while node and isinstance(node, (astroid.AssignName, astroid.Tuple, astroid.List)):
node = node.parent
return node
|
[
"return",
"the",
"higher",
"parent",
"which",
"is",
"not",
"an",
"AssignName",
"Tuple",
"or",
"List",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L414-L419
|
[
"def",
"assign_parent",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"astroid",
".",
"node_classes",
".",
"NodeNG",
":",
"while",
"node",
"and",
"isinstance",
"(",
"node",
",",
"(",
"astroid",
".",
"AssignName",
",",
"astroid",
".",
"Tuple",
",",
"astroid",
".",
"List",
")",
")",
":",
"node",
"=",
"node",
".",
"parent",
"return",
"node"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
overrides_a_method
|
return True if <name> is a method overridden from an ancestor
|
pylint/checkers/utils.py
|
def overrides_a_method(class_node: astroid.node_classes.NodeNG, name: str) -> bool:
"""return True if <name> is a method overridden from an ancestor"""
for ancestor in class_node.ancestors():
if name in ancestor and isinstance(ancestor[name], astroid.FunctionDef):
return True
return False
|
def overrides_a_method(class_node: astroid.node_classes.NodeNG, name: str) -> bool:
"""return True if <name> is a method overridden from an ancestor"""
for ancestor in class_node.ancestors():
if name in ancestor and isinstance(ancestor[name], astroid.FunctionDef):
return True
return False
|
[
"return",
"True",
"if",
"<name",
">",
"is",
"a",
"method",
"overridden",
"from",
"an",
"ancestor"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L422-L427
|
[
"def",
"overrides_a_method",
"(",
"class_node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"for",
"ancestor",
"in",
"class_node",
".",
"ancestors",
"(",
")",
":",
"if",
"name",
"in",
"ancestor",
"and",
"isinstance",
"(",
"ancestor",
"[",
"name",
"]",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
check_messages
|
decorator to store messages that are handled by a checker method
|
pylint/checkers/utils.py
|
def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages
|
def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages
|
[
"decorator",
"to",
"store",
"messages",
"that",
"are",
"handled",
"by",
"a",
"checker",
"method"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L430-L437
|
[
"def",
"check_messages",
"(",
"*",
"messages",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"store_messages",
"(",
"func",
")",
":",
"func",
".",
"checks_msgs",
"=",
"messages",
"return",
"func",
"return",
"store_messages"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
parse_format_string
|
Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
IncompleteFormatString or UnsupportedFormatCharacter if a
parse error occurs.
|
pylint/checkers/utils.py
|
def parse_format_string(
format_string: str
) -> Tuple[Set[str], int, Dict[str, str], List[str]]:
"""Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
IncompleteFormatString or UnsupportedFormatCharacter if a
parse error occurs."""
keys = set()
key_types = dict()
pos_types = []
num_args = 0
def next_char(i):
i += 1
if i == len(format_string):
raise IncompleteFormatString
return (i, format_string[i])
i = 0
while i < len(format_string):
char = format_string[i]
if char == "%":
i, char = next_char(i)
# Parse the mapping key (optional).
key = None
if char == "(":
depth = 1
i, char = next_char(i)
key_start = i
while depth != 0:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
i, char = next_char(i)
key_end = i - 1
key = format_string[key_start:key_end]
# Parse the conversion flags (optional).
while char in "#0- +":
i, char = next_char(i)
# Parse the minimum field width (optional).
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the precision (optional).
if char == ".":
i, char = next_char(i)
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the length modifier (optional).
if char in "hlL":
i, char = next_char(i)
# Parse the conversion type (mandatory).
if PY3K:
flags = "diouxXeEfFgGcrs%a"
else:
flags = "diouxXeEfFgGcrs%"
if char not in flags:
raise UnsupportedFormatCharacter(i)
if key:
keys.add(key)
key_types[key] = char
elif char != "%":
num_args += 1
pos_types.append(char)
i += 1
return keys, num_args, key_types, pos_types
|
def parse_format_string(
format_string: str
) -> Tuple[Set[str], int, Dict[str, str], List[str]]:
"""Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
IncompleteFormatString or UnsupportedFormatCharacter if a
parse error occurs."""
keys = set()
key_types = dict()
pos_types = []
num_args = 0
def next_char(i):
i += 1
if i == len(format_string):
raise IncompleteFormatString
return (i, format_string[i])
i = 0
while i < len(format_string):
char = format_string[i]
if char == "%":
i, char = next_char(i)
# Parse the mapping key (optional).
key = None
if char == "(":
depth = 1
i, char = next_char(i)
key_start = i
while depth != 0:
if char == "(":
depth += 1
elif char == ")":
depth -= 1
i, char = next_char(i)
key_end = i - 1
key = format_string[key_start:key_end]
# Parse the conversion flags (optional).
while char in "#0- +":
i, char = next_char(i)
# Parse the minimum field width (optional).
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the precision (optional).
if char == ".":
i, char = next_char(i)
if char == "*":
num_args += 1
i, char = next_char(i)
else:
while char in string.digits:
i, char = next_char(i)
# Parse the length modifier (optional).
if char in "hlL":
i, char = next_char(i)
# Parse the conversion type (mandatory).
if PY3K:
flags = "diouxXeEfFgGcrs%a"
else:
flags = "diouxXeEfFgGcrs%"
if char not in flags:
raise UnsupportedFormatCharacter(i)
if key:
keys.add(key)
key_types[key] = char
elif char != "%":
num_args += 1
pos_types.append(char)
i += 1
return keys, num_args, key_types, pos_types
|
[
"Parses",
"a",
"format",
"string",
"returning",
"a",
"tuple",
"of",
"(",
"keys",
"num_args",
")",
"where",
"keys",
"is",
"the",
"set",
"of",
"mapping",
"keys",
"in",
"the",
"format",
"string",
"and",
"num_args",
"is",
"the",
"number",
"of",
"arguments",
"required",
"by",
"the",
"format",
"string",
".",
"Raises",
"IncompleteFormatString",
"or",
"UnsupportedFormatCharacter",
"if",
"a",
"parse",
"error",
"occurs",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L453-L528
|
[
"def",
"parse_format_string",
"(",
"format_string",
":",
"str",
")",
"->",
"Tuple",
"[",
"Set",
"[",
"str",
"]",
",",
"int",
",",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"keys",
"=",
"set",
"(",
")",
"key_types",
"=",
"dict",
"(",
")",
"pos_types",
"=",
"[",
"]",
"num_args",
"=",
"0",
"def",
"next_char",
"(",
"i",
")",
":",
"i",
"+=",
"1",
"if",
"i",
"==",
"len",
"(",
"format_string",
")",
":",
"raise",
"IncompleteFormatString",
"return",
"(",
"i",
",",
"format_string",
"[",
"i",
"]",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"format_string",
")",
":",
"char",
"=",
"format_string",
"[",
"i",
"]",
"if",
"char",
"==",
"\"%\"",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"# Parse the mapping key (optional).",
"key",
"=",
"None",
"if",
"char",
"==",
"\"(\"",
":",
"depth",
"=",
"1",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"key_start",
"=",
"i",
"while",
"depth",
"!=",
"0",
":",
"if",
"char",
"==",
"\"(\"",
":",
"depth",
"+=",
"1",
"elif",
"char",
"==",
"\")\"",
":",
"depth",
"-=",
"1",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"key_end",
"=",
"i",
"-",
"1",
"key",
"=",
"format_string",
"[",
"key_start",
":",
"key_end",
"]",
"# Parse the conversion flags (optional).",
"while",
"char",
"in",
"\"#0- +\"",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"# Parse the minimum field width (optional).",
"if",
"char",
"==",
"\"*\"",
":",
"num_args",
"+=",
"1",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"else",
":",
"while",
"char",
"in",
"string",
".",
"digits",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"# Parse the precision (optional).",
"if",
"char",
"==",
"\".\"",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"if",
"char",
"==",
"\"*\"",
":",
"num_args",
"+=",
"1",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"else",
":",
"while",
"char",
"in",
"string",
".",
"digits",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"# Parse the length modifier (optional).",
"if",
"char",
"in",
"\"hlL\"",
":",
"i",
",",
"char",
"=",
"next_char",
"(",
"i",
")",
"# Parse the conversion type (mandatory).",
"if",
"PY3K",
":",
"flags",
"=",
"\"diouxXeEfFgGcrs%a\"",
"else",
":",
"flags",
"=",
"\"diouxXeEfFgGcrs%\"",
"if",
"char",
"not",
"in",
"flags",
":",
"raise",
"UnsupportedFormatCharacter",
"(",
"i",
")",
"if",
"key",
":",
"keys",
".",
"add",
"(",
"key",
")",
"key_types",
"[",
"key",
"]",
"=",
"char",
"elif",
"char",
"!=",
"\"%\"",
":",
"num_args",
"+=",
"1",
"pos_types",
".",
"append",
"(",
"char",
")",
"i",
"+=",
"1",
"return",
"keys",
",",
"num_args",
",",
"key_types",
",",
"pos_types"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
collect_string_fields
|
Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
|
pylint/checkers/utils.py
|
def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result in parseiterator:
if all(item is None for item in result[1:]):
# not a replacement format
continue
name = result[1]
nested = result[2]
yield name
if nested:
for field in collect_string_fields(nested):
yield field
except ValueError as exc:
# Probably the format string is invalid.
if exc.args[0].startswith("cannot switch from manual"):
# On Jython, parsing a string with both manual
# and automatic positions will fail with a ValueError,
# while on CPython it will simply return the fields,
# the validation being done in the interpreter (?).
# We're just returning two mixed fields in order
# to trigger the format-combined-specification check.
yield ""
yield "1"
return
raise IncompleteFormatString(format_string)
|
def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result in parseiterator:
if all(item is None for item in result[1:]):
# not a replacement format
continue
name = result[1]
nested = result[2]
yield name
if nested:
for field in collect_string_fields(nested):
yield field
except ValueError as exc:
# Probably the format string is invalid.
if exc.args[0].startswith("cannot switch from manual"):
# On Jython, parsing a string with both manual
# and automatic positions will fail with a ValueError,
# while on CPython it will simply return the fields,
# the validation being done in the interpreter (?).
# We're just returning two mixed fields in order
# to trigger the format-combined-specification check.
yield ""
yield "1"
return
raise IncompleteFormatString(format_string)
|
[
"Given",
"a",
"format",
"string",
"return",
"an",
"iterator",
"of",
"all",
"the",
"valid",
"format",
"fields",
".",
"It",
"handles",
"nested",
"fields",
"as",
"well",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L538-L568
|
[
"def",
"collect_string_fields",
"(",
"format_string",
")",
"->",
"Iterable",
"[",
"Optional",
"[",
"str",
"]",
"]",
":",
"formatter",
"=",
"string",
".",
"Formatter",
"(",
")",
"try",
":",
"parseiterator",
"=",
"formatter",
".",
"parse",
"(",
"format_string",
")",
"for",
"result",
"in",
"parseiterator",
":",
"if",
"all",
"(",
"item",
"is",
"None",
"for",
"item",
"in",
"result",
"[",
"1",
":",
"]",
")",
":",
"# not a replacement format",
"continue",
"name",
"=",
"result",
"[",
"1",
"]",
"nested",
"=",
"result",
"[",
"2",
"]",
"yield",
"name",
"if",
"nested",
":",
"for",
"field",
"in",
"collect_string_fields",
"(",
"nested",
")",
":",
"yield",
"field",
"except",
"ValueError",
"as",
"exc",
":",
"# Probably the format string is invalid.",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"cannot switch from manual\"",
")",
":",
"# On Jython, parsing a string with both manual",
"# and automatic positions will fail with a ValueError,",
"# while on CPython it will simply return the fields,",
"# the validation being done in the interpreter (?).",
"# We're just returning two mixed fields in order",
"# to trigger the format-combined-specification check.",
"yield",
"\"\"",
"yield",
"\"1\"",
"return",
"raise",
"IncompleteFormatString",
"(",
"format_string",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
parse_format_method_string
|
Parses a PEP 3101 format string, returning a tuple of
(keyword_arguments, implicit_pos_args_cnt, explicit_pos_args),
where keyword_arguments is the set of mapping keys in the format string, implicit_pos_args_cnt
is the number of arguments required by the format string and
explicit_pos_args is the number of arguments passed with the position.
|
pylint/checkers/utils.py
|
def parse_format_method_string(
format_string: str
) -> Tuple[List[Tuple[str, List[Tuple[bool, str]]]], int, int]:
"""
Parses a PEP 3101 format string, returning a tuple of
(keyword_arguments, implicit_pos_args_cnt, explicit_pos_args),
where keyword_arguments is the set of mapping keys in the format string, implicit_pos_args_cnt
is the number of arguments required by the format string and
explicit_pos_args is the number of arguments passed with the position.
"""
keyword_arguments = []
implicit_pos_args_cnt = 0
explicit_pos_args = set()
for name in collect_string_fields(format_string):
if name and str(name).isdigit():
explicit_pos_args.add(str(name))
elif name:
keyname, fielditerator = split_format_field_names(name)
if isinstance(keyname, numbers.Number):
# In Python 2 it will return long which will lead
# to different output between 2 and 3
explicit_pos_args.add(str(keyname))
keyname = int(keyname)
try:
keyword_arguments.append((keyname, list(fielditerator)))
except ValueError:
raise IncompleteFormatString()
else:
implicit_pos_args_cnt += 1
return keyword_arguments, implicit_pos_args_cnt, len(explicit_pos_args)
|
def parse_format_method_string(
format_string: str
) -> Tuple[List[Tuple[str, List[Tuple[bool, str]]]], int, int]:
"""
Parses a PEP 3101 format string, returning a tuple of
(keyword_arguments, implicit_pos_args_cnt, explicit_pos_args),
where keyword_arguments is the set of mapping keys in the format string, implicit_pos_args_cnt
is the number of arguments required by the format string and
explicit_pos_args is the number of arguments passed with the position.
"""
keyword_arguments = []
implicit_pos_args_cnt = 0
explicit_pos_args = set()
for name in collect_string_fields(format_string):
if name and str(name).isdigit():
explicit_pos_args.add(str(name))
elif name:
keyname, fielditerator = split_format_field_names(name)
if isinstance(keyname, numbers.Number):
# In Python 2 it will return long which will lead
# to different output between 2 and 3
explicit_pos_args.add(str(keyname))
keyname = int(keyname)
try:
keyword_arguments.append((keyname, list(fielditerator)))
except ValueError:
raise IncompleteFormatString()
else:
implicit_pos_args_cnt += 1
return keyword_arguments, implicit_pos_args_cnt, len(explicit_pos_args)
|
[
"Parses",
"a",
"PEP",
"3101",
"format",
"string",
"returning",
"a",
"tuple",
"of",
"(",
"keyword_arguments",
"implicit_pos_args_cnt",
"explicit_pos_args",
")",
"where",
"keyword_arguments",
"is",
"the",
"set",
"of",
"mapping",
"keys",
"in",
"the",
"format",
"string",
"implicit_pos_args_cnt",
"is",
"the",
"number",
"of",
"arguments",
"required",
"by",
"the",
"format",
"string",
"and",
"explicit_pos_args",
"is",
"the",
"number",
"of",
"arguments",
"passed",
"with",
"the",
"position",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L571-L600
|
[
"def",
"parse_format_method_string",
"(",
"format_string",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Tuple",
"[",
"str",
",",
"List",
"[",
"Tuple",
"[",
"bool",
",",
"str",
"]",
"]",
"]",
"]",
",",
"int",
",",
"int",
"]",
":",
"keyword_arguments",
"=",
"[",
"]",
"implicit_pos_args_cnt",
"=",
"0",
"explicit_pos_args",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"collect_string_fields",
"(",
"format_string",
")",
":",
"if",
"name",
"and",
"str",
"(",
"name",
")",
".",
"isdigit",
"(",
")",
":",
"explicit_pos_args",
".",
"add",
"(",
"str",
"(",
"name",
")",
")",
"elif",
"name",
":",
"keyname",
",",
"fielditerator",
"=",
"split_format_field_names",
"(",
"name",
")",
"if",
"isinstance",
"(",
"keyname",
",",
"numbers",
".",
"Number",
")",
":",
"# In Python 2 it will return long which will lead",
"# to different output between 2 and 3",
"explicit_pos_args",
".",
"add",
"(",
"str",
"(",
"keyname",
")",
")",
"keyname",
"=",
"int",
"(",
"keyname",
")",
"try",
":",
"keyword_arguments",
".",
"append",
"(",
"(",
"keyname",
",",
"list",
"(",
"fielditerator",
")",
")",
")",
"except",
"ValueError",
":",
"raise",
"IncompleteFormatString",
"(",
")",
"else",
":",
"implicit_pos_args_cnt",
"+=",
"1",
"return",
"keyword_arguments",
",",
"implicit_pos_args_cnt",
",",
"len",
"(",
"explicit_pos_args",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_attr_protected
|
return True if attribute name is protected (start with _ and some other
details), False otherwise.
|
pylint/checkers/utils.py
|
def is_attr_protected(attrname: str) -> bool:
"""return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return (
attrname[0] == "_"
and attrname != "_"
and not (attrname.startswith("__") and attrname.endswith("__"))
)
|
def is_attr_protected(attrname: str) -> bool:
"""return True if attribute name is protected (start with _ and some other
details), False otherwise.
"""
return (
attrname[0] == "_"
and attrname != "_"
and not (attrname.startswith("__") and attrname.endswith("__"))
)
|
[
"return",
"True",
"if",
"attribute",
"name",
"is",
"protected",
"(",
"start",
"with",
"_",
"and",
"some",
"other",
"details",
")",
"False",
"otherwise",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L603-L611
|
[
"def",
"is_attr_protected",
"(",
"attrname",
":",
"str",
")",
"->",
"bool",
":",
"return",
"(",
"attrname",
"[",
"0",
"]",
"==",
"\"_\"",
"and",
"attrname",
"!=",
"\"_\"",
"and",
"not",
"(",
"attrname",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"attrname",
".",
"endswith",
"(",
"\"__\"",
")",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
node_frame_class
|
return klass node for a method node (or a staticmethod or a
classmethod), return null otherwise
|
pylint/checkers/utils.py
|
def node_frame_class(
node: astroid.node_classes.NodeNG
) -> Optional[astroid.node_classes.NodeNG]:
"""return klass node for a method node (or a staticmethod or a
classmethod), return null otherwise
"""
klass = node.frame()
while klass is not None and not isinstance(klass, astroid.ClassDef):
if klass.parent is None:
klass = None
else:
klass = klass.parent.frame()
return klass
|
def node_frame_class(
node: astroid.node_classes.NodeNG
) -> Optional[astroid.node_classes.NodeNG]:
"""return klass node for a method node (or a staticmethod or a
classmethod), return null otherwise
"""
klass = node.frame()
while klass is not None and not isinstance(klass, astroid.ClassDef):
if klass.parent is None:
klass = None
else:
klass = klass.parent.frame()
return klass
|
[
"return",
"klass",
"node",
"for",
"a",
"method",
"node",
"(",
"or",
"a",
"staticmethod",
"or",
"a",
"classmethod",
")",
"return",
"null",
"otherwise"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L614-L628
|
[
"def",
"node_frame_class",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Optional",
"[",
"astroid",
".",
"node_classes",
".",
"NodeNG",
"]",
":",
"klass",
"=",
"node",
".",
"frame",
"(",
")",
"while",
"klass",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"klass",
",",
"astroid",
".",
"ClassDef",
")",
":",
"if",
"klass",
".",
"parent",
"is",
"None",
":",
"klass",
"=",
"None",
"else",
":",
"klass",
"=",
"klass",
".",
"parent",
".",
"frame",
"(",
")",
"return",
"klass"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_attr_private
|
Check that attribute name is private (at least two leading underscores,
at most one trailing underscore)
|
pylint/checkers/utils.py
|
def is_attr_private(attrname: str) -> Optional[Match[str]]:
"""Check that attribute name is private (at least two leading underscores,
at most one trailing underscore)
"""
regex = re.compile("^_{2,}.*[^_]+_?$")
return regex.match(attrname)
|
def is_attr_private(attrname: str) -> Optional[Match[str]]:
"""Check that attribute name is private (at least two leading underscores,
at most one trailing underscore)
"""
regex = re.compile("^_{2,}.*[^_]+_?$")
return regex.match(attrname)
|
[
"Check",
"that",
"attribute",
"name",
"is",
"private",
"(",
"at",
"least",
"two",
"leading",
"underscores",
"at",
"most",
"one",
"trailing",
"underscore",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L631-L636
|
[
"def",
"is_attr_private",
"(",
"attrname",
":",
"str",
")",
"->",
"Optional",
"[",
"Match",
"[",
"str",
"]",
"]",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"^_{2,}.*[^_]+_?$\"",
")",
"return",
"regex",
".",
"match",
"(",
"attrname",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_argument_from_call
|
Returns the specified argument from a function call.
:param astroid.Call call_node: Node representing a function call to check.
:param int position: position of the argument.
:param str keyword: the keyword of the argument.
:returns: The node representing the argument, None if the argument is not found.
:rtype: astroid.Name
:raises ValueError: if both position and keyword are None.
:raises NoSuchArgumentError: if no argument at the provided position or with
the provided keyword.
|
pylint/checkers/utils.py
|
def get_argument_from_call(
call_node: astroid.Call, position: int = None, keyword: str = None
) -> astroid.Name:
"""Returns the specified argument from a function call.
:param astroid.Call call_node: Node representing a function call to check.
:param int position: position of the argument.
:param str keyword: the keyword of the argument.
:returns: The node representing the argument, None if the argument is not found.
:rtype: astroid.Name
:raises ValueError: if both position and keyword are None.
:raises NoSuchArgumentError: if no argument at the provided position or with
the provided keyword.
"""
if position is None and keyword is None:
raise ValueError("Must specify at least one of: position or keyword.")
if position is not None:
try:
return call_node.args[position]
except IndexError:
pass
if keyword and call_node.keywords:
for arg in call_node.keywords:
if arg.arg == keyword:
return arg.value
raise NoSuchArgumentError
|
def get_argument_from_call(
call_node: astroid.Call, position: int = None, keyword: str = None
) -> astroid.Name:
"""Returns the specified argument from a function call.
:param astroid.Call call_node: Node representing a function call to check.
:param int position: position of the argument.
:param str keyword: the keyword of the argument.
:returns: The node representing the argument, None if the argument is not found.
:rtype: astroid.Name
:raises ValueError: if both position and keyword are None.
:raises NoSuchArgumentError: if no argument at the provided position or with
the provided keyword.
"""
if position is None and keyword is None:
raise ValueError("Must specify at least one of: position or keyword.")
if position is not None:
try:
return call_node.args[position]
except IndexError:
pass
if keyword and call_node.keywords:
for arg in call_node.keywords:
if arg.arg == keyword:
return arg.value
raise NoSuchArgumentError
|
[
"Returns",
"the",
"specified",
"argument",
"from",
"a",
"function",
"call",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L639-L666
|
[
"def",
"get_argument_from_call",
"(",
"call_node",
":",
"astroid",
".",
"Call",
",",
"position",
":",
"int",
"=",
"None",
",",
"keyword",
":",
"str",
"=",
"None",
")",
"->",
"astroid",
".",
"Name",
":",
"if",
"position",
"is",
"None",
"and",
"keyword",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must specify at least one of: position or keyword.\"",
")",
"if",
"position",
"is",
"not",
"None",
":",
"try",
":",
"return",
"call_node",
".",
"args",
"[",
"position",
"]",
"except",
"IndexError",
":",
"pass",
"if",
"keyword",
"and",
"call_node",
".",
"keywords",
":",
"for",
"arg",
"in",
"call_node",
".",
"keywords",
":",
"if",
"arg",
".",
"arg",
"==",
"keyword",
":",
"return",
"arg",
".",
"value",
"raise",
"NoSuchArgumentError"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
inherit_from_std_ex
|
Return true if the given class node is subclass of
exceptions.Exception.
|
pylint/checkers/utils.py
|
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool:
"""
Return true if the given class node is subclass of
exceptions.Exception.
"""
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
for ancestor in itertools.chain([node], ancestors):
if (
ancestor.name in ("Exception", "BaseException")
and ancestor.root().name == EXCEPTIONS_MODULE
):
return True
return False
|
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool:
"""
Return true if the given class node is subclass of
exceptions.Exception.
"""
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
for ancestor in itertools.chain([node], ancestors):
if (
ancestor.name in ("Exception", "BaseException")
and ancestor.root().name == EXCEPTIONS_MODULE
):
return True
return False
|
[
"Return",
"true",
"if",
"the",
"given",
"class",
"node",
"is",
"subclass",
"of",
"exceptions",
".",
"Exception",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L669-L681
|
[
"def",
"inherit_from_std_ex",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"ancestors",
"=",
"node",
".",
"ancestors",
"(",
")",
"if",
"hasattr",
"(",
"node",
",",
"\"ancestors\"",
")",
"else",
"[",
"]",
"for",
"ancestor",
"in",
"itertools",
".",
"chain",
"(",
"[",
"node",
"]",
",",
"ancestors",
")",
":",
"if",
"(",
"ancestor",
".",
"name",
"in",
"(",
"\"Exception\"",
",",
"\"BaseException\"",
")",
"and",
"ancestor",
".",
"root",
"(",
")",
".",
"name",
"==",
"EXCEPTIONS_MODULE",
")",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
error_of_type
|
Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an exception, or it can be a tuple of errors.
The function will return True if the handler catches any of the
given errors.
|
pylint/checkers/utils.py
|
def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool:
"""
Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an exception, or it can be a tuple of errors.
The function will return True if the handler catches any of the
given errors.
"""
def stringify_error(error):
if not isinstance(error, str):
return error.__name__
return error
if not isinstance(error_type, tuple):
error_type = (error_type,) # type: ignore
expected_errors = {stringify_error(error) for error in error_type} # type: ignore
if not handler.type:
return True
return handler.catch(expected_errors)
|
def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool:
"""
Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an exception, or it can be a tuple of errors.
The function will return True if the handler catches any of the
given errors.
"""
def stringify_error(error):
if not isinstance(error, str):
return error.__name__
return error
if not isinstance(error_type, tuple):
error_type = (error_type,) # type: ignore
expected_errors = {stringify_error(error) for error in error_type} # type: ignore
if not handler.type:
return True
return handler.catch(expected_errors)
|
[
"Check",
"if",
"the",
"given",
"exception",
"handler",
"catches",
"the",
"given",
"error_type",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L684-L706
|
[
"def",
"error_of_type",
"(",
"handler",
":",
"astroid",
".",
"ExceptHandler",
",",
"error_type",
")",
"->",
"bool",
":",
"def",
"stringify_error",
"(",
"error",
")",
":",
"if",
"not",
"isinstance",
"(",
"error",
",",
"str",
")",
":",
"return",
"error",
".",
"__name__",
"return",
"error",
"if",
"not",
"isinstance",
"(",
"error_type",
",",
"tuple",
")",
":",
"error_type",
"=",
"(",
"error_type",
",",
")",
"# type: ignore",
"expected_errors",
"=",
"{",
"stringify_error",
"(",
"error",
")",
"for",
"error",
"in",
"error_type",
"}",
"# type: ignore",
"if",
"not",
"handler",
".",
"type",
":",
"return",
"True",
"return",
"handler",
".",
"catch",
"(",
"expected_errors",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
decorated_with_property
|
Detect if the given function node is decorated with a property.
|
pylint/checkers/utils.py
|
def decorated_with_property(node: astroid.FunctionDef) -> bool:
""" Detect if the given function node is decorated with a property. """
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False
|
def decorated_with_property(node: astroid.FunctionDef) -> bool:
""" Detect if the given function node is decorated with a property. """
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False
|
[
"Detect",
"if",
"the",
"given",
"function",
"node",
"is",
"decorated",
"with",
"a",
"property",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L709-L721
|
[
"def",
"decorated_with_property",
"(",
"node",
":",
"astroid",
".",
"FunctionDef",
")",
"->",
"bool",
":",
"if",
"not",
"node",
".",
"decorators",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
".",
"Name",
")",
":",
"continue",
"try",
":",
"if",
"_is_property_decorator",
"(",
"decorator",
")",
":",
"return",
"True",
"except",
"astroid",
".",
"InferenceError",
":",
"pass",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
decorated_with
|
Determine if the `func` node has a decorator with the qualified name `qname`.
|
pylint/checkers/utils.py
|
def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool:
"""Determine if the `func` node has a decorator with the qualified name `qname`."""
decorators = func.decorators.nodes if func.decorators else []
for decorator_node in decorators:
try:
if any(
i is not None and i.qname() in qnames for i in decorator_node.infer()
):
return True
except astroid.InferenceError:
continue
return False
|
def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool:
"""Determine if the `func` node has a decorator with the qualified name `qname`."""
decorators = func.decorators.nodes if func.decorators else []
for decorator_node in decorators:
try:
if any(
i is not None and i.qname() in qnames for i in decorator_node.infer()
):
return True
except astroid.InferenceError:
continue
return False
|
[
"Determine",
"if",
"the",
"func",
"node",
"has",
"a",
"decorator",
"with",
"the",
"qualified",
"name",
"qname",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L738-L749
|
[
"def",
"decorated_with",
"(",
"func",
":",
"astroid",
".",
"FunctionDef",
",",
"qnames",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"decorators",
"=",
"func",
".",
"decorators",
".",
"nodes",
"if",
"func",
".",
"decorators",
"else",
"[",
"]",
"for",
"decorator_node",
"in",
"decorators",
":",
"try",
":",
"if",
"any",
"(",
"i",
"is",
"not",
"None",
"and",
"i",
".",
"qname",
"(",
")",
"in",
"qnames",
"for",
"i",
"in",
"decorator_node",
".",
"infer",
"(",
")",
")",
":",
"return",
"True",
"except",
"astroid",
".",
"InferenceError",
":",
"continue",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
unimplemented_abstract_methods
|
Get the unimplemented abstract methods for the given *node*.
A method can be considered abstract if the callback *is_abstract_cb*
returns a ``True`` value. The check defaults to verifying that
a method is decorated with abstract methods.
The function will work only for new-style classes. For old-style
classes, it will simply return an empty dictionary.
For the rest of them, it will return a dictionary of abstract method
names and their inferred objects.
|
pylint/checkers/utils.py
|
def unimplemented_abstract_methods(
node: astroid.node_classes.NodeNG, is_abstract_cb: astroid.FunctionDef = None
) -> Dict[str, astroid.node_classes.NodeNG]:
"""
Get the unimplemented abstract methods for the given *node*.
A method can be considered abstract if the callback *is_abstract_cb*
returns a ``True`` value. The check defaults to verifying that
a method is decorated with abstract methods.
The function will work only for new-style classes. For old-style
classes, it will simply return an empty dictionary.
For the rest of them, it will return a dictionary of abstract method
names and their inferred objects.
"""
if is_abstract_cb is None:
is_abstract_cb = partial(decorated_with, qnames=ABC_METHODS)
visited = {} # type: Dict[str, astroid.node_classes.NodeNG]
try:
mro = reversed(node.mro())
except NotImplementedError:
# Old style class, it will not have a mro.
return {}
except astroid.ResolveError:
# Probably inconsistent hierarchy, don'try
# to figure this out here.
return {}
for ancestor in mro:
for obj in ancestor.values():
infered = obj
if isinstance(obj, astroid.AssignName):
infered = safe_infer(obj)
if not infered:
# Might be an abstract function,
# but since we don't have enough information
# in order to take this decision, we're taking
# the *safe* decision instead.
if obj.name in visited:
del visited[obj.name]
continue
if not isinstance(infered, astroid.FunctionDef):
if obj.name in visited:
del visited[obj.name]
if isinstance(infered, astroid.FunctionDef):
# It's critical to use the original name,
# since after inferring, an object can be something
# else than expected, as in the case of the
# following assignment.
#
# class A:
# def keys(self): pass
# __iter__ = keys
abstract = is_abstract_cb(infered)
if abstract:
visited[obj.name] = infered
elif not abstract and obj.name in visited:
del visited[obj.name]
return visited
|
def unimplemented_abstract_methods(
node: astroid.node_classes.NodeNG, is_abstract_cb: astroid.FunctionDef = None
) -> Dict[str, astroid.node_classes.NodeNG]:
"""
Get the unimplemented abstract methods for the given *node*.
A method can be considered abstract if the callback *is_abstract_cb*
returns a ``True`` value. The check defaults to verifying that
a method is decorated with abstract methods.
The function will work only for new-style classes. For old-style
classes, it will simply return an empty dictionary.
For the rest of them, it will return a dictionary of abstract method
names and their inferred objects.
"""
if is_abstract_cb is None:
is_abstract_cb = partial(decorated_with, qnames=ABC_METHODS)
visited = {} # type: Dict[str, astroid.node_classes.NodeNG]
try:
mro = reversed(node.mro())
except NotImplementedError:
# Old style class, it will not have a mro.
return {}
except astroid.ResolveError:
# Probably inconsistent hierarchy, don'try
# to figure this out here.
return {}
for ancestor in mro:
for obj in ancestor.values():
infered = obj
if isinstance(obj, astroid.AssignName):
infered = safe_infer(obj)
if not infered:
# Might be an abstract function,
# but since we don't have enough information
# in order to take this decision, we're taking
# the *safe* decision instead.
if obj.name in visited:
del visited[obj.name]
continue
if not isinstance(infered, astroid.FunctionDef):
if obj.name in visited:
del visited[obj.name]
if isinstance(infered, astroid.FunctionDef):
# It's critical to use the original name,
# since after inferring, an object can be something
# else than expected, as in the case of the
# following assignment.
#
# class A:
# def keys(self): pass
# __iter__ = keys
abstract = is_abstract_cb(infered)
if abstract:
visited[obj.name] = infered
elif not abstract and obj.name in visited:
del visited[obj.name]
return visited
|
[
"Get",
"the",
"unimplemented",
"abstract",
"methods",
"for",
"the",
"given",
"*",
"node",
"*",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L753-L809
|
[
"def",
"unimplemented_abstract_methods",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"is_abstract_cb",
":",
"astroid",
".",
"FunctionDef",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"astroid",
".",
"node_classes",
".",
"NodeNG",
"]",
":",
"if",
"is_abstract_cb",
"is",
"None",
":",
"is_abstract_cb",
"=",
"partial",
"(",
"decorated_with",
",",
"qnames",
"=",
"ABC_METHODS",
")",
"visited",
"=",
"{",
"}",
"# type: Dict[str, astroid.node_classes.NodeNG]",
"try",
":",
"mro",
"=",
"reversed",
"(",
"node",
".",
"mro",
"(",
")",
")",
"except",
"NotImplementedError",
":",
"# Old style class, it will not have a mro.",
"return",
"{",
"}",
"except",
"astroid",
".",
"ResolveError",
":",
"# Probably inconsistent hierarchy, don'try",
"# to figure this out here.",
"return",
"{",
"}",
"for",
"ancestor",
"in",
"mro",
":",
"for",
"obj",
"in",
"ancestor",
".",
"values",
"(",
")",
":",
"infered",
"=",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"astroid",
".",
"AssignName",
")",
":",
"infered",
"=",
"safe_infer",
"(",
"obj",
")",
"if",
"not",
"infered",
":",
"# Might be an abstract function,",
"# but since we don't have enough information",
"# in order to take this decision, we're taking",
"# the *safe* decision instead.",
"if",
"obj",
".",
"name",
"in",
"visited",
":",
"del",
"visited",
"[",
"obj",
".",
"name",
"]",
"continue",
"if",
"not",
"isinstance",
"(",
"infered",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"if",
"obj",
".",
"name",
"in",
"visited",
":",
"del",
"visited",
"[",
"obj",
".",
"name",
"]",
"if",
"isinstance",
"(",
"infered",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"# It's critical to use the original name,",
"# since after inferring, an object can be something",
"# else than expected, as in the case of the",
"# following assignment.",
"#",
"# class A:",
"# def keys(self): pass",
"# __iter__ = keys",
"abstract",
"=",
"is_abstract_cb",
"(",
"infered",
")",
"if",
"abstract",
":",
"visited",
"[",
"obj",
".",
"name",
"]",
"=",
"infered",
"elif",
"not",
"abstract",
"and",
"obj",
".",
"name",
"in",
"visited",
":",
"del",
"visited",
"[",
"obj",
".",
"name",
"]",
"return",
"visited"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
find_try_except_wrapper_node
|
Return the ExceptHandler or the TryExcept node in which the node is.
|
pylint/checkers/utils.py
|
def find_try_except_wrapper_node(
node: astroid.node_classes.NodeNG
) -> Union[astroid.ExceptHandler, astroid.TryExcept]:
"""Return the ExceptHandler or the TryExcept node in which the node is."""
current = node
ignores = (astroid.ExceptHandler, astroid.TryExcept)
while current and not isinstance(current.parent, ignores):
current = current.parent
if current and isinstance(current.parent, ignores):
return current.parent
return None
|
def find_try_except_wrapper_node(
node: astroid.node_classes.NodeNG
) -> Union[astroid.ExceptHandler, astroid.TryExcept]:
"""Return the ExceptHandler or the TryExcept node in which the node is."""
current = node
ignores = (astroid.ExceptHandler, astroid.TryExcept)
while current and not isinstance(current.parent, ignores):
current = current.parent
if current and isinstance(current.parent, ignores):
return current.parent
return None
|
[
"Return",
"the",
"ExceptHandler",
"or",
"the",
"TryExcept",
"node",
"in",
"which",
"the",
"node",
"is",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L812-L823
|
[
"def",
"find_try_except_wrapper_node",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Union",
"[",
"astroid",
".",
"ExceptHandler",
",",
"astroid",
".",
"TryExcept",
"]",
":",
"current",
"=",
"node",
"ignores",
"=",
"(",
"astroid",
".",
"ExceptHandler",
",",
"astroid",
".",
"TryExcept",
")",
"while",
"current",
"and",
"not",
"isinstance",
"(",
"current",
".",
"parent",
",",
"ignores",
")",
":",
"current",
"=",
"current",
".",
"parent",
"if",
"current",
"and",
"isinstance",
"(",
"current",
".",
"parent",
",",
"ignores",
")",
":",
"return",
"current",
".",
"parent",
"return",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_from_fallback_block
|
Check if the given node is from a fallback import block.
|
pylint/checkers/utils.py
|
def is_from_fallback_block(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the given node is from a fallback import block."""
context = find_try_except_wrapper_node(node)
if not context:
return False
if isinstance(context, astroid.ExceptHandler):
other_body = context.parent.body
handlers = context.parent.handlers
else:
other_body = itertools.chain.from_iterable(
handler.body for handler in context.handlers
)
handlers = context.handlers
has_fallback_imports = any(
isinstance(import_node, (astroid.ImportFrom, astroid.Import))
for import_node in other_body
)
ignores_import_error = _except_handlers_ignores_exception(handlers, ImportError)
return ignores_import_error or has_fallback_imports
|
def is_from_fallback_block(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the given node is from a fallback import block."""
context = find_try_except_wrapper_node(node)
if not context:
return False
if isinstance(context, astroid.ExceptHandler):
other_body = context.parent.body
handlers = context.parent.handlers
else:
other_body = itertools.chain.from_iterable(
handler.body for handler in context.handlers
)
handlers = context.handlers
has_fallback_imports = any(
isinstance(import_node, (astroid.ImportFrom, astroid.Import))
for import_node in other_body
)
ignores_import_error = _except_handlers_ignores_exception(handlers, ImportError)
return ignores_import_error or has_fallback_imports
|
[
"Check",
"if",
"the",
"given",
"node",
"is",
"from",
"a",
"fallback",
"import",
"block",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L826-L846
|
[
"def",
"is_from_fallback_block",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"context",
"=",
"find_try_except_wrapper_node",
"(",
"node",
")",
"if",
"not",
"context",
":",
"return",
"False",
"if",
"isinstance",
"(",
"context",
",",
"astroid",
".",
"ExceptHandler",
")",
":",
"other_body",
"=",
"context",
".",
"parent",
".",
"body",
"handlers",
"=",
"context",
".",
"parent",
".",
"handlers",
"else",
":",
"other_body",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"handler",
".",
"body",
"for",
"handler",
"in",
"context",
".",
"handlers",
")",
"handlers",
"=",
"context",
".",
"handlers",
"has_fallback_imports",
"=",
"any",
"(",
"isinstance",
"(",
"import_node",
",",
"(",
"astroid",
".",
"ImportFrom",
",",
"astroid",
".",
"Import",
")",
")",
"for",
"import_node",
"in",
"other_body",
")",
"ignores_import_error",
"=",
"_except_handlers_ignores_exception",
"(",
"handlers",
",",
"ImportError",
")",
"return",
"ignores_import_error",
"or",
"has_fallback_imports"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_exception_handlers
|
Return the collections of handlers handling the exception in arguments.
Args:
node (astroid.NodeNG): A node that is potentially wrapped in a try except.
exception (builtin.Exception or str): exception or name of the exception.
Returns:
list: the collection of handlers that are handling the exception or None.
|
pylint/checkers/utils.py
|
def get_exception_handlers(
node: astroid.node_classes.NodeNG, exception=Exception
) -> List[astroid.ExceptHandler]:
"""Return the collections of handlers handling the exception in arguments.
Args:
node (astroid.NodeNG): A node that is potentially wrapped in a try except.
exception (builtin.Exception or str): exception or name of the exception.
Returns:
list: the collection of handlers that are handling the exception or None.
"""
context = find_try_except_wrapper_node(node)
if isinstance(context, astroid.TryExcept):
return [
handler for handler in context.handlers if error_of_type(handler, exception)
]
return None
|
def get_exception_handlers(
node: astroid.node_classes.NodeNG, exception=Exception
) -> List[astroid.ExceptHandler]:
"""Return the collections of handlers handling the exception in arguments.
Args:
node (astroid.NodeNG): A node that is potentially wrapped in a try except.
exception (builtin.Exception or str): exception or name of the exception.
Returns:
list: the collection of handlers that are handling the exception or None.
"""
context = find_try_except_wrapper_node(node)
if isinstance(context, astroid.TryExcept):
return [
handler for handler in context.handlers if error_of_type(handler, exception)
]
return None
|
[
"Return",
"the",
"collections",
"of",
"handlers",
"handling",
"the",
"exception",
"in",
"arguments",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L856-L874
|
[
"def",
"get_exception_handlers",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"exception",
"=",
"Exception",
")",
"->",
"List",
"[",
"astroid",
".",
"ExceptHandler",
"]",
":",
"context",
"=",
"find_try_except_wrapper_node",
"(",
"node",
")",
"if",
"isinstance",
"(",
"context",
",",
"astroid",
".",
"TryExcept",
")",
":",
"return",
"[",
"handler",
"for",
"handler",
"in",
"context",
".",
"handlers",
"if",
"error_of_type",
"(",
"handler",
",",
"exception",
")",
"]",
"return",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_node_inside_try_except
|
Check if the node is directly under a Try/Except statement.
(but not under an ExceptHandler!)
Args:
node (astroid.Raise): the node raising the exception.
Returns:
bool: True if the node is inside a try/except statement, False otherwise.
|
pylint/checkers/utils.py
|
def is_node_inside_try_except(node: astroid.Raise) -> bool:
"""Check if the node is directly under a Try/Except statement.
(but not under an ExceptHandler!)
Args:
node (astroid.Raise): the node raising the exception.
Returns:
bool: True if the node is inside a try/except statement, False otherwise.
"""
context = find_try_except_wrapper_node(node)
return isinstance(context, astroid.TryExcept)
|
def is_node_inside_try_except(node: astroid.Raise) -> bool:
"""Check if the node is directly under a Try/Except statement.
(but not under an ExceptHandler!)
Args:
node (astroid.Raise): the node raising the exception.
Returns:
bool: True if the node is inside a try/except statement, False otherwise.
"""
context = find_try_except_wrapper_node(node)
return isinstance(context, astroid.TryExcept)
|
[
"Check",
"if",
"the",
"node",
"is",
"directly",
"under",
"a",
"Try",
"/",
"Except",
"statement",
".",
"(",
"but",
"not",
"under",
"an",
"ExceptHandler!",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L877-L888
|
[
"def",
"is_node_inside_try_except",
"(",
"node",
":",
"astroid",
".",
"Raise",
")",
"->",
"bool",
":",
"context",
"=",
"find_try_except_wrapper_node",
"(",
"node",
")",
"return",
"isinstance",
"(",
"context",
",",
"astroid",
".",
"TryExcept",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
node_ignores_exception
|
Check if the node is in a TryExcept which handles the given exception.
If the exception is not given, the function is going to look for bare
excepts.
|
pylint/checkers/utils.py
|
def node_ignores_exception(
node: astroid.node_classes.NodeNG, exception=Exception
) -> bool:
"""Check if the node is in a TryExcept which handles the given exception.
If the exception is not given, the function is going to look for bare
excepts.
"""
managing_handlers = get_exception_handlers(node, exception)
if not managing_handlers:
return False
return any(managing_handlers)
|
def node_ignores_exception(
node: astroid.node_classes.NodeNG, exception=Exception
) -> bool:
"""Check if the node is in a TryExcept which handles the given exception.
If the exception is not given, the function is going to look for bare
excepts.
"""
managing_handlers = get_exception_handlers(node, exception)
if not managing_handlers:
return False
return any(managing_handlers)
|
[
"Check",
"if",
"the",
"node",
"is",
"in",
"a",
"TryExcept",
"which",
"handles",
"the",
"given",
"exception",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L891-L902
|
[
"def",
"node_ignores_exception",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"exception",
"=",
"Exception",
")",
"->",
"bool",
":",
"managing_handlers",
"=",
"get_exception_handlers",
"(",
"node",
",",
"exception",
")",
"if",
"not",
"managing_handlers",
":",
"return",
"False",
"return",
"any",
"(",
"managing_handlers",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
class_is_abstract
|
return true if the given class node should be considered as an abstract
class
|
pylint/checkers/utils.py
|
def class_is_abstract(node: astroid.ClassDef) -> bool:
"""return true if the given class node should be considered as an abstract
class
"""
for method in node.methods():
if method.parent.frame() is node:
if method.is_abstract(pass_is_abstract=False):
return True
return False
|
def class_is_abstract(node: astroid.ClassDef) -> bool:
"""return true if the given class node should be considered as an abstract
class
"""
for method in node.methods():
if method.parent.frame() is node:
if method.is_abstract(pass_is_abstract=False):
return True
return False
|
[
"return",
"true",
"if",
"the",
"given",
"class",
"node",
"should",
"be",
"considered",
"as",
"an",
"abstract",
"class"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L905-L913
|
[
"def",
"class_is_abstract",
"(",
"node",
":",
"astroid",
".",
"ClassDef",
")",
"->",
"bool",
":",
"for",
"method",
"in",
"node",
".",
"methods",
"(",
")",
":",
"if",
"method",
".",
"parent",
".",
"frame",
"(",
")",
"is",
"node",
":",
"if",
"method",
".",
"is_abstract",
"(",
"pass_is_abstract",
"=",
"False",
")",
":",
"return",
"True",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
safe_infer
|
Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
|
pylint/checkers/utils.py
|
def safe_infer(
node: astroid.node_classes.NodeNG, context=None
) -> Optional[astroid.node_classes.NodeNG]:
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
"""
try:
inferit = node.infer(context=context)
value = next(inferit)
except astroid.InferenceError:
return None
try:
next(inferit)
return None # None if there is ambiguity on the inferred node
except astroid.InferenceError:
return None # there is some kind of ambiguity
except StopIteration:
return value
|
def safe_infer(
node: astroid.node_classes.NodeNG, context=None
) -> Optional[astroid.node_classes.NodeNG]:
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
"""
try:
inferit = node.infer(context=context)
value = next(inferit)
except astroid.InferenceError:
return None
try:
next(inferit)
return None # None if there is ambiguity on the inferred node
except astroid.InferenceError:
return None # there is some kind of ambiguity
except StopIteration:
return value
|
[
"Return",
"the",
"inferred",
"value",
"for",
"the",
"given",
"node",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1057-L1076
|
[
"def",
"safe_infer",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
",",
"context",
"=",
"None",
")",
"->",
"Optional",
"[",
"astroid",
".",
"node_classes",
".",
"NodeNG",
"]",
":",
"try",
":",
"inferit",
"=",
"node",
".",
"infer",
"(",
"context",
"=",
"context",
")",
"value",
"=",
"next",
"(",
"inferit",
")",
"except",
"astroid",
".",
"InferenceError",
":",
"return",
"None",
"try",
":",
"next",
"(",
"inferit",
")",
"return",
"None",
"# None if there is ambiguity on the inferred node",
"except",
"astroid",
".",
"InferenceError",
":",
"return",
"None",
"# there is some kind of ambiguity",
"except",
"StopIteration",
":",
"return",
"value"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
node_type
|
Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
|
pylint/checkers/utils.py
|
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else we
# don't handle it for now
types = set()
try:
for var_type in node.infer():
if var_type == astroid.Uninferable or is_none(var_type):
continue
types.add(var_type)
if len(types) > 1:
return None
except astroid.InferenceError:
return None
return types.pop() if types else None
|
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else we
# don't handle it for now
types = set()
try:
for var_type in node.infer():
if var_type == astroid.Uninferable or is_none(var_type):
continue
types.add(var_type)
if len(types) > 1:
return None
except astroid.InferenceError:
return None
return types.pop() if types else None
|
[
"Return",
"the",
"inferred",
"type",
"for",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1107-L1125
|
[
"def",
"node_type",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"Optional",
"[",
"type",
"]",
":",
"# check there is only one possible type for the assign node. Else we",
"# don't handle it for now",
"types",
"=",
"set",
"(",
")",
"try",
":",
"for",
"var_type",
"in",
"node",
".",
"infer",
"(",
")",
":",
"if",
"var_type",
"==",
"astroid",
".",
"Uninferable",
"or",
"is_none",
"(",
"var_type",
")",
":",
"continue",
"types",
".",
"add",
"(",
"var_type",
")",
"if",
"len",
"(",
"types",
")",
">",
"1",
":",
"return",
"None",
"except",
"astroid",
".",
"InferenceError",
":",
"return",
"None",
"return",
"types",
".",
"pop",
"(",
")",
"if",
"types",
"else",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_registered_in_singledispatch_function
|
Check if the given function node is a singledispatch function.
|
pylint/checkers/utils.py
|
def is_registered_in_singledispatch_function(node: astroid.FunctionDef) -> bool:
"""Check if the given function node is a singledispatch function."""
singledispatch_qnames = (
"functools.singledispatch",
"singledispatch.singledispatch",
)
if not isinstance(node, astroid.FunctionDef):
return False
decorators = node.decorators.nodes if node.decorators else []
for decorator in decorators:
# func.register are function calls
if not isinstance(decorator, astroid.Call):
continue
func = decorator.func
if not isinstance(func, astroid.Attribute) or func.attrname != "register":
continue
try:
func_def = next(func.expr.infer())
except astroid.InferenceError:
continue
if isinstance(func_def, astroid.FunctionDef):
# pylint: disable=redundant-keyword-arg; some flow inference goes wrong here
return decorated_with(func_def, singledispatch_qnames)
return False
|
def is_registered_in_singledispatch_function(node: astroid.FunctionDef) -> bool:
"""Check if the given function node is a singledispatch function."""
singledispatch_qnames = (
"functools.singledispatch",
"singledispatch.singledispatch",
)
if not isinstance(node, astroid.FunctionDef):
return False
decorators = node.decorators.nodes if node.decorators else []
for decorator in decorators:
# func.register are function calls
if not isinstance(decorator, astroid.Call):
continue
func = decorator.func
if not isinstance(func, astroid.Attribute) or func.attrname != "register":
continue
try:
func_def = next(func.expr.infer())
except astroid.InferenceError:
continue
if isinstance(func_def, astroid.FunctionDef):
# pylint: disable=redundant-keyword-arg; some flow inference goes wrong here
return decorated_with(func_def, singledispatch_qnames)
return False
|
[
"Check",
"if",
"the",
"given",
"function",
"node",
"is",
"a",
"singledispatch",
"function",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1128-L1158
|
[
"def",
"is_registered_in_singledispatch_function",
"(",
"node",
":",
"astroid",
".",
"FunctionDef",
")",
"->",
"bool",
":",
"singledispatch_qnames",
"=",
"(",
"\"functools.singledispatch\"",
",",
"\"singledispatch.singledispatch\"",
",",
")",
"if",
"not",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"return",
"False",
"decorators",
"=",
"node",
".",
"decorators",
".",
"nodes",
"if",
"node",
".",
"decorators",
"else",
"[",
"]",
"for",
"decorator",
"in",
"decorators",
":",
"# func.register are function calls",
"if",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
".",
"Call",
")",
":",
"continue",
"func",
"=",
"decorator",
".",
"func",
"if",
"not",
"isinstance",
"(",
"func",
",",
"astroid",
".",
"Attribute",
")",
"or",
"func",
".",
"attrname",
"!=",
"\"register\"",
":",
"continue",
"try",
":",
"func_def",
"=",
"next",
"(",
"func",
".",
"expr",
".",
"infer",
"(",
")",
")",
"except",
"astroid",
".",
"InferenceError",
":",
"continue",
"if",
"isinstance",
"(",
"func_def",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"# pylint: disable=redundant-keyword-arg; some flow inference goes wrong here",
"return",
"decorated_with",
"(",
"func_def",
",",
"singledispatch_qnames",
")",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_node_last_lineno
|
Get the last lineno of the given node. For a simple statement this will just be node.lineno,
but for a node that has child statements (e.g. a method) this will be the lineno of the last
child statement recursively.
|
pylint/checkers/utils.py
|
def get_node_last_lineno(node: astroid.node_classes.NodeNG) -> int:
"""
Get the last lineno of the given node. For a simple statement this will just be node.lineno,
but for a node that has child statements (e.g. a method) this will be the lineno of the last
child statement recursively.
"""
# 'finalbody' is always the last clause in a try statement, if present
if getattr(node, "finalbody", False):
return get_node_last_lineno(node.finalbody[-1])
# For if, while, and for statements 'orelse' is always the last clause.
# For try statements 'orelse' is the last in the absence of a 'finalbody'
if getattr(node, "orelse", False):
return get_node_last_lineno(node.orelse[-1])
# try statements have the 'handlers' last if there is no 'orelse' or 'finalbody'
if getattr(node, "handlers", False):
return get_node_last_lineno(node.handlers[-1])
# All compound statements have a 'body'
if getattr(node, "body", False):
return get_node_last_lineno(node.body[-1])
# Not a compound statement
return node.lineno
|
def get_node_last_lineno(node: astroid.node_classes.NodeNG) -> int:
"""
Get the last lineno of the given node. For a simple statement this will just be node.lineno,
but for a node that has child statements (e.g. a method) this will be the lineno of the last
child statement recursively.
"""
# 'finalbody' is always the last clause in a try statement, if present
if getattr(node, "finalbody", False):
return get_node_last_lineno(node.finalbody[-1])
# For if, while, and for statements 'orelse' is always the last clause.
# For try statements 'orelse' is the last in the absence of a 'finalbody'
if getattr(node, "orelse", False):
return get_node_last_lineno(node.orelse[-1])
# try statements have the 'handlers' last if there is no 'orelse' or 'finalbody'
if getattr(node, "handlers", False):
return get_node_last_lineno(node.handlers[-1])
# All compound statements have a 'body'
if getattr(node, "body", False):
return get_node_last_lineno(node.body[-1])
# Not a compound statement
return node.lineno
|
[
"Get",
"the",
"last",
"lineno",
"of",
"the",
"given",
"node",
".",
"For",
"a",
"simple",
"statement",
"this",
"will",
"just",
"be",
"node",
".",
"lineno",
"but",
"for",
"a",
"node",
"that",
"has",
"child",
"statements",
"(",
"e",
".",
"g",
".",
"a",
"method",
")",
"this",
"will",
"be",
"the",
"lineno",
"of",
"the",
"last",
"child",
"statement",
"recursively",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1161-L1181
|
[
"def",
"get_node_last_lineno",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"int",
":",
"# 'finalbody' is always the last clause in a try statement, if present",
"if",
"getattr",
"(",
"node",
",",
"\"finalbody\"",
",",
"False",
")",
":",
"return",
"get_node_last_lineno",
"(",
"node",
".",
"finalbody",
"[",
"-",
"1",
"]",
")",
"# For if, while, and for statements 'orelse' is always the last clause.",
"# For try statements 'orelse' is the last in the absence of a 'finalbody'",
"if",
"getattr",
"(",
"node",
",",
"\"orelse\"",
",",
"False",
")",
":",
"return",
"get_node_last_lineno",
"(",
"node",
".",
"orelse",
"[",
"-",
"1",
"]",
")",
"# try statements have the 'handlers' last if there is no 'orelse' or 'finalbody'",
"if",
"getattr",
"(",
"node",
",",
"\"handlers\"",
",",
"False",
")",
":",
"return",
"get_node_last_lineno",
"(",
"node",
".",
"handlers",
"[",
"-",
"1",
"]",
")",
"# All compound statements have a 'body'",
"if",
"getattr",
"(",
"node",
",",
"\"body\"",
",",
"False",
")",
":",
"return",
"get_node_last_lineno",
"(",
"node",
".",
"body",
"[",
"-",
"1",
"]",
")",
"# Not a compound statement",
"return",
"node",
".",
"lineno"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_postponed_evaluation_enabled
|
Check if the postponed evaluation of annotations is enabled
|
pylint/checkers/utils.py
|
def is_postponed_evaluation_enabled(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the postponed evaluation of annotations is enabled"""
name = "annotations"
module = node.root()
stmt = module.locals.get(name)
return (
stmt
and isinstance(stmt[0], astroid.ImportFrom)
and stmt[0].modname == "__future__"
)
|
def is_postponed_evaluation_enabled(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the postponed evaluation of annotations is enabled"""
name = "annotations"
module = node.root()
stmt = module.locals.get(name)
return (
stmt
and isinstance(stmt[0], astroid.ImportFrom)
and stmt[0].modname == "__future__"
)
|
[
"Check",
"if",
"the",
"postponed",
"evaluation",
"of",
"annotations",
"is",
"enabled"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1184-L1193
|
[
"def",
"is_postponed_evaluation_enabled",
"(",
"node",
":",
"astroid",
".",
"node_classes",
".",
"NodeNG",
")",
"->",
"bool",
":",
"name",
"=",
"\"annotations\"",
"module",
"=",
"node",
".",
"root",
"(",
")",
"stmt",
"=",
"module",
".",
"locals",
".",
"get",
"(",
"name",
")",
"return",
"(",
"stmt",
"and",
"isinstance",
"(",
"stmt",
"[",
"0",
"]",
",",
"astroid",
".",
"ImportFrom",
")",
"and",
"stmt",
"[",
"0",
"]",
".",
"modname",
"==",
"\"__future__\"",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
is_subclass_of
|
Check if first node is a subclass of second node.
:param child: Node to check for subclass.
:param parent: Node to check for superclass.
:returns: True if child is derived from parent. False otherwise.
|
pylint/checkers/utils.py
|
def is_subclass_of(child: astroid.ClassDef, parent: astroid.ClassDef) -> bool:
"""
Check if first node is a subclass of second node.
:param child: Node to check for subclass.
:param parent: Node to check for superclass.
:returns: True if child is derived from parent. False otherwise.
"""
if not all(isinstance(node, astroid.ClassDef) for node in (child, parent)):
return False
for ancestor in child.ancestors():
try:
if astroid.helpers.is_subtype(ancestor, parent):
return True
except _NonDeducibleTypeHierarchy:
continue
return False
|
def is_subclass_of(child: astroid.ClassDef, parent: astroid.ClassDef) -> bool:
"""
Check if first node is a subclass of second node.
:param child: Node to check for subclass.
:param parent: Node to check for superclass.
:returns: True if child is derived from parent. False otherwise.
"""
if not all(isinstance(node, astroid.ClassDef) for node in (child, parent)):
return False
for ancestor in child.ancestors():
try:
if astroid.helpers.is_subtype(ancestor, parent):
return True
except _NonDeducibleTypeHierarchy:
continue
return False
|
[
"Check",
"if",
"first",
"node",
"is",
"a",
"subclass",
"of",
"second",
"node",
".",
":",
"param",
"child",
":",
"Node",
"to",
"check",
"for",
"subclass",
".",
":",
"param",
"parent",
":",
"Node",
"to",
"check",
"for",
"superclass",
".",
":",
"returns",
":",
"True",
"if",
"child",
"is",
"derived",
"from",
"parent",
".",
"False",
"otherwise",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/utils.py#L1196-L1212
|
[
"def",
"is_subclass_of",
"(",
"child",
":",
"astroid",
".",
"ClassDef",
",",
"parent",
":",
"astroid",
".",
"ClassDef",
")",
"->",
"bool",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ClassDef",
")",
"for",
"node",
"in",
"(",
"child",
",",
"parent",
")",
")",
":",
"return",
"False",
"for",
"ancestor",
"in",
"child",
".",
"ancestors",
"(",
")",
":",
"try",
":",
"if",
"astroid",
".",
"helpers",
".",
"is_subtype",
"(",
"ancestor",
",",
"parent",
")",
":",
"return",
"True",
"except",
"_NonDeducibleTypeHierarchy",
":",
"continue",
"return",
"False"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_qualified_names
|
Split the names of the given module into subparts
For example,
_qualified_names('pylint.checkers.ImportsChecker')
returns
['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker']
|
pylint/checkers/imports.py
|
def _qualified_names(modname):
"""Split the names of the given module into subparts
For example,
_qualified_names('pylint.checkers.ImportsChecker')
returns
['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker']
"""
names = modname.split(".")
return [".".join(names[0 : i + 1]) for i in range(len(names))]
|
def _qualified_names(modname):
"""Split the names of the given module into subparts
For example,
_qualified_names('pylint.checkers.ImportsChecker')
returns
['pylint', 'pylint.checkers', 'pylint.checkers.ImportsChecker']
"""
names = modname.split(".")
return [".".join(names[0 : i + 1]) for i in range(len(names))]
|
[
"Split",
"the",
"names",
"of",
"the",
"given",
"module",
"into",
"subparts"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L55-L64
|
[
"def",
"_qualified_names",
"(",
"modname",
")",
":",
"names",
"=",
"modname",
".",
"split",
"(",
"\".\"",
")",
"return",
"[",
"\".\"",
".",
"join",
"(",
"names",
"[",
"0",
":",
"i",
"+",
"1",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"names",
")",
")",
"]"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_get_import_name
|
Get a prepared module name from the given import node
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
for debugging. Otherwise, the initial module name
is returned unchanged.
|
pylint/checkers/imports.py
|
def _get_import_name(importnode, modname):
"""Get a prepared module name from the given import node
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
for debugging. Otherwise, the initial module name
is returned unchanged.
"""
if isinstance(importnode, astroid.ImportFrom):
if importnode.level:
root = importnode.root()
if isinstance(root, astroid.Module):
modname = root.relative_to_absolute_name(
modname, level=importnode.level
)
return modname
|
def _get_import_name(importnode, modname):
"""Get a prepared module name from the given import node
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
for debugging. Otherwise, the initial module name
is returned unchanged.
"""
if isinstance(importnode, astroid.ImportFrom):
if importnode.level:
root = importnode.root()
if isinstance(root, astroid.Module):
modname = root.relative_to_absolute_name(
modname, level=importnode.level
)
return modname
|
[
"Get",
"a",
"prepared",
"module",
"name",
"from",
"the",
"given",
"import",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L67-L82
|
[
"def",
"_get_import_name",
"(",
"importnode",
",",
"modname",
")",
":",
"if",
"isinstance",
"(",
"importnode",
",",
"astroid",
".",
"ImportFrom",
")",
":",
"if",
"importnode",
".",
"level",
":",
"root",
"=",
"importnode",
".",
"root",
"(",
")",
"if",
"isinstance",
"(",
"root",
",",
"astroid",
".",
"Module",
")",
":",
"modname",
"=",
"root",
".",
"relative_to_absolute_name",
"(",
"modname",
",",
"level",
"=",
"importnode",
".",
"level",
")",
"return",
"modname"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_get_first_import
|
return the node where [base.]<name> is imported or None if not found
|
pylint/checkers/imports.py
|
def _get_first_import(node, context, name, base, level, alias):
"""return the node where [base.]<name> is imported or None if not found
"""
fullname = "%s.%s" % (base, name) if base else name
first = None
found = False
for first in context.body:
if first is node:
continue
if first.scope() is node.scope() and first.fromlineno > node.fromlineno:
continue
if isinstance(first, astroid.Import):
if any(fullname == iname[0] for iname in first.names):
found = True
break
elif isinstance(first, astroid.ImportFrom):
if level == first.level:
for imported_name, imported_alias in first.names:
if fullname == "%s.%s" % (first.modname, imported_name):
found = True
break
if (
name != "*"
and name == imported_name
and not (alias or imported_alias)
):
found = True
break
if found:
break
if found and not astroid.are_exclusive(first, node):
return first
return None
|
def _get_first_import(node, context, name, base, level, alias):
"""return the node where [base.]<name> is imported or None if not found
"""
fullname = "%s.%s" % (base, name) if base else name
first = None
found = False
for first in context.body:
if first is node:
continue
if first.scope() is node.scope() and first.fromlineno > node.fromlineno:
continue
if isinstance(first, astroid.Import):
if any(fullname == iname[0] for iname in first.names):
found = True
break
elif isinstance(first, astroid.ImportFrom):
if level == first.level:
for imported_name, imported_alias in first.names:
if fullname == "%s.%s" % (first.modname, imported_name):
found = True
break
if (
name != "*"
and name == imported_name
and not (alias or imported_alias)
):
found = True
break
if found:
break
if found and not astroid.are_exclusive(first, node):
return first
return None
|
[
"return",
"the",
"node",
"where",
"[",
"base",
".",
"]",
"<name",
">",
"is",
"imported",
"or",
"None",
"if",
"not",
"found"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L85-L118
|
[
"def",
"_get_first_import",
"(",
"node",
",",
"context",
",",
"name",
",",
"base",
",",
"level",
",",
"alias",
")",
":",
"fullname",
"=",
"\"%s.%s\"",
"%",
"(",
"base",
",",
"name",
")",
"if",
"base",
"else",
"name",
"first",
"=",
"None",
"found",
"=",
"False",
"for",
"first",
"in",
"context",
".",
"body",
":",
"if",
"first",
"is",
"node",
":",
"continue",
"if",
"first",
".",
"scope",
"(",
")",
"is",
"node",
".",
"scope",
"(",
")",
"and",
"first",
".",
"fromlineno",
">",
"node",
".",
"fromlineno",
":",
"continue",
"if",
"isinstance",
"(",
"first",
",",
"astroid",
".",
"Import",
")",
":",
"if",
"any",
"(",
"fullname",
"==",
"iname",
"[",
"0",
"]",
"for",
"iname",
"in",
"first",
".",
"names",
")",
":",
"found",
"=",
"True",
"break",
"elif",
"isinstance",
"(",
"first",
",",
"astroid",
".",
"ImportFrom",
")",
":",
"if",
"level",
"==",
"first",
".",
"level",
":",
"for",
"imported_name",
",",
"imported_alias",
"in",
"first",
".",
"names",
":",
"if",
"fullname",
"==",
"\"%s.%s\"",
"%",
"(",
"first",
".",
"modname",
",",
"imported_name",
")",
":",
"found",
"=",
"True",
"break",
"if",
"(",
"name",
"!=",
"\"*\"",
"and",
"name",
"==",
"imported_name",
"and",
"not",
"(",
"alias",
"or",
"imported_alias",
")",
")",
":",
"found",
"=",
"True",
"break",
"if",
"found",
":",
"break",
"if",
"found",
"and",
"not",
"astroid",
".",
"are_exclusive",
"(",
"first",
",",
"node",
")",
":",
"return",
"first",
"return",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_make_tree_defs
|
get a list of 2-uple (module, list_of_files_which_import_this_module),
it will return a dictionary to represent this as a tree
|
pylint/checkers/imports.py
|
def _make_tree_defs(mod_files_list):
"""get a list of 2-uple (module, list_of_files_which_import_this_module),
it will return a dictionary to represent this as a tree
"""
tree_defs = {}
for mod, files in mod_files_list:
node = (tree_defs, ())
for prefix in mod.split("."):
node = node[0].setdefault(prefix, [{}, []])
node[1] += files
return tree_defs
|
def _make_tree_defs(mod_files_list):
"""get a list of 2-uple (module, list_of_files_which_import_this_module),
it will return a dictionary to represent this as a tree
"""
tree_defs = {}
for mod, files in mod_files_list:
node = (tree_defs, ())
for prefix in mod.split("."):
node = node[0].setdefault(prefix, [{}, []])
node[1] += files
return tree_defs
|
[
"get",
"a",
"list",
"of",
"2",
"-",
"uple",
"(",
"module",
"list_of_files_which_import_this_module",
")",
"it",
"will",
"return",
"a",
"dictionary",
"to",
"represent",
"this",
"as",
"a",
"tree"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L132-L142
|
[
"def",
"_make_tree_defs",
"(",
"mod_files_list",
")",
":",
"tree_defs",
"=",
"{",
"}",
"for",
"mod",
",",
"files",
"in",
"mod_files_list",
":",
"node",
"=",
"(",
"tree_defs",
",",
"(",
")",
")",
"for",
"prefix",
"in",
"mod",
".",
"split",
"(",
"\".\"",
")",
":",
"node",
"=",
"node",
"[",
"0",
"]",
".",
"setdefault",
"(",
"prefix",
",",
"[",
"{",
"}",
",",
"[",
"]",
"]",
")",
"node",
"[",
"1",
"]",
"+=",
"files",
"return",
"tree_defs"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_repr_tree_defs
|
return a string which represents imports as a tree
|
pylint/checkers/imports.py
|
def _repr_tree_defs(data, indent_str=None):
"""return a string which represents imports as a tree"""
lines = []
nodes = data.items()
for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[0])):
if not files:
files = ""
else:
files = "(%s)" % ",".join(sorted(files))
if indent_str is None:
lines.append("%s %s" % (mod, files))
sub_indent_str = " "
else:
lines.append(r"%s\-%s %s" % (indent_str, mod, files))
if i == len(nodes) - 1:
sub_indent_str = "%s " % indent_str
else:
sub_indent_str = "%s| " % indent_str
if sub:
lines.append(_repr_tree_defs(sub, sub_indent_str))
return "\n".join(lines)
|
def _repr_tree_defs(data, indent_str=None):
"""return a string which represents imports as a tree"""
lines = []
nodes = data.items()
for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[0])):
if not files:
files = ""
else:
files = "(%s)" % ",".join(sorted(files))
if indent_str is None:
lines.append("%s %s" % (mod, files))
sub_indent_str = " "
else:
lines.append(r"%s\-%s %s" % (indent_str, mod, files))
if i == len(nodes) - 1:
sub_indent_str = "%s " % indent_str
else:
sub_indent_str = "%s| " % indent_str
if sub:
lines.append(_repr_tree_defs(sub, sub_indent_str))
return "\n".join(lines)
|
[
"return",
"a",
"string",
"which",
"represents",
"imports",
"as",
"a",
"tree"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L145-L165
|
[
"def",
"_repr_tree_defs",
"(",
"data",
",",
"indent_str",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"nodes",
"=",
"data",
".",
"items",
"(",
")",
"for",
"i",
",",
"(",
"mod",
",",
"(",
"sub",
",",
"files",
")",
")",
"in",
"enumerate",
"(",
"sorted",
"(",
"nodes",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
")",
":",
"if",
"not",
"files",
":",
"files",
"=",
"\"\"",
"else",
":",
"files",
"=",
"\"(%s)\"",
"%",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"files",
")",
")",
"if",
"indent_str",
"is",
"None",
":",
"lines",
".",
"append",
"(",
"\"%s %s\"",
"%",
"(",
"mod",
",",
"files",
")",
")",
"sub_indent_str",
"=",
"\" \"",
"else",
":",
"lines",
".",
"append",
"(",
"r\"%s\\-%s %s\"",
"%",
"(",
"indent_str",
",",
"mod",
",",
"files",
")",
")",
"if",
"i",
"==",
"len",
"(",
"nodes",
")",
"-",
"1",
":",
"sub_indent_str",
"=",
"\"%s \"",
"%",
"indent_str",
"else",
":",
"sub_indent_str",
"=",
"\"%s| \"",
"%",
"indent_str",
"if",
"sub",
":",
"lines",
".",
"append",
"(",
"_repr_tree_defs",
"(",
"sub",
",",
"sub_indent_str",
")",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"lines",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_dependencies_graph
|
write dependencies as a dot (graphviz) file
|
pylint/checkers/imports.py
|
def _dependencies_graph(filename, dep_info):
"""write dependencies as a dot (graphviz) file
"""
done = {}
printer = DotBackend(filename[:-4], rankdir="LR")
printer.emit('URL="." node[shape="box"]')
for modname, dependencies in sorted(dep_info.items()):
done[modname] = 1
printer.emit_node(modname)
for depmodname in dependencies:
if depmodname not in done:
done[depmodname] = 1
printer.emit_node(depmodname)
for depmodname, dependencies in sorted(dep_info.items()):
for modname in dependencies:
printer.emit_edge(modname, depmodname)
printer.generate(filename)
|
def _dependencies_graph(filename, dep_info):
"""write dependencies as a dot (graphviz) file
"""
done = {}
printer = DotBackend(filename[:-4], rankdir="LR")
printer.emit('URL="." node[shape="box"]')
for modname, dependencies in sorted(dep_info.items()):
done[modname] = 1
printer.emit_node(modname)
for depmodname in dependencies:
if depmodname not in done:
done[depmodname] = 1
printer.emit_node(depmodname)
for depmodname, dependencies in sorted(dep_info.items()):
for modname in dependencies:
printer.emit_edge(modname, depmodname)
printer.generate(filename)
|
[
"write",
"dependencies",
"as",
"a",
"dot",
"(",
"graphviz",
")",
"file"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L168-L184
|
[
"def",
"_dependencies_graph",
"(",
"filename",
",",
"dep_info",
")",
":",
"done",
"=",
"{",
"}",
"printer",
"=",
"DotBackend",
"(",
"filename",
"[",
":",
"-",
"4",
"]",
",",
"rankdir",
"=",
"\"LR\"",
")",
"printer",
".",
"emit",
"(",
"'URL=\".\" node[shape=\"box\"]'",
")",
"for",
"modname",
",",
"dependencies",
"in",
"sorted",
"(",
"dep_info",
".",
"items",
"(",
")",
")",
":",
"done",
"[",
"modname",
"]",
"=",
"1",
"printer",
".",
"emit_node",
"(",
"modname",
")",
"for",
"depmodname",
"in",
"dependencies",
":",
"if",
"depmodname",
"not",
"in",
"done",
":",
"done",
"[",
"depmodname",
"]",
"=",
"1",
"printer",
".",
"emit_node",
"(",
"depmodname",
")",
"for",
"depmodname",
",",
"dependencies",
"in",
"sorted",
"(",
"dep_info",
".",
"items",
"(",
")",
")",
":",
"for",
"modname",
"in",
"dependencies",
":",
"printer",
".",
"emit_edge",
"(",
"modname",
",",
"depmodname",
")",
"printer",
".",
"generate",
"(",
"filename",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
_make_graph
|
generate a dependencies graph and add some information about it in the
report's section
|
pylint/checkers/imports.py
|
def _make_graph(filename, dep_info, sect, gtype):
"""generate a dependencies graph and add some information about it in the
report's section
"""
_dependencies_graph(filename, dep_info)
sect.append(Paragraph("%simports graph has been written to %s" % (gtype, filename)))
|
def _make_graph(filename, dep_info, sect, gtype):
"""generate a dependencies graph and add some information about it in the
report's section
"""
_dependencies_graph(filename, dep_info)
sect.append(Paragraph("%simports graph has been written to %s" % (gtype, filename)))
|
[
"generate",
"a",
"dependencies",
"graph",
"and",
"add",
"some",
"information",
"about",
"it",
"in",
"the",
"report",
"s",
"section"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L187-L192
|
[
"def",
"_make_graph",
"(",
"filename",
",",
"dep_info",
",",
"sect",
",",
"gtype",
")",
":",
"_dependencies_graph",
"(",
"filename",
",",
"dep_info",
")",
"sect",
".",
"append",
"(",
"Paragraph",
"(",
"\"%simports graph has been written to %s\"",
"%",
"(",
"gtype",
",",
"filename",
")",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker.open
|
called before visiting project (i.e set of modules)
|
pylint/checkers/imports.py
|
def open(self):
"""called before visiting project (i.e set of modules)"""
self.linter.add_stats(dependencies={})
self.linter.add_stats(cycles=[])
self.stats = self.linter.stats
self.import_graph = collections.defaultdict(set)
self._module_pkg = {} # mapping of modules to the pkg they belong in
self._excluded_edges = collections.defaultdict(set)
self._ignored_modules = get_global_option(self, "ignored-modules", default=[])
# Build a mapping {'module': 'preferred-module'}
self.preferred_modules = dict(
module.split(":")
for module in self.config.preferred_modules
if ":" in module
)
|
def open(self):
"""called before visiting project (i.e set of modules)"""
self.linter.add_stats(dependencies={})
self.linter.add_stats(cycles=[])
self.stats = self.linter.stats
self.import_graph = collections.defaultdict(set)
self._module_pkg = {} # mapping of modules to the pkg they belong in
self._excluded_edges = collections.defaultdict(set)
self._ignored_modules = get_global_option(self, "ignored-modules", default=[])
# Build a mapping {'module': 'preferred-module'}
self.preferred_modules = dict(
module.split(":")
for module in self.config.preferred_modules
if ":" in module
)
|
[
"called",
"before",
"visiting",
"project",
"(",
"i",
".",
"e",
"set",
"of",
"modules",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L442-L456
|
[
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"linter",
".",
"add_stats",
"(",
"dependencies",
"=",
"{",
"}",
")",
"self",
".",
"linter",
".",
"add_stats",
"(",
"cycles",
"=",
"[",
"]",
")",
"self",
".",
"stats",
"=",
"self",
".",
"linter",
".",
"stats",
"self",
".",
"import_graph",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"self",
".",
"_module_pkg",
"=",
"{",
"}",
"# mapping of modules to the pkg they belong in",
"self",
".",
"_excluded_edges",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"self",
".",
"_ignored_modules",
"=",
"get_global_option",
"(",
"self",
",",
"\"ignored-modules\"",
",",
"default",
"=",
"[",
"]",
")",
"# Build a mapping {'module': 'preferred-module'}",
"self",
".",
"preferred_modules",
"=",
"dict",
"(",
"module",
".",
"split",
"(",
"\":\"",
")",
"for",
"module",
"in",
"self",
".",
"config",
".",
"preferred_modules",
"if",
"\":\"",
"in",
"module",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker.close
|
called before visiting project (i.e set of modules)
|
pylint/checkers/imports.py
|
def close(self):
"""called before visiting project (i.e set of modules)"""
if self.linter.is_message_enabled("cyclic-import"):
graph = self._import_graph_without_ignored_edges()
vertices = list(graph)
for cycle in get_cycles(graph, vertices=vertices):
self.add_message("cyclic-import", args=" -> ".join(cycle))
|
def close(self):
"""called before visiting project (i.e set of modules)"""
if self.linter.is_message_enabled("cyclic-import"):
graph = self._import_graph_without_ignored_edges()
vertices = list(graph)
for cycle in get_cycles(graph, vertices=vertices):
self.add_message("cyclic-import", args=" -> ".join(cycle))
|
[
"called",
"before",
"visiting",
"project",
"(",
"i",
".",
"e",
"set",
"of",
"modules",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L464-L470
|
[
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"cyclic-import\"",
")",
":",
"graph",
"=",
"self",
".",
"_import_graph_without_ignored_edges",
"(",
")",
"vertices",
"=",
"list",
"(",
"graph",
")",
"for",
"cycle",
"in",
"get_cycles",
"(",
"graph",
",",
"vertices",
"=",
"vertices",
")",
":",
"self",
".",
"add_message",
"(",
"\"cyclic-import\"",
",",
"args",
"=",
"\" -> \"",
".",
"join",
"(",
"cycle",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker.visit_import
|
triggered when an import statement is seen
|
pylint/checkers/imports.py
|
def visit_import(self, node):
"""triggered when an import statement is seen"""
self._check_reimport(node)
self._check_import_as_rename(node)
modnode = node.root()
names = [name for name, _ in node.names]
if len(names) >= 2:
self.add_message("multiple-imports", args=", ".join(names), node=node)
for name in names:
self._check_deprecated_module(node, name)
self._check_preferred_module(node, name)
imported_module = self._get_imported_module(node, name)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
self._check_position(node)
if isinstance(node.scope(), astroid.Module):
self._record_import(node, imported_module)
if imported_module is None:
continue
self._check_relative_import(modnode, node, imported_module, name)
self._add_imported_module(node, imported_module.name)
|
def visit_import(self, node):
"""triggered when an import statement is seen"""
self._check_reimport(node)
self._check_import_as_rename(node)
modnode = node.root()
names = [name for name, _ in node.names]
if len(names) >= 2:
self.add_message("multiple-imports", args=", ".join(names), node=node)
for name in names:
self._check_deprecated_module(node, name)
self._check_preferred_module(node, name)
imported_module = self._get_imported_module(node, name)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
self._check_position(node)
if isinstance(node.scope(), astroid.Module):
self._record_import(node, imported_module)
if imported_module is None:
continue
self._check_relative_import(modnode, node, imported_module, name)
self._add_imported_module(node, imported_module.name)
|
[
"triggered",
"when",
"an",
"import",
"statement",
"is",
"seen"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L473-L497
|
[
"def",
"visit_import",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"_check_reimport",
"(",
"node",
")",
"self",
".",
"_check_import_as_rename",
"(",
"node",
")",
"modnode",
"=",
"node",
".",
"root",
"(",
")",
"names",
"=",
"[",
"name",
"for",
"name",
",",
"_",
"in",
"node",
".",
"names",
"]",
"if",
"len",
"(",
"names",
")",
">=",
"2",
":",
"self",
".",
"add_message",
"(",
"\"multiple-imports\"",
",",
"args",
"=",
"\", \"",
".",
"join",
"(",
"names",
")",
",",
"node",
"=",
"node",
")",
"for",
"name",
"in",
"names",
":",
"self",
".",
"_check_deprecated_module",
"(",
"node",
",",
"name",
")",
"self",
".",
"_check_preferred_module",
"(",
"node",
",",
"name",
")",
"imported_module",
"=",
"self",
".",
"_get_imported_module",
"(",
"node",
",",
"name",
")",
"if",
"isinstance",
"(",
"node",
".",
"parent",
",",
"astroid",
".",
"Module",
")",
":",
"# Allow imports nested",
"self",
".",
"_check_position",
"(",
"node",
")",
"if",
"isinstance",
"(",
"node",
".",
"scope",
"(",
")",
",",
"astroid",
".",
"Module",
")",
":",
"self",
".",
"_record_import",
"(",
"node",
",",
"imported_module",
")",
"if",
"imported_module",
"is",
"None",
":",
"continue",
"self",
".",
"_check_relative_import",
"(",
"modnode",
",",
"node",
",",
"imported_module",
",",
"name",
")",
"self",
".",
"_add_imported_module",
"(",
"node",
",",
"imported_module",
".",
"name",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker.visit_importfrom
|
triggered when a from statement is seen
|
pylint/checkers/imports.py
|
def visit_importfrom(self, node):
"""triggered when a from statement is seen"""
basename = node.modname
imported_module = self._get_imported_module(node, basename)
self._check_import_as_rename(node)
self._check_misplaced_future(node)
self._check_deprecated_module(node, basename)
self._check_preferred_module(node, basename)
self._check_wildcard_imports(node, imported_module)
self._check_same_line_imports(node)
self._check_reimport(node, basename=basename, level=node.level)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
self._check_position(node)
if isinstance(node.scope(), astroid.Module):
self._record_import(node, imported_module)
if imported_module is None:
return
modnode = node.root()
self._check_relative_import(modnode, node, imported_module, basename)
for name, _ in node.names:
if name != "*":
self._add_imported_module(node, "%s.%s" % (imported_module.name, name))
else:
self._add_imported_module(node, imported_module.name)
|
def visit_importfrom(self, node):
"""triggered when a from statement is seen"""
basename = node.modname
imported_module = self._get_imported_module(node, basename)
self._check_import_as_rename(node)
self._check_misplaced_future(node)
self._check_deprecated_module(node, basename)
self._check_preferred_module(node, basename)
self._check_wildcard_imports(node, imported_module)
self._check_same_line_imports(node)
self._check_reimport(node, basename=basename, level=node.level)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
self._check_position(node)
if isinstance(node.scope(), astroid.Module):
self._record_import(node, imported_module)
if imported_module is None:
return
modnode = node.root()
self._check_relative_import(modnode, node, imported_module, basename)
for name, _ in node.names:
if name != "*":
self._add_imported_module(node, "%s.%s" % (imported_module.name, name))
else:
self._add_imported_module(node, imported_module.name)
|
[
"triggered",
"when",
"a",
"from",
"statement",
"is",
"seen"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L500-L527
|
[
"def",
"visit_importfrom",
"(",
"self",
",",
"node",
")",
":",
"basename",
"=",
"node",
".",
"modname",
"imported_module",
"=",
"self",
".",
"_get_imported_module",
"(",
"node",
",",
"basename",
")",
"self",
".",
"_check_import_as_rename",
"(",
"node",
")",
"self",
".",
"_check_misplaced_future",
"(",
"node",
")",
"self",
".",
"_check_deprecated_module",
"(",
"node",
",",
"basename",
")",
"self",
".",
"_check_preferred_module",
"(",
"node",
",",
"basename",
")",
"self",
".",
"_check_wildcard_imports",
"(",
"node",
",",
"imported_module",
")",
"self",
".",
"_check_same_line_imports",
"(",
"node",
")",
"self",
".",
"_check_reimport",
"(",
"node",
",",
"basename",
"=",
"basename",
",",
"level",
"=",
"node",
".",
"level",
")",
"if",
"isinstance",
"(",
"node",
".",
"parent",
",",
"astroid",
".",
"Module",
")",
":",
"# Allow imports nested",
"self",
".",
"_check_position",
"(",
"node",
")",
"if",
"isinstance",
"(",
"node",
".",
"scope",
"(",
")",
",",
"astroid",
".",
"Module",
")",
":",
"self",
".",
"_record_import",
"(",
"node",
",",
"imported_module",
")",
"if",
"imported_module",
"is",
"None",
":",
"return",
"modnode",
"=",
"node",
".",
"root",
"(",
")",
"self",
".",
"_check_relative_import",
"(",
"modnode",
",",
"node",
",",
"imported_module",
",",
"basename",
")",
"for",
"name",
",",
"_",
"in",
"node",
".",
"names",
":",
"if",
"name",
"!=",
"\"*\"",
":",
"self",
".",
"_add_imported_module",
"(",
"node",
",",
"\"%s.%s\"",
"%",
"(",
"imported_module",
".",
"name",
",",
"name",
")",
")",
"else",
":",
"self",
".",
"_add_imported_module",
"(",
"node",
",",
"imported_module",
".",
"name",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_position
|
Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction
|
pylint/checkers/imports.py
|
def _check_position(self, node):
"""Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction
"""
# if a first non-import instruction has already been encountered,
# it means the import comes after it and therefore is not well placed
if self._first_non_import_node:
self.add_message("wrong-import-position", node=node, args=node.as_string())
|
def _check_position(self, node):
"""Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction
"""
# if a first non-import instruction has already been encountered,
# it means the import comes after it and therefore is not well placed
if self._first_non_import_node:
self.add_message("wrong-import-position", node=node, args=node.as_string())
|
[
"Check",
"node",
"import",
"or",
"importfrom",
"node",
"position",
"is",
"correct"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L644-L652
|
[
"def",
"_check_position",
"(",
"self",
",",
"node",
")",
":",
"# if a first non-import instruction has already been encountered,",
"# it means the import comes after it and therefore is not well placed",
"if",
"self",
".",
"_first_non_import_node",
":",
"self",
".",
"add_message",
"(",
"\"wrong-import-position\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"node",
".",
"as_string",
"(",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._record_import
|
Record the package `node` imports from
|
pylint/checkers/imports.py
|
def _record_import(self, node, importedmodnode):
"""Record the package `node` imports from"""
if isinstance(node, astroid.ImportFrom):
importedname = node.modname
else:
importedname = importedmodnode.name if importedmodnode else None
if not importedname:
importedname = node.names[0][0].split(".")[0]
if isinstance(node, astroid.ImportFrom) and (node.level or 0) >= 1:
# We need the importedname with first point to detect local package
# Example of node:
# 'from .my_package1 import MyClass1'
# the output should be '.my_package1' instead of 'my_package1'
# Example of node:
# 'from . import my_package2'
# the output should be '.my_package2' instead of '{pyfile}'
importedname = "." + importedname
self._imports_stack.append((node, importedname))
|
def _record_import(self, node, importedmodnode):
"""Record the package `node` imports from"""
if isinstance(node, astroid.ImportFrom):
importedname = node.modname
else:
importedname = importedmodnode.name if importedmodnode else None
if not importedname:
importedname = node.names[0][0].split(".")[0]
if isinstance(node, astroid.ImportFrom) and (node.level or 0) >= 1:
# We need the importedname with first point to detect local package
# Example of node:
# 'from .my_package1 import MyClass1'
# the output should be '.my_package1' instead of 'my_package1'
# Example of node:
# 'from . import my_package2'
# the output should be '.my_package2' instead of '{pyfile}'
importedname = "." + importedname
self._imports_stack.append((node, importedname))
|
[
"Record",
"the",
"package",
"node",
"imports",
"from"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L654-L673
|
[
"def",
"_record_import",
"(",
"self",
",",
"node",
",",
"importedmodnode",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ImportFrom",
")",
":",
"importedname",
"=",
"node",
".",
"modname",
"else",
":",
"importedname",
"=",
"importedmodnode",
".",
"name",
"if",
"importedmodnode",
"else",
"None",
"if",
"not",
"importedname",
":",
"importedname",
"=",
"node",
".",
"names",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ImportFrom",
")",
"and",
"(",
"node",
".",
"level",
"or",
"0",
")",
">=",
"1",
":",
"# We need the importedname with first point to detect local package",
"# Example of node:",
"# 'from .my_package1 import MyClass1'",
"# the output should be '.my_package1' instead of 'my_package1'",
"# Example of node:",
"# 'from . import my_package2'",
"# the output should be '.my_package2' instead of '{pyfile}'",
"importedname",
"=",
"\".\"",
"+",
"importedname",
"self",
".",
"_imports_stack",
".",
"append",
"(",
"(",
"node",
",",
"importedname",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_imports_order
|
Checks imports of module `node` are grouped by category
Imports must follow this order: standard, 3rd party, local
|
pylint/checkers/imports.py
|
def _check_imports_order(self, _module_node):
"""Checks imports of module `node` are grouped by category
Imports must follow this order: standard, 3rd party, local
"""
std_imports = []
third_party_imports = []
first_party_imports = []
# need of a list that holds third or first party ordered import
external_imports = []
local_imports = []
third_party_not_ignored = []
first_party_not_ignored = []
local_not_ignored = []
isort_obj = isort.SortImports(
file_contents="",
known_third_party=self.config.known_third_party,
known_standard_library=self.config.known_standard_library,
)
for node, modname in self._imports_stack:
if modname.startswith("."):
package = "." + modname.split(".")[1]
else:
package = modname.split(".")[0]
nested = not isinstance(node.parent, astroid.Module)
ignore_for_import_order = not self.linter.is_message_enabled(
"wrong-import-order", node.fromlineno
)
import_category = isort_obj.place_module(package)
node_and_package_import = (node, package)
if import_category in ("FUTURE", "STDLIB"):
std_imports.append(node_and_package_import)
wrong_import = (
third_party_not_ignored
or first_party_not_ignored
or local_not_ignored
)
if self._is_fallback_import(node, wrong_import):
continue
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'standard import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "THIRDPARTY":
third_party_imports.append(node_and_package_import)
external_imports.append(node_and_package_import)
if not nested and not ignore_for_import_order:
third_party_not_ignored.append(node_and_package_import)
wrong_import = first_party_not_ignored or local_not_ignored
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'third party import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "FIRSTPARTY":
first_party_imports.append(node_and_package_import)
external_imports.append(node_and_package_import)
if not nested and not ignore_for_import_order:
first_party_not_ignored.append(node_and_package_import)
wrong_import = local_not_ignored
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'first party import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "LOCALFOLDER":
local_imports.append((node, package))
if not nested and not ignore_for_import_order:
local_not_ignored.append((node, package))
return std_imports, external_imports, local_imports
|
def _check_imports_order(self, _module_node):
"""Checks imports of module `node` are grouped by category
Imports must follow this order: standard, 3rd party, local
"""
std_imports = []
third_party_imports = []
first_party_imports = []
# need of a list that holds third or first party ordered import
external_imports = []
local_imports = []
third_party_not_ignored = []
first_party_not_ignored = []
local_not_ignored = []
isort_obj = isort.SortImports(
file_contents="",
known_third_party=self.config.known_third_party,
known_standard_library=self.config.known_standard_library,
)
for node, modname in self._imports_stack:
if modname.startswith("."):
package = "." + modname.split(".")[1]
else:
package = modname.split(".")[0]
nested = not isinstance(node.parent, astroid.Module)
ignore_for_import_order = not self.linter.is_message_enabled(
"wrong-import-order", node.fromlineno
)
import_category = isort_obj.place_module(package)
node_and_package_import = (node, package)
if import_category in ("FUTURE", "STDLIB"):
std_imports.append(node_and_package_import)
wrong_import = (
third_party_not_ignored
or first_party_not_ignored
or local_not_ignored
)
if self._is_fallback_import(node, wrong_import):
continue
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'standard import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "THIRDPARTY":
third_party_imports.append(node_and_package_import)
external_imports.append(node_and_package_import)
if not nested and not ignore_for_import_order:
third_party_not_ignored.append(node_and_package_import)
wrong_import = first_party_not_ignored or local_not_ignored
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'third party import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "FIRSTPARTY":
first_party_imports.append(node_and_package_import)
external_imports.append(node_and_package_import)
if not nested and not ignore_for_import_order:
first_party_not_ignored.append(node_and_package_import)
wrong_import = local_not_ignored
if wrong_import and not nested:
self.add_message(
"wrong-import-order",
node=node,
args=(
'first party import "%s"' % node.as_string(),
'"%s"' % wrong_import[0][0].as_string(),
),
)
elif import_category == "LOCALFOLDER":
local_imports.append((node, package))
if not nested and not ignore_for_import_order:
local_not_ignored.append((node, package))
return std_imports, external_imports, local_imports
|
[
"Checks",
"imports",
"of",
"module",
"node",
"are",
"grouped",
"by",
"category"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L680-L762
|
[
"def",
"_check_imports_order",
"(",
"self",
",",
"_module_node",
")",
":",
"std_imports",
"=",
"[",
"]",
"third_party_imports",
"=",
"[",
"]",
"first_party_imports",
"=",
"[",
"]",
"# need of a list that holds third or first party ordered import",
"external_imports",
"=",
"[",
"]",
"local_imports",
"=",
"[",
"]",
"third_party_not_ignored",
"=",
"[",
"]",
"first_party_not_ignored",
"=",
"[",
"]",
"local_not_ignored",
"=",
"[",
"]",
"isort_obj",
"=",
"isort",
".",
"SortImports",
"(",
"file_contents",
"=",
"\"\"",
",",
"known_third_party",
"=",
"self",
".",
"config",
".",
"known_third_party",
",",
"known_standard_library",
"=",
"self",
".",
"config",
".",
"known_standard_library",
",",
")",
"for",
"node",
",",
"modname",
"in",
"self",
".",
"_imports_stack",
":",
"if",
"modname",
".",
"startswith",
"(",
"\".\"",
")",
":",
"package",
"=",
"\".\"",
"+",
"modname",
".",
"split",
"(",
"\".\"",
")",
"[",
"1",
"]",
"else",
":",
"package",
"=",
"modname",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"nested",
"=",
"not",
"isinstance",
"(",
"node",
".",
"parent",
",",
"astroid",
".",
"Module",
")",
"ignore_for_import_order",
"=",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"wrong-import-order\"",
",",
"node",
".",
"fromlineno",
")",
"import_category",
"=",
"isort_obj",
".",
"place_module",
"(",
"package",
")",
"node_and_package_import",
"=",
"(",
"node",
",",
"package",
")",
"if",
"import_category",
"in",
"(",
"\"FUTURE\"",
",",
"\"STDLIB\"",
")",
":",
"std_imports",
".",
"append",
"(",
"node_and_package_import",
")",
"wrong_import",
"=",
"(",
"third_party_not_ignored",
"or",
"first_party_not_ignored",
"or",
"local_not_ignored",
")",
"if",
"self",
".",
"_is_fallback_import",
"(",
"node",
",",
"wrong_import",
")",
":",
"continue",
"if",
"wrong_import",
"and",
"not",
"nested",
":",
"self",
".",
"add_message",
"(",
"\"wrong-import-order\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"(",
"'standard import \"%s\"'",
"%",
"node",
".",
"as_string",
"(",
")",
",",
"'\"%s\"'",
"%",
"wrong_import",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"as_string",
"(",
")",
",",
")",
",",
")",
"elif",
"import_category",
"==",
"\"THIRDPARTY\"",
":",
"third_party_imports",
".",
"append",
"(",
"node_and_package_import",
")",
"external_imports",
".",
"append",
"(",
"node_and_package_import",
")",
"if",
"not",
"nested",
"and",
"not",
"ignore_for_import_order",
":",
"third_party_not_ignored",
".",
"append",
"(",
"node_and_package_import",
")",
"wrong_import",
"=",
"first_party_not_ignored",
"or",
"local_not_ignored",
"if",
"wrong_import",
"and",
"not",
"nested",
":",
"self",
".",
"add_message",
"(",
"\"wrong-import-order\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"(",
"'third party import \"%s\"'",
"%",
"node",
".",
"as_string",
"(",
")",
",",
"'\"%s\"'",
"%",
"wrong_import",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"as_string",
"(",
")",
",",
")",
",",
")",
"elif",
"import_category",
"==",
"\"FIRSTPARTY\"",
":",
"first_party_imports",
".",
"append",
"(",
"node_and_package_import",
")",
"external_imports",
".",
"append",
"(",
"node_and_package_import",
")",
"if",
"not",
"nested",
"and",
"not",
"ignore_for_import_order",
":",
"first_party_not_ignored",
".",
"append",
"(",
"node_and_package_import",
")",
"wrong_import",
"=",
"local_not_ignored",
"if",
"wrong_import",
"and",
"not",
"nested",
":",
"self",
".",
"add_message",
"(",
"\"wrong-import-order\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"(",
"'first party import \"%s\"'",
"%",
"node",
".",
"as_string",
"(",
")",
",",
"'\"%s\"'",
"%",
"wrong_import",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"as_string",
"(",
")",
",",
")",
",",
")",
"elif",
"import_category",
"==",
"\"LOCALFOLDER\"",
":",
"local_imports",
".",
"append",
"(",
"(",
"node",
",",
"package",
")",
")",
"if",
"not",
"nested",
"and",
"not",
"ignore_for_import_order",
":",
"local_not_ignored",
".",
"append",
"(",
"(",
"node",
",",
"package",
")",
")",
"return",
"std_imports",
",",
"external_imports",
",",
"local_imports"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_relative_import
|
check relative import. node is either an Import or From node, modname
the imported module name.
|
pylint/checkers/imports.py
|
def _check_relative_import(
self, modnode, importnode, importedmodnode, importedasname
):
"""check relative import. node is either an Import or From node, modname
the imported module name.
"""
if not self.linter.is_message_enabled("relative-import"):
return None
if importedmodnode.file is None:
return False # built-in module
if modnode is importedmodnode:
return False # module importing itself
if modnode.absolute_import_activated() or getattr(importnode, "level", None):
return False
if importedmodnode.name != importedasname:
# this must be a relative import...
self.add_message(
"relative-import",
args=(importedasname, importedmodnode.name),
node=importnode,
)
return None
return None
|
def _check_relative_import(
self, modnode, importnode, importedmodnode, importedasname
):
"""check relative import. node is either an Import or From node, modname
the imported module name.
"""
if not self.linter.is_message_enabled("relative-import"):
return None
if importedmodnode.file is None:
return False # built-in module
if modnode is importedmodnode:
return False # module importing itself
if modnode.absolute_import_activated() or getattr(importnode, "level", None):
return False
if importedmodnode.name != importedasname:
# this must be a relative import...
self.add_message(
"relative-import",
args=(importedasname, importedmodnode.name),
node=importnode,
)
return None
return None
|
[
"check",
"relative",
"import",
".",
"node",
"is",
"either",
"an",
"Import",
"or",
"From",
"node",
"modname",
"the",
"imported",
"module",
"name",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L791-L813
|
[
"def",
"_check_relative_import",
"(",
"self",
",",
"modnode",
",",
"importnode",
",",
"importedmodnode",
",",
"importedasname",
")",
":",
"if",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"relative-import\"",
")",
":",
"return",
"None",
"if",
"importedmodnode",
".",
"file",
"is",
"None",
":",
"return",
"False",
"# built-in module",
"if",
"modnode",
"is",
"importedmodnode",
":",
"return",
"False",
"# module importing itself",
"if",
"modnode",
".",
"absolute_import_activated",
"(",
")",
"or",
"getattr",
"(",
"importnode",
",",
"\"level\"",
",",
"None",
")",
":",
"return",
"False",
"if",
"importedmodnode",
".",
"name",
"!=",
"importedasname",
":",
"# this must be a relative import...",
"self",
".",
"add_message",
"(",
"\"relative-import\"",
",",
"args",
"=",
"(",
"importedasname",
",",
"importedmodnode",
".",
"name",
")",
",",
"node",
"=",
"importnode",
",",
")",
"return",
"None",
"return",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._add_imported_module
|
notify an imported module, used to analyze dependencies
|
pylint/checkers/imports.py
|
def _add_imported_module(self, node, importedmodname):
"""notify an imported module, used to analyze dependencies"""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
try:
importedmodname = astroid.modutils.get_module_part(
importedmodname, module_file
)
except ImportError:
pass
if context_name == importedmodname:
self.add_message("import-self", node=node)
elif not astroid.modutils.is_standard_module(importedmodname):
# if this is not a package __init__ module
if base != "__init__" and context_name not in self._module_pkg:
# record the module's parent, or the module itself if this is
# a top level module, as the package it belongs to
self._module_pkg[context_name] = context_name.rsplit(".", 1)[0]
# handle dependencies
importedmodnames = self.stats["dependencies"].setdefault(
importedmodname, set()
)
if context_name not in importedmodnames:
importedmodnames.add(context_name)
# update import graph
self.import_graph[context_name].add(importedmodname)
if not self.linter.is_message_enabled("cyclic-import", line=node.lineno):
self._excluded_edges[context_name].add(importedmodname)
|
def _add_imported_module(self, node, importedmodname):
"""notify an imported module, used to analyze dependencies"""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
try:
importedmodname = astroid.modutils.get_module_part(
importedmodname, module_file
)
except ImportError:
pass
if context_name == importedmodname:
self.add_message("import-self", node=node)
elif not astroid.modutils.is_standard_module(importedmodname):
# if this is not a package __init__ module
if base != "__init__" and context_name not in self._module_pkg:
# record the module's parent, or the module itself if this is
# a top level module, as the package it belongs to
self._module_pkg[context_name] = context_name.rsplit(".", 1)[0]
# handle dependencies
importedmodnames = self.stats["dependencies"].setdefault(
importedmodname, set()
)
if context_name not in importedmodnames:
importedmodnames.add(context_name)
# update import graph
self.import_graph[context_name].add(importedmodname)
if not self.linter.is_message_enabled("cyclic-import", line=node.lineno):
self._excluded_edges[context_name].add(importedmodname)
|
[
"notify",
"an",
"imported",
"module",
"used",
"to",
"analyze",
"dependencies"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L815-L848
|
[
"def",
"_add_imported_module",
"(",
"self",
",",
"node",
",",
"importedmodname",
")",
":",
"module_file",
"=",
"node",
".",
"root",
"(",
")",
".",
"file",
"context_name",
"=",
"node",
".",
"root",
"(",
")",
".",
"name",
"base",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"module_file",
")",
")",
"[",
"0",
"]",
"try",
":",
"importedmodname",
"=",
"astroid",
".",
"modutils",
".",
"get_module_part",
"(",
"importedmodname",
",",
"module_file",
")",
"except",
"ImportError",
":",
"pass",
"if",
"context_name",
"==",
"importedmodname",
":",
"self",
".",
"add_message",
"(",
"\"import-self\"",
",",
"node",
"=",
"node",
")",
"elif",
"not",
"astroid",
".",
"modutils",
".",
"is_standard_module",
"(",
"importedmodname",
")",
":",
"# if this is not a package __init__ module",
"if",
"base",
"!=",
"\"__init__\"",
"and",
"context_name",
"not",
"in",
"self",
".",
"_module_pkg",
":",
"# record the module's parent, or the module itself if this is",
"# a top level module, as the package it belongs to",
"self",
".",
"_module_pkg",
"[",
"context_name",
"]",
"=",
"context_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"# handle dependencies",
"importedmodnames",
"=",
"self",
".",
"stats",
"[",
"\"dependencies\"",
"]",
".",
"setdefault",
"(",
"importedmodname",
",",
"set",
"(",
")",
")",
"if",
"context_name",
"not",
"in",
"importedmodnames",
":",
"importedmodnames",
".",
"add",
"(",
"context_name",
")",
"# update import graph",
"self",
".",
"import_graph",
"[",
"context_name",
"]",
".",
"add",
"(",
"importedmodname",
")",
"if",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"cyclic-import\"",
",",
"line",
"=",
"node",
".",
"lineno",
")",
":",
"self",
".",
"_excluded_edges",
"[",
"context_name",
"]",
".",
"add",
"(",
"importedmodname",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_deprecated_module
|
check if the module is deprecated
|
pylint/checkers/imports.py
|
def _check_deprecated_module(self, node, mod_path):
"""check if the module is deprecated"""
for mod_name in self.config.deprecated_modules:
if mod_path == mod_name or mod_path.startswith(mod_name + "."):
self.add_message("deprecated-module", node=node, args=mod_path)
|
def _check_deprecated_module(self, node, mod_path):
"""check if the module is deprecated"""
for mod_name in self.config.deprecated_modules:
if mod_path == mod_name or mod_path.startswith(mod_name + "."):
self.add_message("deprecated-module", node=node, args=mod_path)
|
[
"check",
"if",
"the",
"module",
"is",
"deprecated"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L850-L854
|
[
"def",
"_check_deprecated_module",
"(",
"self",
",",
"node",
",",
"mod_path",
")",
":",
"for",
"mod_name",
"in",
"self",
".",
"config",
".",
"deprecated_modules",
":",
"if",
"mod_path",
"==",
"mod_name",
"or",
"mod_path",
".",
"startswith",
"(",
"mod_name",
"+",
"\".\"",
")",
":",
"self",
".",
"add_message",
"(",
"\"deprecated-module\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"mod_path",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_preferred_module
|
check if the module has a preferred replacement
|
pylint/checkers/imports.py
|
def _check_preferred_module(self, node, mod_path):
"""check if the module has a preferred replacement"""
if mod_path in self.preferred_modules:
self.add_message(
"preferred-module",
node=node,
args=(self.preferred_modules[mod_path], mod_path),
)
|
def _check_preferred_module(self, node, mod_path):
"""check if the module has a preferred replacement"""
if mod_path in self.preferred_modules:
self.add_message(
"preferred-module",
node=node,
args=(self.preferred_modules[mod_path], mod_path),
)
|
[
"check",
"if",
"the",
"module",
"has",
"a",
"preferred",
"replacement"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L856-L863
|
[
"def",
"_check_preferred_module",
"(",
"self",
",",
"node",
",",
"mod_path",
")",
":",
"if",
"mod_path",
"in",
"self",
".",
"preferred_modules",
":",
"self",
".",
"add_message",
"(",
"\"preferred-module\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"(",
"self",
".",
"preferred_modules",
"[",
"mod_path",
"]",
",",
"mod_path",
")",
",",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._check_reimport
|
check if the import is necessary (i.e. not already done)
|
pylint/checkers/imports.py
|
def _check_reimport(self, node, basename=None, level=None):
"""check if the import is necessary (i.e. not already done)"""
if not self.linter.is_message_enabled("reimported"):
return
frame = node.frame()
root = node.root()
contexts = [(frame, level)]
if root is not frame:
contexts.append((root, None))
for known_context, known_level in contexts:
for name, alias in node.names:
first = _get_first_import(
node, known_context, name, basename, known_level, alias
)
if first is not None:
self.add_message(
"reimported", node=node, args=(name, first.fromlineno)
)
|
def _check_reimport(self, node, basename=None, level=None):
"""check if the import is necessary (i.e. not already done)"""
if not self.linter.is_message_enabled("reimported"):
return
frame = node.frame()
root = node.root()
contexts = [(frame, level)]
if root is not frame:
contexts.append((root, None))
for known_context, known_level in contexts:
for name, alias in node.names:
first = _get_first_import(
node, known_context, name, basename, known_level, alias
)
if first is not None:
self.add_message(
"reimported", node=node, args=(name, first.fromlineno)
)
|
[
"check",
"if",
"the",
"import",
"is",
"necessary",
"(",
"i",
".",
"e",
".",
"not",
"already",
"done",
")"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L882-L901
|
[
"def",
"_check_reimport",
"(",
"self",
",",
"node",
",",
"basename",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"reimported\"",
")",
":",
"return",
"frame",
"=",
"node",
".",
"frame",
"(",
")",
"root",
"=",
"node",
".",
"root",
"(",
")",
"contexts",
"=",
"[",
"(",
"frame",
",",
"level",
")",
"]",
"if",
"root",
"is",
"not",
"frame",
":",
"contexts",
".",
"append",
"(",
"(",
"root",
",",
"None",
")",
")",
"for",
"known_context",
",",
"known_level",
"in",
"contexts",
":",
"for",
"name",
",",
"alias",
"in",
"node",
".",
"names",
":",
"first",
"=",
"_get_first_import",
"(",
"node",
",",
"known_context",
",",
"name",
",",
"basename",
",",
"known_level",
",",
"alias",
")",
"if",
"first",
"is",
"not",
"None",
":",
"self",
".",
"add_message",
"(",
"\"reimported\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"(",
"name",
",",
"first",
".",
"fromlineno",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._report_external_dependencies
|
return a verbatim layout for displaying dependencies
|
pylint/checkers/imports.py
|
def _report_external_dependencies(self, sect, _, _dummy):
"""return a verbatim layout for displaying dependencies"""
dep_info = _make_tree_defs(self._external_dependencies_info().items())
if not dep_info:
raise EmptyReportError()
tree_str = _repr_tree_defs(dep_info)
sect.append(VerbatimText(tree_str))
|
def _report_external_dependencies(self, sect, _, _dummy):
"""return a verbatim layout for displaying dependencies"""
dep_info = _make_tree_defs(self._external_dependencies_info().items())
if not dep_info:
raise EmptyReportError()
tree_str = _repr_tree_defs(dep_info)
sect.append(VerbatimText(tree_str))
|
[
"return",
"a",
"verbatim",
"layout",
"for",
"displaying",
"dependencies"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L903-L909
|
[
"def",
"_report_external_dependencies",
"(",
"self",
",",
"sect",
",",
"_",
",",
"_dummy",
")",
":",
"dep_info",
"=",
"_make_tree_defs",
"(",
"self",
".",
"_external_dependencies_info",
"(",
")",
".",
"items",
"(",
")",
")",
"if",
"not",
"dep_info",
":",
"raise",
"EmptyReportError",
"(",
")",
"tree_str",
"=",
"_repr_tree_defs",
"(",
"dep_info",
")",
"sect",
".",
"append",
"(",
"VerbatimText",
"(",
"tree_str",
")",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._report_dependencies_graph
|
write dependencies as a dot (graphviz) file
|
pylint/checkers/imports.py
|
def _report_dependencies_graph(self, sect, _, _dummy):
"""write dependencies as a dot (graphviz) file"""
dep_info = self.stats["dependencies"]
if not dep_info or not (
self.config.import_graph
or self.config.ext_import_graph
or self.config.int_import_graph
):
raise EmptyReportError()
filename = self.config.import_graph
if filename:
_make_graph(filename, dep_info, sect, "")
filename = self.config.ext_import_graph
if filename:
_make_graph(filename, self._external_dependencies_info(), sect, "external ")
filename = self.config.int_import_graph
if filename:
_make_graph(filename, self._internal_dependencies_info(), sect, "internal ")
|
def _report_dependencies_graph(self, sect, _, _dummy):
"""write dependencies as a dot (graphviz) file"""
dep_info = self.stats["dependencies"]
if not dep_info or not (
self.config.import_graph
or self.config.ext_import_graph
or self.config.int_import_graph
):
raise EmptyReportError()
filename = self.config.import_graph
if filename:
_make_graph(filename, dep_info, sect, "")
filename = self.config.ext_import_graph
if filename:
_make_graph(filename, self._external_dependencies_info(), sect, "external ")
filename = self.config.int_import_graph
if filename:
_make_graph(filename, self._internal_dependencies_info(), sect, "internal ")
|
[
"write",
"dependencies",
"as",
"a",
"dot",
"(",
"graphviz",
")",
"file"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L911-L928
|
[
"def",
"_report_dependencies_graph",
"(",
"self",
",",
"sect",
",",
"_",
",",
"_dummy",
")",
":",
"dep_info",
"=",
"self",
".",
"stats",
"[",
"\"dependencies\"",
"]",
"if",
"not",
"dep_info",
"or",
"not",
"(",
"self",
".",
"config",
".",
"import_graph",
"or",
"self",
".",
"config",
".",
"ext_import_graph",
"or",
"self",
".",
"config",
".",
"int_import_graph",
")",
":",
"raise",
"EmptyReportError",
"(",
")",
"filename",
"=",
"self",
".",
"config",
".",
"import_graph",
"if",
"filename",
":",
"_make_graph",
"(",
"filename",
",",
"dep_info",
",",
"sect",
",",
"\"\"",
")",
"filename",
"=",
"self",
".",
"config",
".",
"ext_import_graph",
"if",
"filename",
":",
"_make_graph",
"(",
"filename",
",",
"self",
".",
"_external_dependencies_info",
"(",
")",
",",
"sect",
",",
"\"external \"",
")",
"filename",
"=",
"self",
".",
"config",
".",
"int_import_graph",
"if",
"filename",
":",
"_make_graph",
"(",
"filename",
",",
"self",
".",
"_internal_dependencies_info",
"(",
")",
",",
"sect",
",",
"\"internal \"",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ImportsChecker._filter_dependencies_graph
|
build the internal or the external depedency graph
|
pylint/checkers/imports.py
|
def _filter_dependencies_graph(self, internal):
"""build the internal or the external depedency graph"""
graph = collections.defaultdict(set)
for importee, importers in self.stats["dependencies"].items():
for importer in importers:
package = self._module_pkg.get(importer, importer)
is_inside = importee.startswith(package)
if is_inside and internal or not is_inside and not internal:
graph[importee].add(importer)
return graph
|
def _filter_dependencies_graph(self, internal):
"""build the internal or the external depedency graph"""
graph = collections.defaultdict(set)
for importee, importers in self.stats["dependencies"].items():
for importer in importers:
package = self._module_pkg.get(importer, importer)
is_inside = importee.startswith(package)
if is_inside and internal or not is_inside and not internal:
graph[importee].add(importer)
return graph
|
[
"build",
"the",
"internal",
"or",
"the",
"external",
"depedency",
"graph"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L930-L939
|
[
"def",
"_filter_dependencies_graph",
"(",
"self",
",",
"internal",
")",
":",
"graph",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"for",
"importee",
",",
"importers",
"in",
"self",
".",
"stats",
"[",
"\"dependencies\"",
"]",
".",
"items",
"(",
")",
":",
"for",
"importer",
"in",
"importers",
":",
"package",
"=",
"self",
".",
"_module_pkg",
".",
"get",
"(",
"importer",
",",
"importer",
")",
"is_inside",
"=",
"importee",
".",
"startswith",
"(",
"package",
")",
"if",
"is_inside",
"and",
"internal",
"or",
"not",
"is_inside",
"and",
"not",
"internal",
":",
"graph",
"[",
"importee",
"]",
".",
"add",
"(",
"importer",
")",
"return",
"graph"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_default_options
|
Read config file and return list of options
|
pylint/pyreverse/utils.py
|
def get_default_options():
"""
Read config file and return list of options
"""
options = []
home = os.environ.get("HOME", "")
if home:
rcfile = os.path.join(home, RCFILE)
try:
options = open(rcfile).read().split()
except IOError:
pass # ignore if no config file found
return options
|
def get_default_options():
"""
Read config file and return list of options
"""
options = []
home = os.environ.get("HOME", "")
if home:
rcfile = os.path.join(home, RCFILE)
try:
options = open(rcfile).read().split()
except IOError:
pass # ignore if no config file found
return options
|
[
"Read",
"config",
"file",
"and",
"return",
"list",
"of",
"options"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L27-L39
|
[
"def",
"get_default_options",
"(",
")",
":",
"options",
"=",
"[",
"]",
"home",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"HOME\"",
",",
"\"\"",
")",
"if",
"home",
":",
"rcfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"RCFILE",
")",
"try",
":",
"options",
"=",
"open",
"(",
"rcfile",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
")",
"except",
"IOError",
":",
"pass",
"# ignore if no config file found",
"return",
"options"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
insert_default_options
|
insert default options to sys.argv
|
pylint/pyreverse/utils.py
|
def insert_default_options():
"""insert default options to sys.argv
"""
options = get_default_options()
options.reverse()
for arg in options:
sys.argv.insert(1, arg)
|
def insert_default_options():
"""insert default options to sys.argv
"""
options = get_default_options()
options.reverse()
for arg in options:
sys.argv.insert(1, arg)
|
[
"insert",
"default",
"options",
"to",
"sys",
".",
"argv"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L42-L48
|
[
"def",
"insert_default_options",
"(",
")",
":",
"options",
"=",
"get_default_options",
"(",
")",
"options",
".",
"reverse",
"(",
")",
"for",
"arg",
"in",
"options",
":",
"sys",
".",
"argv",
".",
"insert",
"(",
"1",
",",
"arg",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
get_visibility
|
return the visibility from a name: public, protected, private or special
|
pylint/pyreverse/utils.py
|
def get_visibility(name):
"""return the visibility from a name: public, protected, private or special
"""
if SPECIAL.match(name):
visibility = "special"
elif PRIVATE.match(name):
visibility = "private"
elif PROTECTED.match(name):
visibility = "protected"
else:
visibility = "public"
return visibility
|
def get_visibility(name):
"""return the visibility from a name: public, protected, private or special
"""
if SPECIAL.match(name):
visibility = "special"
elif PRIVATE.match(name):
visibility = "private"
elif PROTECTED.match(name):
visibility = "protected"
else:
visibility = "public"
return visibility
|
[
"return",
"the",
"visibility",
"from",
"a",
"name",
":",
"public",
"protected",
"private",
"or",
"special"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L58-L70
|
[
"def",
"get_visibility",
"(",
"name",
")",
":",
"if",
"SPECIAL",
".",
"match",
"(",
"name",
")",
":",
"visibility",
"=",
"\"special\"",
"elif",
"PRIVATE",
".",
"match",
"(",
"name",
")",
":",
"visibility",
"=",
"\"private\"",
"elif",
"PROTECTED",
".",
"match",
"(",
"name",
")",
":",
"visibility",
"=",
"\"protected\"",
"else",
":",
"visibility",
"=",
"\"public\"",
"return",
"visibility"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
FilterMixIn.show_attr
|
return true if the node should be treated
|
pylint/pyreverse/utils.py
|
def show_attr(self, node):
"""return true if the node should be treated
"""
visibility = get_visibility(getattr(node, "name", node))
return not self.__mode & VIS_MOD[visibility]
|
def show_attr(self, node):
"""return true if the node should be treated
"""
visibility = get_visibility(getattr(node, "name", node))
return not self.__mode & VIS_MOD[visibility]
|
[
"return",
"true",
"if",
"the",
"node",
"should",
"be",
"treated"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L135-L139
|
[
"def",
"show_attr",
"(",
"self",
",",
"node",
")",
":",
"visibility",
"=",
"get_visibility",
"(",
"getattr",
"(",
"node",
",",
"\"name\"",
",",
"node",
")",
")",
"return",
"not",
"self",
".",
"__mode",
"&",
"VIS_MOD",
"[",
"visibility",
"]"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ASTWalker.walk
|
walk on the tree from <node>, getting callbacks from handler
|
pylint/pyreverse/utils.py
|
def walk(self, node, _done=None):
"""walk on the tree from <node>, getting callbacks from handler"""
if _done is None:
_done = set()
if node in _done:
raise AssertionError((id(node), node, node.parent))
_done.add(node)
self.visit(node)
for child_node in node.get_children():
assert child_node is not node
self.walk(child_node, _done)
self.leave(node)
assert node.parent is not node
|
def walk(self, node, _done=None):
"""walk on the tree from <node>, getting callbacks from handler"""
if _done is None:
_done = set()
if node in _done:
raise AssertionError((id(node), node, node.parent))
_done.add(node)
self.visit(node)
for child_node in node.get_children():
assert child_node is not node
self.walk(child_node, _done)
self.leave(node)
assert node.parent is not node
|
[
"walk",
"on",
"the",
"tree",
"from",
"<node",
">",
"getting",
"callbacks",
"from",
"handler"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L156-L168
|
[
"def",
"walk",
"(",
"self",
",",
"node",
",",
"_done",
"=",
"None",
")",
":",
"if",
"_done",
"is",
"None",
":",
"_done",
"=",
"set",
"(",
")",
"if",
"node",
"in",
"_done",
":",
"raise",
"AssertionError",
"(",
"(",
"id",
"(",
"node",
")",
",",
"node",
",",
"node",
".",
"parent",
")",
")",
"_done",
".",
"add",
"(",
"node",
")",
"self",
".",
"visit",
"(",
"node",
")",
"for",
"child_node",
"in",
"node",
".",
"get_children",
"(",
")",
":",
"assert",
"child_node",
"is",
"not",
"node",
"self",
".",
"walk",
"(",
"child_node",
",",
"_done",
")",
"self",
".",
"leave",
"(",
"node",
")",
"assert",
"node",
".",
"parent",
"is",
"not",
"node"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ASTWalker.get_callbacks
|
get callbacks from handler for the visited node
|
pylint/pyreverse/utils.py
|
def get_callbacks(self, node):
"""get callbacks from handler for the visited node"""
klass = node.__class__
methods = self._cache.get(klass)
if methods is None:
handler = self.handler
kid = klass.__name__.lower()
e_method = getattr(
handler, "visit_%s" % kid, getattr(handler, "visit_default", None)
)
l_method = getattr(
handler, "leave_%s" % kid, getattr(handler, "leave_default", None)
)
self._cache[klass] = (e_method, l_method)
else:
e_method, l_method = methods
return e_method, l_method
|
def get_callbacks(self, node):
"""get callbacks from handler for the visited node"""
klass = node.__class__
methods = self._cache.get(klass)
if methods is None:
handler = self.handler
kid = klass.__name__.lower()
e_method = getattr(
handler, "visit_%s" % kid, getattr(handler, "visit_default", None)
)
l_method = getattr(
handler, "leave_%s" % kid, getattr(handler, "leave_default", None)
)
self._cache[klass] = (e_method, l_method)
else:
e_method, l_method = methods
return e_method, l_method
|
[
"get",
"callbacks",
"from",
"handler",
"for",
"the",
"visited",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L170-L186
|
[
"def",
"get_callbacks",
"(",
"self",
",",
"node",
")",
":",
"klass",
"=",
"node",
".",
"__class__",
"methods",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"klass",
")",
"if",
"methods",
"is",
"None",
":",
"handler",
"=",
"self",
".",
"handler",
"kid",
"=",
"klass",
".",
"__name__",
".",
"lower",
"(",
")",
"e_method",
"=",
"getattr",
"(",
"handler",
",",
"\"visit_%s\"",
"%",
"kid",
",",
"getattr",
"(",
"handler",
",",
"\"visit_default\"",
",",
"None",
")",
")",
"l_method",
"=",
"getattr",
"(",
"handler",
",",
"\"leave_%s\"",
"%",
"kid",
",",
"getattr",
"(",
"handler",
",",
"\"leave_default\"",
",",
"None",
")",
")",
"self",
".",
"_cache",
"[",
"klass",
"]",
"=",
"(",
"e_method",
",",
"l_method",
")",
"else",
":",
"e_method",
",",
"l_method",
"=",
"methods",
"return",
"e_method",
",",
"l_method"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ASTWalker.visit
|
walk on the tree from <node>, getting callbacks from handler
|
pylint/pyreverse/utils.py
|
def visit(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[0]
if method is not None:
method(node)
|
def visit(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[0]
if method is not None:
method(node)
|
[
"walk",
"on",
"the",
"tree",
"from",
"<node",
">",
"getting",
"callbacks",
"from",
"handler"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L188-L192
|
[
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"[",
"0",
"]",
"if",
"method",
"is",
"not",
"None",
":",
"method",
"(",
"node",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
ASTWalker.leave
|
walk on the tree from <node>, getting callbacks from handler
|
pylint/pyreverse/utils.py
|
def leave(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[1]
if method is not None:
method(node)
|
def leave(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[1]
if method is not None:
method(node)
|
[
"walk",
"on",
"the",
"tree",
"from",
"<node",
">",
"getting",
"callbacks",
"from",
"handler"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L194-L198
|
[
"def",
"leave",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"[",
"1",
"]",
"if",
"method",
"is",
"not",
"None",
":",
"method",
"(",
"node",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
LocalsVisitor.visit
|
launch the visit starting from the given node
|
pylint/pyreverse/utils.py
|
def visit(self, node):
"""launch the visit starting from the given node"""
if node in self._visited:
return None
self._visited[node] = 1 # FIXME: use set ?
methods = self.get_callbacks(node)
if methods[0] is not None:
methods[0](node)
if hasattr(node, "locals"): # skip Instance and other proxy
for local_node in node.values():
self.visit(local_node)
if methods[1] is not None:
return methods[1](node)
return None
|
def visit(self, node):
"""launch the visit starting from the given node"""
if node in self._visited:
return None
self._visited[node] = 1 # FIXME: use set ?
methods = self.get_callbacks(node)
if methods[0] is not None:
methods[0](node)
if hasattr(node, "locals"): # skip Instance and other proxy
for local_node in node.values():
self.visit(local_node)
if methods[1] is not None:
return methods[1](node)
return None
|
[
"launch",
"the",
"visit",
"starting",
"from",
"the",
"given",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/utils.py#L208-L221
|
[
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"in",
"self",
".",
"_visited",
":",
"return",
"None",
"self",
".",
"_visited",
"[",
"node",
"]",
"=",
"1",
"# FIXME: use set ?",
"methods",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"if",
"methods",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"methods",
"[",
"0",
"]",
"(",
"node",
")",
"if",
"hasattr",
"(",
"node",
",",
"\"locals\"",
")",
":",
"# skip Instance and other proxy",
"for",
"local_node",
"in",
"node",
".",
"values",
"(",
")",
":",
"self",
".",
"visit",
"(",
"local_node",
")",
"if",
"methods",
"[",
"1",
"]",
"is",
"not",
"None",
":",
"return",
"methods",
"[",
"1",
"]",
"(",
"node",
")",
"return",
"None"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
BaseChecker.check_consistency
|
Check the consistency of msgid.
msg ids for a checker should be a string of len 4, where the two first
characters are the checker id and the two last the msg id in this
checker.
:raises InvalidMessageError: If the checker id in the messages are not
always the same.
|
pylint/checkers/base_checker.py
|
def check_consistency(self) -> None:
"""Check the consistency of msgid.
msg ids for a checker should be a string of len 4, where the two first
characters are the checker id and the two last the msg id in this
checker.
:raises InvalidMessageError: If the checker id in the messages are not
always the same. """
checker_id = None
existing_ids = []
for message in self.messages:
if checker_id is not None and checker_id != message.msgid[1:3]:
error_msg = "Inconsistent checker part in message id "
error_msg += "'{}' (expected 'x{checker_id}xx' ".format(
message.msgid, checker_id=checker_id
)
error_msg += "because we already had {existing_ids}).".format(
existing_ids=existing_ids
)
raise InvalidMessageError(error_msg)
checker_id = message.msgid[1:3]
existing_ids.append(message.msgid)
|
def check_consistency(self) -> None:
"""Check the consistency of msgid.
msg ids for a checker should be a string of len 4, where the two first
characters are the checker id and the two last the msg id in this
checker.
:raises InvalidMessageError: If the checker id in the messages are not
always the same. """
checker_id = None
existing_ids = []
for message in self.messages:
if checker_id is not None and checker_id != message.msgid[1:3]:
error_msg = "Inconsistent checker part in message id "
error_msg += "'{}' (expected 'x{checker_id}xx' ".format(
message.msgid, checker_id=checker_id
)
error_msg += "because we already had {existing_ids}).".format(
existing_ids=existing_ids
)
raise InvalidMessageError(error_msg)
checker_id = message.msgid[1:3]
existing_ids.append(message.msgid)
|
[
"Check",
"the",
"consistency",
"of",
"msgid",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base_checker.py#L57-L79
|
[
"def",
"check_consistency",
"(",
"self",
")",
"->",
"None",
":",
"checker_id",
"=",
"None",
"existing_ids",
"=",
"[",
"]",
"for",
"message",
"in",
"self",
".",
"messages",
":",
"if",
"checker_id",
"is",
"not",
"None",
"and",
"checker_id",
"!=",
"message",
".",
"msgid",
"[",
"1",
":",
"3",
"]",
":",
"error_msg",
"=",
"\"Inconsistent checker part in message id \"",
"error_msg",
"+=",
"\"'{}' (expected 'x{checker_id}xx' \"",
".",
"format",
"(",
"message",
".",
"msgid",
",",
"checker_id",
"=",
"checker_id",
")",
"error_msg",
"+=",
"\"because we already had {existing_ids}).\"",
".",
"format",
"(",
"existing_ids",
"=",
"existing_ids",
")",
"raise",
"InvalidMessageError",
"(",
"error_msg",
")",
"checker_id",
"=",
"message",
".",
"msgid",
"[",
"1",
":",
"3",
"]",
"existing_ids",
".",
"append",
"(",
"message",
".",
"msgid",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
StdlibChecker.visit_call
|
Visit a Call node.
|
pylint/checkers/stdlib.py
|
def visit_call(self, node):
"""Visit a Call node."""
try:
for inferred in node.func.infer():
if inferred is astroid.Uninferable:
continue
elif inferred.root().name == OPEN_MODULE:
if getattr(node.func, "name", None) in OPEN_FILES:
self._check_open_mode(node)
elif inferred.root().name == UNITTEST_CASE:
self._check_redundant_assert(node, inferred)
elif isinstance(inferred, astroid.ClassDef):
if inferred.qname() == THREADING_THREAD:
self._check_bad_thread_instantiation(node)
elif inferred.qname() == SUBPROCESS_POPEN:
self._check_for_preexec_fn_in_popen(node)
elif isinstance(inferred, astroid.FunctionDef):
name = inferred.qname()
if name == COPY_COPY:
self._check_shallow_copy_environ(node)
elif name in ENV_GETTERS:
self._check_env_function(node, inferred)
elif name == SUBPROCESS_RUN and PY35:
self._check_for_check_kw_in_run(node)
self._check_deprecated_method(node, inferred)
except astroid.InferenceError:
return
|
def visit_call(self, node):
"""Visit a Call node."""
try:
for inferred in node.func.infer():
if inferred is astroid.Uninferable:
continue
elif inferred.root().name == OPEN_MODULE:
if getattr(node.func, "name", None) in OPEN_FILES:
self._check_open_mode(node)
elif inferred.root().name == UNITTEST_CASE:
self._check_redundant_assert(node, inferred)
elif isinstance(inferred, astroid.ClassDef):
if inferred.qname() == THREADING_THREAD:
self._check_bad_thread_instantiation(node)
elif inferred.qname() == SUBPROCESS_POPEN:
self._check_for_preexec_fn_in_popen(node)
elif isinstance(inferred, astroid.FunctionDef):
name = inferred.qname()
if name == COPY_COPY:
self._check_shallow_copy_environ(node)
elif name in ENV_GETTERS:
self._check_env_function(node, inferred)
elif name == SUBPROCESS_RUN and PY35:
self._check_for_check_kw_in_run(node)
self._check_deprecated_method(node, inferred)
except astroid.InferenceError:
return
|
[
"Visit",
"a",
"Call",
"node",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/stdlib.py#L286-L312
|
[
"def",
"visit_call",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"for",
"inferred",
"in",
"node",
".",
"func",
".",
"infer",
"(",
")",
":",
"if",
"inferred",
"is",
"astroid",
".",
"Uninferable",
":",
"continue",
"elif",
"inferred",
".",
"root",
"(",
")",
".",
"name",
"==",
"OPEN_MODULE",
":",
"if",
"getattr",
"(",
"node",
".",
"func",
",",
"\"name\"",
",",
"None",
")",
"in",
"OPEN_FILES",
":",
"self",
".",
"_check_open_mode",
"(",
"node",
")",
"elif",
"inferred",
".",
"root",
"(",
")",
".",
"name",
"==",
"UNITTEST_CASE",
":",
"self",
".",
"_check_redundant_assert",
"(",
"node",
",",
"inferred",
")",
"elif",
"isinstance",
"(",
"inferred",
",",
"astroid",
".",
"ClassDef",
")",
":",
"if",
"inferred",
".",
"qname",
"(",
")",
"==",
"THREADING_THREAD",
":",
"self",
".",
"_check_bad_thread_instantiation",
"(",
"node",
")",
"elif",
"inferred",
".",
"qname",
"(",
")",
"==",
"SUBPROCESS_POPEN",
":",
"self",
".",
"_check_for_preexec_fn_in_popen",
"(",
"node",
")",
"elif",
"isinstance",
"(",
"inferred",
",",
"astroid",
".",
"FunctionDef",
")",
":",
"name",
"=",
"inferred",
".",
"qname",
"(",
")",
"if",
"name",
"==",
"COPY_COPY",
":",
"self",
".",
"_check_shallow_copy_environ",
"(",
"node",
")",
"elif",
"name",
"in",
"ENV_GETTERS",
":",
"self",
".",
"_check_env_function",
"(",
"node",
",",
"inferred",
")",
"elif",
"name",
"==",
"SUBPROCESS_RUN",
"and",
"PY35",
":",
"self",
".",
"_check_for_check_kw_in_run",
"(",
"node",
")",
"self",
".",
"_check_deprecated_method",
"(",
"node",
",",
"inferred",
")",
"except",
"astroid",
".",
"InferenceError",
":",
"return"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
StdlibChecker._check_datetime
|
Check that a datetime was infered.
If so, emit boolean-datetime warning.
|
pylint/checkers/stdlib.py
|
def _check_datetime(self, node):
""" Check that a datetime was infered.
If so, emit boolean-datetime warning.
"""
try:
infered = next(node.infer())
except astroid.InferenceError:
return
if isinstance(infered, Instance) and infered.qname() == "datetime.time":
self.add_message("boolean-datetime", node=node)
|
def _check_datetime(self, node):
""" Check that a datetime was infered.
If so, emit boolean-datetime warning.
"""
try:
infered = next(node.infer())
except astroid.InferenceError:
return
if isinstance(infered, Instance) and infered.qname() == "datetime.time":
self.add_message("boolean-datetime", node=node)
|
[
"Check",
"that",
"a",
"datetime",
"was",
"infered",
".",
"If",
"so",
"emit",
"boolean",
"-",
"datetime",
"warning",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/stdlib.py#L376-L385
|
[
"def",
"_check_datetime",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"infered",
"=",
"next",
"(",
"node",
".",
"infer",
"(",
")",
")",
"except",
"astroid",
".",
"InferenceError",
":",
"return",
"if",
"isinstance",
"(",
"infered",
",",
"Instance",
")",
"and",
"infered",
".",
"qname",
"(",
")",
"==",
"\"datetime.time\"",
":",
"self",
".",
"add_message",
"(",
"\"boolean-datetime\"",
",",
"node",
"=",
"node",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
StdlibChecker._check_open_mode
|
Check that the mode argument of an open or file call is valid.
|
pylint/checkers/stdlib.py
|
def _check_open_mode(self, node):
"""Check that the mode argument of an open or file call is valid."""
try:
mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode")
except utils.NoSuchArgumentError:
return
if mode_arg:
mode_arg = utils.safe_infer(mode_arg)
if isinstance(mode_arg, astroid.Const) and not _check_mode_str(
mode_arg.value
):
self.add_message("bad-open-mode", node=node, args=mode_arg.value)
|
def _check_open_mode(self, node):
"""Check that the mode argument of an open or file call is valid."""
try:
mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode")
except utils.NoSuchArgumentError:
return
if mode_arg:
mode_arg = utils.safe_infer(mode_arg)
if isinstance(mode_arg, astroid.Const) and not _check_mode_str(
mode_arg.value
):
self.add_message("bad-open-mode", node=node, args=mode_arg.value)
|
[
"Check",
"that",
"the",
"mode",
"argument",
"of",
"an",
"open",
"or",
"file",
"call",
"is",
"valid",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/stdlib.py#L387-L398
|
[
"def",
"_check_open_mode",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"mode_arg",
"=",
"utils",
".",
"get_argument_from_call",
"(",
"node",
",",
"position",
"=",
"1",
",",
"keyword",
"=",
"\"mode\"",
")",
"except",
"utils",
".",
"NoSuchArgumentError",
":",
"return",
"if",
"mode_arg",
":",
"mode_arg",
"=",
"utils",
".",
"safe_infer",
"(",
"mode_arg",
")",
"if",
"isinstance",
"(",
"mode_arg",
",",
"astroid",
".",
"Const",
")",
"and",
"not",
"_check_mode_str",
"(",
"mode_arg",
".",
"value",
")",
":",
"self",
".",
"add_message",
"(",
"\"bad-open-mode\"",
",",
"node",
"=",
"node",
",",
"args",
"=",
"mode_arg",
".",
"value",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
JSONReporter.handle_message
|
Manage message of different type and in the context of path.
|
pylint/reporters/json_reporter.py
|
def handle_message(self, msg):
"""Manage message of different type and in the context of path."""
self.messages.append(
{
"type": msg.category,
"module": msg.module,
"obj": msg.obj,
"line": msg.line,
"column": msg.column,
"path": msg.path,
"symbol": msg.symbol,
"message": html.escape(msg.msg or "", quote=False),
"message-id": msg.msg_id,
}
)
|
def handle_message(self, msg):
"""Manage message of different type and in the context of path."""
self.messages.append(
{
"type": msg.category,
"module": msg.module,
"obj": msg.obj,
"line": msg.line,
"column": msg.column,
"path": msg.path,
"symbol": msg.symbol,
"message": html.escape(msg.msg or "", quote=False),
"message-id": msg.msg_id,
}
)
|
[
"Manage",
"message",
"of",
"different",
"type",
"and",
"in",
"the",
"context",
"of",
"path",
"."
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/reporters/json_reporter.py#L31-L45
|
[
"def",
"handle_message",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"messages",
".",
"append",
"(",
"{",
"\"type\"",
":",
"msg",
".",
"category",
",",
"\"module\"",
":",
"msg",
".",
"module",
",",
"\"obj\"",
":",
"msg",
".",
"obj",
",",
"\"line\"",
":",
"msg",
".",
"line",
",",
"\"column\"",
":",
"msg",
".",
"column",
",",
"\"path\"",
":",
"msg",
".",
"path",
",",
"\"symbol\"",
":",
"msg",
".",
"symbol",
",",
"\"message\"",
":",
"html",
".",
"escape",
"(",
"msg",
".",
"msg",
"or",
"\"\"",
",",
"quote",
"=",
"False",
")",
",",
"\"message-id\"",
":",
"msg",
".",
"msg_id",
",",
"}",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
JSONReporter.display_messages
|
Launch layouts display
|
pylint/reporters/json_reporter.py
|
def display_messages(self, layout):
"""Launch layouts display"""
print(json.dumps(self.messages, indent=4), file=self.out)
|
def display_messages(self, layout):
"""Launch layouts display"""
print(json.dumps(self.messages, indent=4), file=self.out)
|
[
"Launch",
"layouts",
"display"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/reporters/json_reporter.py#L47-L49
|
[
"def",
"display_messages",
"(",
"self",
",",
"layout",
")",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"messages",
",",
"indent",
"=",
"4",
")",
",",
"file",
"=",
"self",
".",
"out",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.get_title
|
get title for objects
|
pylint/pyreverse/diadefslib.py
|
def get_title(self, node):
"""get title for objects"""
title = node.name
if self.module_names:
title = "%s.%s" % (node.root().name, title)
return title
|
def get_title(self, node):
"""get title for objects"""
title = node.name
if self.module_names:
title = "%s.%s" % (node.root().name, title)
return title
|
[
"get",
"title",
"for",
"objects"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L40-L45
|
[
"def",
"get_title",
"(",
"self",
",",
"node",
")",
":",
"title",
"=",
"node",
".",
"name",
"if",
"self",
".",
"module_names",
":",
"title",
"=",
"\"%s.%s\"",
"%",
"(",
"node",
".",
"root",
"(",
")",
".",
"name",
",",
"title",
")",
"return",
"title"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator._set_default_options
|
set different default options with _default dictionary
|
pylint/pyreverse/diadefslib.py
|
def _set_default_options(self):
"""set different default options with _default dictionary"""
self.module_names = self._set_option(self.config.module_names)
all_ancestors = self._set_option(self.config.all_ancestors)
all_associated = self._set_option(self.config.all_associated)
anc_level, association_level = (0, 0)
if all_ancestors:
anc_level = -1
if all_associated:
association_level = -1
if self.config.show_ancestors is not None:
anc_level = self.config.show_ancestors
if self.config.show_associated is not None:
association_level = self.config.show_associated
self.anc_level, self.association_level = anc_level, association_level
|
def _set_default_options(self):
"""set different default options with _default dictionary"""
self.module_names = self._set_option(self.config.module_names)
all_ancestors = self._set_option(self.config.all_ancestors)
all_associated = self._set_option(self.config.all_associated)
anc_level, association_level = (0, 0)
if all_ancestors:
anc_level = -1
if all_associated:
association_level = -1
if self.config.show_ancestors is not None:
anc_level = self.config.show_ancestors
if self.config.show_associated is not None:
association_level = self.config.show_associated
self.anc_level, self.association_level = anc_level, association_level
|
[
"set",
"different",
"default",
"options",
"with",
"_default",
"dictionary"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L55-L69
|
[
"def",
"_set_default_options",
"(",
"self",
")",
":",
"self",
".",
"module_names",
"=",
"self",
".",
"_set_option",
"(",
"self",
".",
"config",
".",
"module_names",
")",
"all_ancestors",
"=",
"self",
".",
"_set_option",
"(",
"self",
".",
"config",
".",
"all_ancestors",
")",
"all_associated",
"=",
"self",
".",
"_set_option",
"(",
"self",
".",
"config",
".",
"all_associated",
")",
"anc_level",
",",
"association_level",
"=",
"(",
"0",
",",
"0",
")",
"if",
"all_ancestors",
":",
"anc_level",
"=",
"-",
"1",
"if",
"all_associated",
":",
"association_level",
"=",
"-",
"1",
"if",
"self",
".",
"config",
".",
"show_ancestors",
"is",
"not",
"None",
":",
"anc_level",
"=",
"self",
".",
"config",
".",
"show_ancestors",
"if",
"self",
".",
"config",
".",
"show_associated",
"is",
"not",
"None",
":",
"association_level",
"=",
"self",
".",
"config",
".",
"show_associated",
"self",
".",
"anc_level",
",",
"self",
".",
"association_level",
"=",
"anc_level",
",",
"association_level"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.show_node
|
true if builtins and not show_builtins
|
pylint/pyreverse/diadefslib.py
|
def show_node(self, node):
"""true if builtins and not show_builtins"""
if self.config.show_builtin:
return True
return node.root().name != BUILTINS_NAME
|
def show_node(self, node):
"""true if builtins and not show_builtins"""
if self.config.show_builtin:
return True
return node.root().name != BUILTINS_NAME
|
[
"true",
"if",
"builtins",
"and",
"not",
"show_builtins"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L75-L79
|
[
"def",
"show_node",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"config",
".",
"show_builtin",
":",
"return",
"True",
"return",
"node",
".",
"root",
"(",
")",
".",
"name",
"!=",
"BUILTINS_NAME"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.add_class
|
visit one class and add it to diagram
|
pylint/pyreverse/diadefslib.py
|
def add_class(self, node):
"""visit one class and add it to diagram"""
self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node)
|
def add_class(self, node):
"""visit one class and add it to diagram"""
self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node)
|
[
"visit",
"one",
"class",
"and",
"add",
"it",
"to",
"diagram"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L81-L84
|
[
"def",
"add_class",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"linker",
".",
"visit",
"(",
"node",
")",
"self",
".",
"classdiagram",
".",
"add_object",
"(",
"self",
".",
"get_title",
"(",
"node",
")",
",",
"node",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.get_ancestors
|
return ancestor nodes of a class node
|
pylint/pyreverse/diadefslib.py
|
def get_ancestors(self, node, level):
"""return ancestor nodes of a class node"""
if level == 0:
return
for ancestor in node.ancestors(recurs=False):
if not self.show_node(ancestor):
continue
yield ancestor
|
def get_ancestors(self, node, level):
"""return ancestor nodes of a class node"""
if level == 0:
return
for ancestor in node.ancestors(recurs=False):
if not self.show_node(ancestor):
continue
yield ancestor
|
[
"return",
"ancestor",
"nodes",
"of",
"a",
"class",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L86-L93
|
[
"def",
"get_ancestors",
"(",
"self",
",",
"node",
",",
"level",
")",
":",
"if",
"level",
"==",
"0",
":",
"return",
"for",
"ancestor",
"in",
"node",
".",
"ancestors",
"(",
"recurs",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"show_node",
"(",
"ancestor",
")",
":",
"continue",
"yield",
"ancestor"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.get_associated
|
return associated nodes of a class node
|
pylint/pyreverse/diadefslib.py
|
def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
klass_node.locals_type.values()
):
for node in association_nodes:
if isinstance(node, astroid.Instance):
node = node._proxied
if not (isinstance(node, astroid.ClassDef) and self.show_node(node)):
continue
yield node
|
def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
klass_node.locals_type.values()
):
for node in association_nodes:
if isinstance(node, astroid.Instance):
node = node._proxied
if not (isinstance(node, astroid.ClassDef) and self.show_node(node)):
continue
yield node
|
[
"return",
"associated",
"nodes",
"of",
"a",
"class",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L95-L107
|
[
"def",
"get_associated",
"(",
"self",
",",
"klass_node",
",",
"level",
")",
":",
"if",
"level",
"==",
"0",
":",
"return",
"for",
"association_nodes",
"in",
"list",
"(",
"klass_node",
".",
"instance_attrs_type",
".",
"values",
"(",
")",
")",
"+",
"list",
"(",
"klass_node",
".",
"locals_type",
".",
"values",
"(",
")",
")",
":",
"for",
"node",
"in",
"association_nodes",
":",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"Instance",
")",
":",
"node",
"=",
"node",
".",
"_proxied",
"if",
"not",
"(",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"ClassDef",
")",
"and",
"self",
".",
"show_node",
"(",
"node",
")",
")",
":",
"continue",
"yield",
"node"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DiaDefGenerator.extract_classes
|
extract recursively classes related to klass_node
|
pylint/pyreverse/diadefslib.py
|
def extract_classes(self, klass_node, anc_level, association_level):
"""extract recursively classes related to klass_node"""
if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node):
return
self.add_class(klass_node)
for ancestor in self.get_ancestors(klass_node, anc_level):
self.extract_classes(ancestor, anc_level - 1, association_level)
for node in self.get_associated(klass_node, association_level):
self.extract_classes(node, anc_level, association_level - 1)
|
def extract_classes(self, klass_node, anc_level, association_level):
"""extract recursively classes related to klass_node"""
if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node):
return
self.add_class(klass_node)
for ancestor in self.get_ancestors(klass_node, anc_level):
self.extract_classes(ancestor, anc_level - 1, association_level)
for node in self.get_associated(klass_node, association_level):
self.extract_classes(node, anc_level, association_level - 1)
|
[
"extract",
"recursively",
"classes",
"related",
"to",
"klass_node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L109-L119
|
[
"def",
"extract_classes",
"(",
"self",
",",
"klass_node",
",",
"anc_level",
",",
"association_level",
")",
":",
"if",
"self",
".",
"classdiagram",
".",
"has_node",
"(",
"klass_node",
")",
"or",
"not",
"self",
".",
"show_node",
"(",
"klass_node",
")",
":",
"return",
"self",
".",
"add_class",
"(",
"klass_node",
")",
"for",
"ancestor",
"in",
"self",
".",
"get_ancestors",
"(",
"klass_node",
",",
"anc_level",
")",
":",
"self",
".",
"extract_classes",
"(",
"ancestor",
",",
"anc_level",
"-",
"1",
",",
"association_level",
")",
"for",
"node",
"in",
"self",
".",
"get_associated",
"(",
"klass_node",
",",
"association_level",
")",
":",
"self",
".",
"extract_classes",
"(",
"node",
",",
"anc_level",
",",
"association_level",
"-",
"1",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
test
|
DefaultDiadefGenerator.visit_project
|
visit a pyreverse.utils.Project node
create a diagram definition for packages
|
pylint/pyreverse/diadefslib.py
|
def visit_project(self, node):
"""visit a pyreverse.utils.Project node
create a diagram definition for packages
"""
mode = self.config.mode
if len(node.modules) > 1:
self.pkgdiagram = PackageDiagram("packages %s" % node.name, mode)
else:
self.pkgdiagram = None
self.classdiagram = ClassDiagram("classes %s" % node.name, mode)
|
def visit_project(self, node):
"""visit a pyreverse.utils.Project node
create a diagram definition for packages
"""
mode = self.config.mode
if len(node.modules) > 1:
self.pkgdiagram = PackageDiagram("packages %s" % node.name, mode)
else:
self.pkgdiagram = None
self.classdiagram = ClassDiagram("classes %s" % node.name, mode)
|
[
"visit",
"a",
"pyreverse",
".",
"utils",
".",
"Project",
"node"
] |
PyCQA/pylint
|
python
|
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/pyreverse/diadefslib.py#L133-L143
|
[
"def",
"visit_project",
"(",
"self",
",",
"node",
")",
":",
"mode",
"=",
"self",
".",
"config",
".",
"mode",
"if",
"len",
"(",
"node",
".",
"modules",
")",
">",
"1",
":",
"self",
".",
"pkgdiagram",
"=",
"PackageDiagram",
"(",
"\"packages %s\"",
"%",
"node",
".",
"name",
",",
"mode",
")",
"else",
":",
"self",
".",
"pkgdiagram",
"=",
"None",
"self",
".",
"classdiagram",
"=",
"ClassDiagram",
"(",
"\"classes %s\"",
"%",
"node",
".",
"name",
",",
"mode",
")"
] |
2bf5c61a3ff6ae90613b81679de42c0f19aea600
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.