diff options
author | Claudiu Popa <pcmanticore@gmail.com> | 2018-10-02 09:43:56 +0200 |
---|---|---|
committer | Claudiu Popa <pcmanticore@gmail.com> | 2018-10-02 09:43:56 +0200 |
commit | add5f7b8eba427de9d39caae864bbc6dc37ef980 (patch) | |
tree | 86bb7df77f389062879365e97df0c3d53d38a8a6 /astroid/brain | |
parent | bb46cd198b93f3715da94089d42f39fc910892ff (diff) | |
download | astroid-git-add5f7b8eba427de9d39caae864bbc6dc37ef980.tar.gz |
Initial formatting of astroid
Diffstat (limited to 'astroid/brain')
27 files changed, 588 insertions, 520 deletions
diff --git a/astroid/brain/brain_argparse.py b/astroid/brain/brain_argparse.py index 1b120b4e..d4899117 100644 --- a/astroid/brain/brain_argparse.py +++ b/astroid/brain/brain_argparse.py @@ -1,10 +1,4 @@ -from astroid import ( - MANAGER, - arguments, - nodes, - inference_tip, - UseInferenceDefault, -) +from astroid import MANAGER, arguments, nodes, inference_tip, UseInferenceDefault def infer_namespace(node, context=None): @@ -13,28 +7,27 @@ def infer_namespace(node, context=None): # Cannot make sense of it. raise UseInferenceDefault() - class_node = nodes.ClassDef('Namespace', 'docstring') + class_node = nodes.ClassDef("Namespace", "docstring") class_node.parent = node.parent for attr in set(callsite.keyword_arguments): fake_node = nodes.EmptyNode() fake_node.parent = class_node fake_node.attrname = attr class_node.instance_attrs[attr] = [fake_node] - return iter((class_node.instantiate_class(), )) + return iter((class_node.instantiate_class(),)) def _looks_like_namespace(node): func = node.func if isinstance(func, nodes.Attribute): return ( - func.attrname == 'Namespace' + func.attrname == "Namespace" and isinstance(func.expr, nodes.Name) - and func.expr.name == 'argparse' + and func.expr.name == "argparse" ) return False MANAGER.register_transform( - nodes.Call, inference_tip(infer_namespace), - _looks_like_namespace, + nodes.Call, inference_tip(infer_namespace), _looks_like_namespace ) diff --git a/astroid/brain/brain_attrs.py b/astroid/brain/brain_attrs.py index 06dc912f..74d1aa34 100644 --- a/astroid/brain/brain_attrs.py +++ b/astroid/brain/brain_attrs.py @@ -11,11 +11,12 @@ import astroid from astroid import MANAGER -ATTR_IB = 'attr.ib' +ATTR_IB = "attr.ib" def is_decorated_with_attrs( - node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')): + node, decorator_names=("attr.s", "attr.attrs", "attr.attributes") +): """Return True if a decorated node has an attr decorator applied.""" if not node.decorators: @@ -49,12 +50,11 @@ def attr_attributes_transform(node): rhs_node = astroid.Unknown( lineno=cdefbodynode.lineno, col_offset=cdefbodynode.col_offset, - parent=cdefbodynode + parent=cdefbodynode, ) node.locals[target.name] = [rhs_node] MANAGER.register_transform( - astroid.ClassDef, - attr_attributes_transform, - is_decorated_with_attrs) + astroid.ClassDef, attr_attributes_transform, is_decorated_with_attrs +) diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py index e6def5c7..44a2efb3 100644 --- a/astroid/brain/brain_builtin_inference.py +++ b/astroid/brain/brain_builtin_inference.py @@ -34,12 +34,13 @@ from astroid import scoped_nodes from astroid import util -OBJECT_DUNDER_NEW = 'object.__new__' +OBJECT_DUNDER_NEW = "object.__new__" def _extend_str(class_node, rvalue): """function to extend builtin str/unicode class""" - code = dedent(''' + code = dedent( + """ class whatever(object): def join(self, iterable): return {rvalue} @@ -79,41 +80,53 @@ def _extend_str(class_node, rvalue): return {rvalue} def ljust(self, width, fillchar=None): return {rvalue} - ''') + """ + ) code = code.format(rvalue=rvalue) - fake = AstroidBuilder(MANAGER).string_build(code)['whatever'] + fake = AstroidBuilder(MANAGER).string_build(code)["whatever"] for method in fake.mymethods(): method.parent = class_node method.lineno = None method.col_offset = None - if '__class__' in method.locals: - method.locals['__class__'] = [class_node] + if "__class__" in method.locals: + method.locals["__class__"] = [class_node] class_node.locals[method.name] = [method] method.parent = class_node def extend_builtins(class_transforms): from astroid.bases import BUILTINS + builtin_ast = MANAGER.astroid_cache[BUILTINS] for class_name, transform in class_transforms.items(): transform(builtin_ast[class_name]) if sys.version_info > (3, 0): - extend_builtins({'bytes': partial(_extend_str, rvalue="b''"), - 'str': partial(_extend_str, rvalue="''")}) + extend_builtins( + { + "bytes": partial(_extend_str, rvalue="b''"), + "str": partial(_extend_str, rvalue="''"), + } + ) else: - extend_builtins({'str': partial(_extend_str, rvalue="''"), - 'unicode': partial(_extend_str, rvalue="u''")}) + extend_builtins( + { + "str": partial(_extend_str, rvalue="''"), + "unicode": partial(_extend_str, rvalue="u''"), + } + ) def _builtin_filter_predicate(node, builtin_name): if isinstance(node.func, nodes.Name) and node.func.name == builtin_name: return True if isinstance(node.func, nodes.Attribute): - return (node.func.attrname == 'fromkeys' - and isinstance(node.func.expr, nodes.Name) - and node.func.expr.name == 'dict') + return ( + node.func.attrname == "fromkeys" + and isinstance(node.func.expr, nodes.Name) + and node.func.expr.name == "dict" + ) return False @@ -123,6 +136,7 @@ def register_builtin_transform(transform, builtin_name): The transform function must accept two parameters, a node and an optional context. """ + def _transform_wrapper(node, context=None): result = transform(node, context=context) if result: @@ -175,64 +189,72 @@ def _generic_transform(arg, klass, iterables, build_elts): raise UseInferenceDefault() elts = [elt.value for elt in arg.elts] elif isinstance(arg, nodes.Dict): - if not all(isinstance(elt[0], nodes.Const) - for elt in arg.items): + if not all(isinstance(elt[0], nodes.Const) for elt in arg.items): raise UseInferenceDefault() elts = [item[0].value for item in arg.items] - elif (isinstance(arg, nodes.Const) and - isinstance(arg.value, (six.string_types, six.binary_type))): + elif isinstance(arg, nodes.Const) and isinstance( + arg.value, (six.string_types, six.binary_type) + ): elts = arg.value else: return return klass.from_constants(elts=build_elts(elts)) -def _infer_builtin(node, context, - klass=None, iterables=None, - build_elts=None): +def _infer_builtin(node, context, klass=None, iterables=None, build_elts=None): transform_func = partial( - _generic_transform, - klass=klass, - iterables=iterables, - build_elts=build_elts) + _generic_transform, klass=klass, iterables=iterables, build_elts=build_elts + ) return _generic_inference(node, context, klass, transform_func) + # pylint: disable=invalid-name infer_tuple = partial( _infer_builtin, klass=nodes.Tuple, - iterables=(nodes.List, nodes.Set, objects.FrozenSet, - objects.DictItems, objects.DictKeys, - objects.DictValues), - build_elts=tuple) + iterables=( + nodes.List, + nodes.Set, + objects.FrozenSet, + objects.DictItems, + objects.DictKeys, + objects.DictValues, + ), + build_elts=tuple, +) infer_list = partial( _infer_builtin, klass=nodes.List, - iterables=(nodes.Tuple, nodes.Set, objects.FrozenSet, - objects.DictItems, objects.DictKeys, - objects.DictValues), - build_elts=list) + iterables=( + nodes.Tuple, + nodes.Set, + objects.FrozenSet, + objects.DictItems, + objects.DictKeys, + objects.DictValues, + ), + build_elts=list, +) infer_set = partial( _infer_builtin, klass=nodes.Set, - iterables=(nodes.List, nodes.Tuple, objects.FrozenSet, - objects.DictKeys), - build_elts=set) + iterables=(nodes.List, nodes.Tuple, objects.FrozenSet, objects.DictKeys), + build_elts=set, +) infer_frozenset = partial( _infer_builtin, klass=objects.FrozenSet, - iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet, - objects.DictKeys), - build_elts=frozenset) + iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet, objects.DictKeys), + build_elts=frozenset, +) def _get_elts(arg, context): - is_iterable = lambda n: isinstance(n, - (nodes.List, nodes.Tuple, nodes.Set)) + is_iterable = lambda n: isinstance(n, (nodes.List, nodes.Tuple, nodes.Set)) try: inferred = next(arg.infer(context)) except (InferenceError, NameInferenceError): @@ -250,14 +272,14 @@ def _get_elts(arg, context): raise UseInferenceDefault() if len(elt.elts) != 2: raise UseInferenceDefault() - if not isinstance(elt.elts[0], - (nodes.Tuple, nodes.Const, nodes.Name)): + if not isinstance(elt.elts[0], (nodes.Tuple, nodes.Const, nodes.Name)): raise UseInferenceDefault() items.append(tuple(elt.elts)) else: raise UseInferenceDefault() return items + def infer_dict(node, context=None): """Try to infer a dict call to a Dict node. @@ -295,9 +317,9 @@ def infer_dict(node, context=None): else: raise UseInferenceDefault() - value = nodes.Dict(col_offset=node.col_offset, - lineno=node.lineno, - parent=node.parent) + value = nodes.Dict( + col_offset=node.col_offset, lineno=node.lineno, parent=node.parent + ) value.postinit(items) return value @@ -323,7 +345,7 @@ def infer_super(node, context=None): if not isinstance(scope, nodes.FunctionDef): # Ignore non-method uses of super. raise UseInferenceDefault - if scope.type not in ('classmethod', 'method'): + if scope.type not in ("classmethod", "method"): # Not interested in staticmethods. raise UseInferenceDefault @@ -332,7 +354,7 @@ def infer_super(node, context=None): mro_pointer = cls # In we are in a classmethod, the interpreter will fill # automatically the class as the second argument, not an instance. - if scope.type == 'classmethod': + if scope.type == "classmethod": mro_type = cls else: mro_type = cls.instantiate_class() @@ -350,10 +372,9 @@ def infer_super(node, context=None): # No way we could understand this. raise UseInferenceDefault - super_obj = objects.Super(mro_pointer=mro_pointer, - mro_type=mro_type, - self_class=cls, - scope=scope) + super_obj = objects.Super( + mro_pointer=mro_pointer, mro_type=mro_type, self_class=cls, scope=scope + ) super_obj.parent = node return super_obj @@ -375,8 +396,9 @@ def _infer_getattr_args(node, context): # which is unknown. return util.Uninferable, util.Uninferable - is_string = (isinstance(attr, nodes.Const) and - isinstance(attr.value, six.string_types)) + is_string = isinstance(attr, nodes.Const) and isinstance( + attr.value, six.string_types + ) if not is_string: raise UseInferenceDefault @@ -391,7 +413,11 @@ def infer_getattr(node, context=None): lookup will be done. """ obj, attr = _infer_getattr_args(node, context) - if obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, 'igetattr'): + if ( + obj is util.Uninferable + or attr is util.Uninferable + or not hasattr(obj, "igetattr") + ): return util.Uninferable try: @@ -418,7 +444,11 @@ def infer_hasattr(node, context=None): """ try: obj, attr = _infer_getattr_args(node, context) - if obj is util.Uninferable or attr is util.Uninferable or not hasattr(obj, 'getattr'): + if ( + obj is util.Uninferable + or attr is util.Uninferable + or not hasattr(obj, "getattr") + ): return util.Uninferable obj.getattr(attr, context=context) except UseInferenceDefault: @@ -502,9 +532,9 @@ def infer_slice(node, context=None): # Make sure we have 3 arguments. args.extend([None] * (3 - len(args))) - slice_node = nodes.Slice(lineno=node.lineno, - col_offset=node.col_offset, - parent=node.parent) + slice_node = nodes.Slice( + lineno=node.lineno, col_offset=node.col_offset, parent=node.parent + ) slice_node.postinit(*args) return slice_node @@ -544,8 +574,10 @@ def infer_issubclass(callnode, context=None): raise UseInferenceDefault("TypeError: issubclass() takes no keyword arguments") if len(call.positional_arguments) != 2: raise UseInferenceDefault( - "Expected two arguments, got {count}" - .format(count=len(call.positional_arguments))) + "Expected two arguments, got {count}".format( + count=len(call.positional_arguments) + ) + ) # The left hand argument is the obj to be checked obj_node, class_or_tuple_node = call.positional_arguments @@ -560,7 +592,8 @@ def infer_issubclass(callnode, context=None): # object is to be checked against. try: class_container = _class_or_tuple_to_container( - class_or_tuple_node, context=context) + class_or_tuple_node, context=context + ) except InferenceError as exc: raise UseInferenceDefault from exc try: @@ -588,20 +621,22 @@ def infer_isinstance(callnode, context=None): raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments") if len(call.positional_arguments) != 2: raise UseInferenceDefault( - "Expected two arguments, got {count}" - .format(count=len(call.positional_arguments))) + "Expected two arguments, got {count}".format( + count=len(call.positional_arguments) + ) + ) # The left hand argument is the obj to be checked obj_node, class_or_tuple_node = call.positional_arguments # The right hand argument is the class(es) that the given # obj is to be check is an instance of try: class_container = _class_or_tuple_to_container( - class_or_tuple_node, context=context) + class_or_tuple_node, context=context + ) except InferenceError: raise UseInferenceDefault try: - isinstance_bool = helpers.object_isinstance( - obj_node, class_container, context) + isinstance_bool = helpers.object_isinstance(obj_node, class_container, context) except AstroidTypeError as exc: raise UseInferenceDefault("TypeError: " + str(exc)) except MroError as exc: @@ -620,12 +655,10 @@ def _class_or_tuple_to_container(node, context=None): # for isinstance if isinstance(node_infer, nodes.Tuple): class_container = [ - next(node.infer(context=context)) - for node in node_infer.elts + next(node.infer(context=context)) for node in node_infer.elts ] class_container = [ - klass_node for klass_node - in class_container if klass_node is not None + klass_node for klass_node in class_container if klass_node is not None ] else: class_container = [node_infer] @@ -641,9 +674,7 @@ def infer_len(node, context=None): """ call = arguments.CallSite.from_call(node) if call.keyword_arguments: - raise UseInferenceDefault( - "TypeError: len() must take no keyword arguments" - ) + raise UseInferenceDefault("TypeError: len() must take no keyword arguments") if len(call.positional_arguments) != 1: raise UseInferenceDefault( "TypeError: len() must take exactly one argument " @@ -665,10 +696,9 @@ def infer_str(node, context=None): """ call = arguments.CallSite.from_call(node) if call.keyword_arguments: - raise UseInferenceDefault( - "TypeError: str() must take no keyword arguments") + raise UseInferenceDefault("TypeError: str() must take no keyword arguments") try: - return nodes.Const('') + return nodes.Const("") except (AstroidTypeError, InferenceError) as exc: raise UseInferenceDefault(str(exc)) from exc @@ -682,9 +712,7 @@ def infer_int(node, context=None): """ call = arguments.CallSite.from_call(node) if call.keyword_arguments: - raise UseInferenceDefault( - "TypeError: int() must take no keyword arguments" - ) + raise UseInferenceDefault("TypeError: int() must take no keyword arguments") if call.positional_arguments: try: @@ -695,7 +723,9 @@ def infer_int(node, context=None): if first_value is util.Uninferable: raise UseInferenceDefault - if isinstance(first_value, nodes.Const) and isinstance(first_value.value, (int, str)): + if isinstance(first_value, nodes.Const) and isinstance( + first_value.value, (int, str) + ): try: actual_value = int(first_value.value) except ValueError: @@ -717,19 +747,19 @@ def infer_dict_fromkeys(node, context=None): """ def _build_dict_with_elements(elements): - new_node = nodes.Dict(col_offset=node.col_offset, - lineno=node.lineno, - parent=node.parent) + new_node = nodes.Dict( + col_offset=node.col_offset, lineno=node.lineno, parent=node.parent + ) new_node.postinit(elements) return new_node call = arguments.CallSite.from_call(node) if call.keyword_arguments: + raise UseInferenceDefault("TypeError: int() must take no keyword arguments") + if len(call.positional_arguments) not in {1, 2}: raise UseInferenceDefault( - "TypeError: int() must take no keyword arguments" + "TypeError: Needs between 1 and 2 positional arguments" ) - if len(call.positional_arguments) not in {1, 2}: - raise UseInferenceDefault("TypeError: Needs between 1 and 2 positional arguments") default = nodes.Const(None) values = call.positional_arguments[0] @@ -741,9 +771,7 @@ def infer_dict_fromkeys(node, context=None): return _build_dict_with_elements([]) # Limit to a couple of potential values, as this can become pretty complicated - accepted_iterable_elements = ( - nodes.Const, - ) + accepted_iterable_elements = (nodes.Const,) if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)): elements = inferred_values.elts for element in elements: @@ -754,8 +782,9 @@ def infer_dict_fromkeys(node, context=None): elements_with_value = [(element, default) for element in elements] return _build_dict_with_elements(elements_with_value) - elif (isinstance(inferred_values, nodes.Const) - and isinstance(inferred_values.value, (str, bytes))): + elif isinstance(inferred_values, nodes.Const) and isinstance( + inferred_values.value, (str, bytes) + ): elements = [ (nodes.Const(element), default) for element in inferred_values.value ] @@ -775,29 +804,29 @@ def infer_dict_fromkeys(node, context=None): # Builtins inference -register_builtin_transform(infer_bool, 'bool') -register_builtin_transform(infer_super, 'super') -register_builtin_transform(infer_callable, 'callable') -register_builtin_transform(infer_getattr, 'getattr') -register_builtin_transform(infer_hasattr, 'hasattr') -register_builtin_transform(infer_tuple, 'tuple') -register_builtin_transform(infer_set, 'set') -register_builtin_transform(infer_list, 'list') -register_builtin_transform(infer_dict, 'dict') -register_builtin_transform(infer_frozenset, 'frozenset') -register_builtin_transform(infer_type, 'type') -register_builtin_transform(infer_slice, 'slice') -register_builtin_transform(infer_isinstance, 'isinstance') -register_builtin_transform(infer_issubclass, 'issubclass') -register_builtin_transform(infer_len, 'len') -register_builtin_transform(infer_str, 'str') -register_builtin_transform(infer_int, 'int') -register_builtin_transform(infer_dict_fromkeys, 'dict.fromkeys') +register_builtin_transform(infer_bool, "bool") +register_builtin_transform(infer_super, "super") +register_builtin_transform(infer_callable, "callable") +register_builtin_transform(infer_getattr, "getattr") +register_builtin_transform(infer_hasattr, "hasattr") +register_builtin_transform(infer_tuple, "tuple") +register_builtin_transform(infer_set, "set") +register_builtin_transform(infer_list, "list") +register_builtin_transform(infer_dict, "dict") +register_builtin_transform(infer_frozenset, "frozenset") +register_builtin_transform(infer_type, "type") +register_builtin_transform(infer_slice, "slice") +register_builtin_transform(infer_isinstance, "isinstance") +register_builtin_transform(infer_issubclass, "issubclass") +register_builtin_transform(infer_len, "len") +register_builtin_transform(infer_str, "str") +register_builtin_transform(infer_int, "int") +register_builtin_transform(infer_dict_fromkeys, "dict.fromkeys") # Infer object.__new__ calls MANAGER.register_transform( nodes.ClassDef, inference_tip(_infer_object__new__decorator), - _infer_object__new__decorator_check + _infer_object__new__decorator_check, ) diff --git a/astroid/brain/brain_collections.py b/astroid/brain/brain_collections.py index c255bf44..b9eb9b96 100644 --- a/astroid/brain/brain_collections.py +++ b/astroid/brain/brain_collections.py @@ -15,17 +15,21 @@ PY35 = sys.version_info >= (3, 5) def _collections_transform(): - return astroid.parse(''' + return astroid.parse( + """ class defaultdict(dict): default_factory = None def __missing__(self, key): pass def __getitem__(self, key): return default_factory - ''' + _deque_mock() + _ordered_dict_mock()) + """ + + _deque_mock() + + _ordered_dict_mock() + ) def _deque_mock(): - base_deque_class = ''' + base_deque_class = """ class deque(object): maxlen = 0 def __init__(self, iterable=None, maxlen=None): @@ -50,9 +54,9 @@ def _deque_mock(): def __nonzero__(self): return bool(self.iterable) def __contains__(self, o): return o in self.iterable def __len__(self): return len(self.iterable) - def __copy__(self): return deque(self.iterable)''' + def __copy__(self): return deque(self.iterable)""" if PY35: - base_deque_class += ''' + base_deque_class += """ def copy(self): return deque(self.iterable) def index(self, x, start=0, end=0): return 0 def insert(self, x, i): pass @@ -60,19 +64,19 @@ def _deque_mock(): def __iadd__(self, other): pass def __mul__(self, other): pass def __imul__(self, other): pass - def __rmul__(self, other): pass''' + def __rmul__(self, other): pass""" return base_deque_class def _ordered_dict_mock(): - base_ordered_dict_class = ''' + base_ordered_dict_class = """ class OrderedDict(dict): def __reversed__(self): return self[::-1] - ''' + """ if PY34: - base_ordered_dict_class += ''' - def move_to_end(self, key, last=False): pass''' + base_ordered_dict_class += """ + def move_to_end(self, key, last=False): pass""" return base_ordered_dict_class -astroid.register_module_extender(astroid.MANAGER, 'collections', _collections_transform) +astroid.register_module_extender(astroid.MANAGER, "collections", _collections_transform) diff --git a/astroid/brain/brain_curses.py b/astroid/brain/brain_curses.py index f1954835..68e88b90 100644 --- a/astroid/brain/brain_curses.py +++ b/astroid/brain/brain_curses.py @@ -4,7 +4,8 @@ import astroid def _curses_transform(): - return astroid.parse(''' + return astroid.parse( + """ A_ALTCHARSET = 1 A_BLINK = 1 A_BOLD = 1 @@ -171,7 +172,8 @@ def _curses_transform(): COLOR_RED = 1 COLOR_WHITE = 1 COLOR_YELLOW = 1 - ''') + """ + ) -astroid.register_module_extender(astroid.MANAGER, 'curses', _curses_transform) +astroid.register_module_extender(astroid.MANAGER, "curses", _curses_transform) diff --git a/astroid/brain/brain_dateutil.py b/astroid/brain/brain_dateutil.py index 0c641ac6..a1c270fe 100644 --- a/astroid/brain/brain_dateutil.py +++ b/astroid/brain/brain_dateutil.py @@ -12,11 +12,17 @@ import textwrap from astroid import MANAGER, register_module_extender from astroid.builder import AstroidBuilder + def dateutil_transform(): - return AstroidBuilder(MANAGER).string_build(textwrap.dedent(''' + return AstroidBuilder(MANAGER).string_build( + textwrap.dedent( + """ import datetime def parse(timestr, parserinfo=None, **kwargs): return datetime.datetime() - ''')) + """ + ) + ) + -register_module_extender(MANAGER, 'dateutil.parser', dateutil_transform) +register_module_extender(MANAGER, "dateutil.parser", dateutil_transform) diff --git a/astroid/brain/brain_fstrings.py b/astroid/brain/brain_fstrings.py index 5c2d17b8..7d8c7b68 100644 --- a/astroid/brain/brain_fstrings.py +++ b/astroid/brain/brain_fstrings.py @@ -12,28 +12,16 @@ def _clone_node_with_lineno(node, parent, lineno): cls = node.__class__ other_fields = node._other_fields _astroid_fields = node._astroid_fields - init_params = { - 'lineno': lineno, - 'col_offset': node.col_offset, - 'parent': parent - } - postinit_params = { - param: getattr(node, param) - for param in _astroid_fields - } + init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent} + postinit_params = {param: getattr(node, param) for param in _astroid_fields} if other_fields: - init_params.update({ - param: getattr(node, param) - for param in other_fields - }) + init_params.update({param: getattr(node, param) for param in other_fields}) new_node = cls(**init_params) - if hasattr(node, 'postinit') and _astroid_fields: + if hasattr(node, "postinit") and _astroid_fields: for param, child in postinit_params.items(): if child and not isinstance(child, collections.Sequence): cloned_child = _clone_node_with_lineno( - node=child, - lineno=new_node.lineno, - parent=new_node, + node=child, lineno=new_node.lineno, parent=new_node ) postinit_params[param] = cloned_child new_node.postinit(**postinit_params) @@ -44,17 +32,12 @@ def _transform_formatted_value(node): if node.value and node.value.lineno == 1: if node.lineno != node.value.lineno: new_node = astroid.FormattedValue( - lineno=node.lineno, - col_offset=node.col_offset, - parent=node.parent + lineno=node.lineno, col_offset=node.col_offset, parent=node.parent ) new_value = _clone_node_with_lineno( - node=node.value, - lineno=node.lineno, - parent=new_node + node=node.value, lineno=node.lineno, parent=new_node ) - new_node.postinit(value=new_value, - format_spec=node.format_spec) + new_node.postinit(value=new_value, format_spec=node.format_spec) return new_node @@ -64,5 +47,5 @@ if sys.version_info[:2] >= (3, 6): # has wrong line numbers, usually 1. This creates problems for pylint, # which expects correct line numbers for things such as message control. astroid.MANAGER.register_transform( - astroid.FormattedValue, - _transform_formatted_value) + astroid.FormattedValue, _transform_formatted_value + ) diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py index b70dd4dc..ff307dfe 100644 --- a/astroid/brain/brain_functools.py +++ b/astroid/brain/brain_functools.py @@ -13,7 +13,7 @@ from astroid.interpreter import objectmodel from astroid import MANAGER -LRU_CACHE = 'functools.lru_cache' +LRU_CACHE = "functools.lru_cache" class LruWrappedModel(objectmodel.FunctionModel): @@ -29,10 +29,13 @@ class LruWrappedModel(objectmodel.FunctionModel): @property def pycache_info(self): - cache_info = extract_node(''' + cache_info = extract_node( + """ from functools import _CacheInfo _CacheInfo(0, 0, 0, 0) - ''') + """ + ) + class CacheInfoBoundMethod(BoundMethod): def infer_call_result(self, caller, context=None): yield helpers.safe_infer(cache_info) @@ -41,7 +44,7 @@ class LruWrappedModel(objectmodel.FunctionModel): @property def pycache_clear(self): - node = extract_node('''def cache_clear(self): pass''') + node = extract_node("""def cache_clear(self): pass""") return BoundMethod(proxy=node, bound=self._instance.parent.scope()) @@ -60,10 +63,12 @@ def _functools_partial_inference(node, context=None): call = arguments.CallSite.from_call(node) number_of_positional = len(call.positional_arguments) if number_of_positional < 1: - raise astroid.UseInferenceDefault('functools.partial takes at least one argument') + raise astroid.UseInferenceDefault( + "functools.partial takes at least one argument" + ) if number_of_positional == 1 and not call.keyword_arguments: raise astroid.UseInferenceDefault( - 'functools.partial needs at least to have some filled arguments' + "functools.partial needs at least to have some filled arguments" ) partial_function = call.positional_arguments[0] @@ -72,22 +77,25 @@ def _functools_partial_inference(node, context=None): except astroid.InferenceError as exc: raise astroid.UseInferenceDefault from exc if inferred_wrapped_function is astroid.Uninferable: - raise astroid.UseInferenceDefault('Cannot infer the wrapped function') + raise astroid.UseInferenceDefault("Cannot infer the wrapped function") if not isinstance(inferred_wrapped_function, astroid.FunctionDef): - raise astroid.UseInferenceDefault('The wrapped function is not a function') + raise astroid.UseInferenceDefault("The wrapped function is not a function") # Determine if the passed keywords into the callsite are supported # by the wrapped function. function_parameters = chain( inferred_wrapped_function.args.args or (), - inferred_wrapped_function.args.kwonlyargs or () + inferred_wrapped_function.args.kwonlyargs or (), ) parameter_names = set( - param.name for param in function_parameters + param.name + for param in function_parameters if isinstance(param, astroid.AssignName) ) if set(call.keyword_arguments) - parameter_names: - raise astroid.UseInferenceDefault('wrapped function received unknown parameters') + raise astroid.UseInferenceDefault( + "wrapped function received unknown parameters" + ) # Return a wrapped() object that can be used further for inference class PartialFunction(astroid.FunctionDef): @@ -111,10 +119,7 @@ def _functools_partial_inference(node, context=None): call_context_args = context.callcontext.args or [] context.callcontext.args = filled_args + call_context_args - return super().infer_call_result( - caller=caller, - context=context, - ) + return super().infer_call_result(caller=caller, context=context) partial_function = PartialFunction( name=inferred_wrapped_function.name, @@ -155,17 +160,17 @@ def _looks_like_lru_cache(node): def _looks_like_functools_partial(node): """Check if the given Call node is a functools.partial call""" if isinstance(node.func, astroid.Name): - return node.func.name == 'partial' + return node.func.name == "partial" elif isinstance(node.func, astroid.Attribute): - return (node.func.attrname == 'partial' - and isinstance(node.func.expr, astroid.Name) - and node.func.expr.name == 'functools') + return ( + node.func.attrname == "partial" + and isinstance(node.func.expr, astroid.Name) + and node.func.expr.name == "functools" + ) MANAGER.register_transform( - astroid.FunctionDef, - _transform_lru_cache, - _looks_like_lru_cache, + astroid.FunctionDef, _transform_lru_cache, _looks_like_lru_cache ) diff --git a/astroid/brain/brain_gi.py b/astroid/brain/brain_gi.py index 82b923df..09706107 100644 --- a/astroid/brain/brain_gi.py +++ b/astroid/brain/brain_gi.py @@ -27,7 +27,8 @@ from astroid.builder import AstroidBuilder _inspected_modules = {} -_identifier_re = r'^[A-Za-z_]\w*$' +_identifier_re = r"^[A-Za-z_]\w*$" + def _gi_build_stub(parent): """ @@ -53,16 +54,16 @@ def _gi_build_stub(parent): if inspect.isclass(obj): classes[name] = obj - elif (inspect.isfunction(obj) or - inspect.isbuiltin(obj)): + elif inspect.isfunction(obj) or inspect.isbuiltin(obj): functions[name] = obj - elif (inspect.ismethod(obj) or - inspect.ismethoddescriptor(obj)): + elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj): methods[name] = obj - elif (str(obj).startswith("<flags") or - str(obj).startswith("<enum ") or - str(obj).startswith("<GType ") or - inspect.isdatadescriptor(obj)): + elif ( + str(obj).startswith("<flags") + or str(obj).startswith("<enum ") + or str(obj).startswith("<GType ") + or inspect.isdatadescriptor(obj) + ): constants[name] = 0 elif isinstance(obj, (int, str)): constants[name] = obj @@ -126,9 +127,10 @@ def _gi_build_stub(parent): return ret + def _import_gi_module(modname): # we only consider gi.repository submodules - if not modname.startswith('gi.repository.'): + if not modname.startswith("gi.repository."): raise AstroidBuildingError(modname=modname) # build astroid representation unless we already tried so if modname not in _inspected_modules: @@ -139,13 +141,13 @@ def _import_gi_module(modname): # in pygobject that we need to cope with. However at # least as of pygobject3-3.13.91 the _glib module doesn't # exist anymore, so if treat these modules as optional. - if modname == 'gi.repository.GLib': - optional_modnames.append('gi._glib') - elif modname == 'gi.repository.GObject': - optional_modnames.append('gi._gobject') + if modname == "gi.repository.GLib": + optional_modnames.append("gi._glib") + elif modname == "gi.repository.GObject": + optional_modnames.append("gi._gobject") try: - modcode = '' + modcode = "" for m in itertools.chain(modnames, optional_modnames): try: with warnings.catch_warnings(): @@ -153,6 +155,7 @@ def _import_gi_module(modname): # warnings, so ignore them. try: from gi import PyGIDeprecationWarning, PyGIWarning + warnings.simplefilter("ignore", PyGIDeprecationWarning) warnings.simplefilter("ignore", PyGIWarning) except Exception: @@ -174,6 +177,7 @@ def _import_gi_module(modname): raise AstroidBuildingError(modname=modname) return astng + def _looks_like_require_version(node): # Return whether this looks like a call to gi.require_version(<name>, <version>) # Only accept function calls with two constant arguments @@ -185,27 +189,32 @@ def _looks_like_require_version(node): func = node.func if isinstance(func, nodes.Attribute): - if func.attrname != 'require_version': + if func.attrname != "require_version": return False - if isinstance(func.expr, nodes.Name) and func.expr.name == 'gi': + if isinstance(func.expr, nodes.Name) and func.expr.name == "gi": return True return False if isinstance(func, nodes.Name): - return func.name == 'require_version' + return func.name == "require_version" return False + def _register_require_version(node): # Load the gi.require_version locally try: import gi + gi.require_version(node.args[0].value, node.args[1].value) except Exception: pass return node + MANAGER.register_failed_import_hook(_import_gi_module) -MANAGER.register_transform(nodes.Call, _register_require_version, _looks_like_require_version) +MANAGER.register_transform( + nodes.Call, _register_require_version, _looks_like_require_version +) diff --git a/astroid/brain/brain_hashlib.py b/astroid/brain/brain_hashlib.py index e2b8c535..8b83ebed 100644 --- a/astroid/brain/brain_hashlib.py +++ b/astroid/brain/brain_hashlib.py @@ -14,7 +14,7 @@ PY36 = sys.version_info >= (3, 6) def _hashlib_transform(): signature = "value=''" - template = ''' + template = """ class %(name)s(object): def __init__(self, %(signature)s): pass def digest(self): @@ -33,31 +33,30 @@ def _hashlib_transform(): @property def digest_size(self): return 1 - ''' + """ algorithms_with_signature = dict.fromkeys( - ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], - signature, + ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature ) if PY36: blake_signature = "value='', digest_size=None" new_algorithms = dict.fromkeys( - ['sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'shake_128', 'shake_256'], - signature + ["sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128", "shake_256"], + signature, ) algorithms_with_signature.update(new_algorithms) - algorithms_with_signature.update({ - 'blake2b': blake_signature, - 'blake2s': blake_signature, - }) + algorithms_with_signature.update( + {"blake2b": blake_signature, "blake2s": blake_signature} + ) classes = "".join( - template % { - 'name': hashfunc, - 'digest': 'b""' if six.PY3 else '""', - 'signature': signature + template + % { + "name": hashfunc, + "digest": 'b""' if six.PY3 else '""', + "signature": signature, } for hashfunc, signature in algorithms_with_signature.items() ) return astroid.parse(classes) -astroid.register_module_extender(astroid.MANAGER, 'hashlib', _hashlib_transform) +astroid.register_module_extender(astroid.MANAGER, "hashlib", _hashlib_transform) diff --git a/astroid/brain/brain_io.py b/astroid/brain/brain_io.py index be8d30c8..4c689225 100644 --- a/astroid/brain/brain_io.py +++ b/astroid/brain/brain_io.py @@ -3,21 +3,21 @@ # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER -'''Astroid brain hints for some of the _io C objects.''' +"""Astroid brain hints for some of the _io C objects.""" import astroid -BUFFERED = {'BufferedWriter', 'BufferedReader'} -TextIOWrapper = 'TextIOWrapper' -FileIO = 'FileIO' -BufferedWriter = 'BufferedWriter' +BUFFERED = {"BufferedWriter", "BufferedReader"} +TextIOWrapper = "TextIOWrapper" +FileIO = "FileIO" +BufferedWriter = "BufferedWriter" def _generic_io_transform(node, name, cls): - '''Transform the given name, by adding the given *class* as a member of the node.''' + """Transform the given name, by adding the given *class* as a member of the node.""" - io_module = astroid.MANAGER.ast_from_module_name('_io') + io_module = astroid.MANAGER.ast_from_module_name("_io") attribute_object = io_module[cls] instance = attribute_object.instantiate_class() node.locals[name] = [instance] @@ -28,16 +28,18 @@ def _transform_text_io_wrapper(node): # being stdout, stderr or stdin. But we cannot get access to the name of the # stream, which is why we are using the BufferedWriter class as a default # value - return _generic_io_transform(node, name='buffer', cls=BufferedWriter) + return _generic_io_transform(node, name="buffer", cls=BufferedWriter) def _transform_buffered(node): - return _generic_io_transform(node, name='raw', cls=FileIO) + return _generic_io_transform(node, name="raw", cls=FileIO) -astroid.MANAGER.register_transform(astroid.ClassDef, - _transform_buffered, - lambda node: node.name in BUFFERED) -astroid.MANAGER.register_transform(astroid.ClassDef, - _transform_text_io_wrapper, - lambda node: node.name == TextIOWrapper) +astroid.MANAGER.register_transform( + astroid.ClassDef, _transform_buffered, lambda node: node.name in BUFFERED +) +astroid.MANAGER.register_transform( + astroid.ClassDef, + _transform_text_io_wrapper, + lambda node: node.name == TextIOWrapper, +) diff --git a/astroid/brain/brain_mechanize.py b/astroid/brain/brain_mechanize.py index 3b921807..93f282ec 100644 --- a/astroid/brain/brain_mechanize.py +++ b/astroid/brain/brain_mechanize.py @@ -9,8 +9,10 @@ from astroid import MANAGER, register_module_extender from astroid.builder import AstroidBuilder + def mechanize_transform(): - return AstroidBuilder(MANAGER).string_build(''' + return AstroidBuilder(MANAGER).string_build( + """ class Browser(object): def open(self, url, data=None, timeout=None): @@ -20,7 +22,8 @@ class Browser(object): def open_local_file(self, filename): return None -''') +""" + ) -register_module_extender(MANAGER, 'mechanize', mechanize_transform) +register_module_extender(MANAGER, "mechanize", mechanize_transform) diff --git a/astroid/brain/brain_multiprocessing.py b/astroid/brain/brain_multiprocessing.py index a19bac69..be575e94 100644 --- a/astroid/brain/brain_multiprocessing.py +++ b/astroid/brain/brain_multiprocessing.py @@ -13,25 +13,29 @@ PY34 = sys.version_info >= (3, 4) def _multiprocessing_transform(): - module = astroid.parse(''' + module = astroid.parse( + """ from multiprocessing.managers import SyncManager def Manager(): return SyncManager() - ''') + """ + ) if not PY34: return module # On Python 3.4, multiprocessing uses a getattr lookup inside contexts, # in order to get the attributes they need. Since it's extremely # dynamic, we use this approach to fake it. - node = astroid.parse(''' + node = astroid.parse( + """ from multiprocessing.context import DefaultContext, BaseContext default = DefaultContext() base = BaseContext() - ''') + """ + ) try: - context = next(node['default'].infer()) - base = next(node['base'].infer()) + context = next(node["default"].infer()) + base = next(node["base"].infer()) except exceptions.InferenceError: return module @@ -50,7 +54,8 @@ def _multiprocessing_transform(): def _multiprocessing_managers_transform(): - return astroid.parse(''' + return astroid.parse( + """ import array import threading import multiprocessing.pool as pool @@ -90,15 +95,18 @@ def _multiprocessing_managers_transform(): Namespace = Namespace __enter__ = lambda self: self __exit__ = lambda *args: args - + def start(self, initializer=None, initargs=None): pass def shutdown(self): pass - ''') + """ + ) -astroid.register_module_extender(astroid.MANAGER, 'multiprocessing.managers', - _multiprocessing_managers_transform) -astroid.register_module_extender(astroid.MANAGER, 'multiprocessing', - _multiprocessing_transform) +astroid.register_module_extender( + astroid.MANAGER, "multiprocessing.managers", _multiprocessing_managers_transform +) +astroid.register_module_extender( + astroid.MANAGER, "multiprocessing", _multiprocessing_transform +) diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index cc399246..85390a82 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -21,9 +21,7 @@ import functools import keyword from textwrap import dedent -from astroid import ( - MANAGER, UseInferenceDefault, inference_tip, - InferenceError) +from astroid import MANAGER, UseInferenceDefault, inference_tip, InferenceError from astroid import arguments from astroid import exceptions from astroid import nodes @@ -31,11 +29,8 @@ from astroid.builder import AstroidBuilder, extract_node from astroid import util -TYPING_NAMEDTUPLE_BASENAMES = { - 'NamedTuple', - 'typing.NamedTuple' -} -ENUM_BASE_NAMES = {'Enum', 'IntEnum', 'enum.Enum', 'enum.IntEnum'} +TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"} +ENUM_BASE_NAMES = {"Enum", "IntEnum", "enum.Enum", "enum.IntEnum"} def _infer_first(node, context): @@ -52,7 +47,6 @@ def _infer_first(node, context): def _find_func_form_arguments(node, context): - def _extract_namedtuple_arg_or_keyword(position, key_name=None): if len(args) > position: @@ -62,18 +56,12 @@ def _find_func_form_arguments(node, context): args = node.args keywords = node.keywords - found_keywords = { - keyword.arg: keyword.value for keyword in keywords - } if keywords else {} - - name = _extract_namedtuple_arg_or_keyword( - position=0, - key_name='typename' - ) - names = _extract_namedtuple_arg_or_keyword( - position=1, - key_name='field_names' + found_keywords = ( + {keyword.arg: keyword.value for keyword in keywords} if keywords else {} ) + + name = _extract_namedtuple_arg_or_keyword(position=0, key_name="typename") + names = _extract_namedtuple_arg_or_keyword(position=1, key_name="field_names") if name and names: return name.value, names @@ -90,30 +78,35 @@ def infer_func_form(node, base_type, context=None, enum=False): try: name, names = _find_func_form_arguments(node, context) try: - attributes = names.value.replace(',', ' ').split() + attributes = names.value.replace(",", " ").split() except AttributeError: if not enum: - attributes = [_infer_first(const, context).value - for const in names.elts] + attributes = [ + _infer_first(const, context).value for const in names.elts + ] else: # Enums supports either iterator of (name, value) pairs # or mappings. - if hasattr(names, 'items') and isinstance(names.items, list): - attributes = [_infer_first(const[0], context).value - for const in names.items - if isinstance(const[0], nodes.Const)] - elif hasattr(names, 'elts'): + if hasattr(names, "items") and isinstance(names.items, list): + attributes = [ + _infer_first(const[0], context).value + for const in names.items + if isinstance(const[0], nodes.Const) + ] + elif hasattr(names, "elts"): # Enums can support either ["a", "b", "c"] # or [("a", 1), ("b", 2), ...], but they can't # be mixed. - if all(isinstance(const, nodes.Tuple) - for const in names.elts): - attributes = [_infer_first(const.elts[0], context).value - for const in names.elts - if isinstance(const, nodes.Tuple)] + if all(isinstance(const, nodes.Tuple) for const in names.elts): + attributes = [ + _infer_first(const.elts[0], context).value + for const in names.elts + if isinstance(const, nodes.Tuple) + ] else: - attributes = [_infer_first(const, context).value - for const in names.elts] + attributes = [ + _infer_first(const, context).value for const in names.elts + ] else: raise AttributeError if not attributes: @@ -123,9 +116,9 @@ def infer_func_form(node, base_type, context=None, enum=False): # If we can't infer the name of the class, don't crash, up to this point # we know it is a namedtuple anyway. - name = name or 'Uninferable' + name = name or "Uninferable" # we want to return a Class node instance with proper attributes set - class_node = nodes.ClassDef(name, 'docstring') + class_node = nodes.ClassDef(name, "docstring") class_node.parent = node.parent # set base class=tuple class_node.bases.append(base_type) @@ -156,39 +149,39 @@ def _looks_like(node, name): return False -_looks_like_namedtuple = functools.partial(_looks_like, name='namedtuple') -_looks_like_enum = functools.partial(_looks_like, name='Enum') -_looks_like_typing_namedtuple = functools.partial(_looks_like, name='NamedTuple') +_looks_like_namedtuple = functools.partial(_looks_like, name="namedtuple") +_looks_like_enum = functools.partial(_looks_like, name="Enum") +_looks_like_typing_namedtuple = functools.partial(_looks_like, name="NamedTuple") def infer_named_tuple(node, context=None): """Specific inference function for namedtuple Call node""" - tuple_base_name = nodes.Name(name='tuple', parent=node.root()) + tuple_base_name = nodes.Name(name="tuple", parent=node.root()) class_node, name, attributes = infer_func_form( - node, - tuple_base_name, - context=context, + node, tuple_base_name, context=context ) call_site = arguments.CallSite.from_call(node) - func = next(extract_node('import collections; collections.namedtuple').infer()) + func = next(extract_node("import collections; collections.namedtuple").infer()) try: - rename = next(call_site.infer_argument(func, 'rename', context)).bool_value() + rename = next(call_site.infer_argument(func, "rename", context)).bool_value() except InferenceError: rename = False if rename: attributes = _get_renamed_namedtuple_attributes(attributes) - replace_args = ', '.join( - '{arg}=None'.format(arg=arg) - for arg in attributes - ) + replace_args = ", ".join("{arg}=None".format(arg=arg) for arg in attributes) - field_def = (" {name} = property(lambda self: self[{index:d}], " - "doc='Alias for field number {index:d}')") - field_defs = '\n'.join(field_def.format(name=name, index=index) - for index, name in enumerate(attributes)) - fake = AstroidBuilder(MANAGER).string_build(''' + field_def = ( + " {name} = property(lambda self: self[{index:d}], " + "doc='Alias for field number {index:d}')" + ) + field_defs = "\n".join( + field_def.format(name=name, index=index) + for index, name in enumerate(attributes) + ) + fake = AstroidBuilder(MANAGER).string_build( + """ class %(name)s(tuple): __slots__ = () _fields = %(fields)r @@ -202,14 +195,18 @@ class %(name)s(tuple): def __getnewargs__(self): return tuple(self) %(field_defs)s - ''' % {'name': name, - 'fields': attributes, - 'field_defs': field_defs, - 'replace_args': replace_args}) - class_node.locals['_asdict'] = fake.body[0].locals['_asdict'] - class_node.locals['_make'] = fake.body[0].locals['_make'] - class_node.locals['_replace'] = fake.body[0].locals['_replace'] - class_node.locals['_fields'] = fake.body[0].locals['_fields'] + """ + % { + "name": name, + "fields": attributes, + "field_defs": field_defs, + "replace_args": replace_args, + } + ) + class_node.locals["_asdict"] = fake.body[0].locals["_asdict"] + class_node.locals["_make"] = fake.body[0].locals["_make"] + class_node.locals["_replace"] = fake.body[0].locals["_replace"] + class_node.locals["_fields"] = fake.body[0].locals["_fields"] for attr in attributes: class_node.locals[attr] = fake.body[0].locals[attr] # we use UseInferenceDefault, we can't be a generator so return an iterator @@ -220,16 +217,23 @@ def _get_renamed_namedtuple_attributes(field_names): names = list(field_names) seen = set() for i, name in enumerate(field_names): - if (not all(c.isalnum() or c == '_' for c in name) or keyword.iskeyword(name) - or not name or name[0].isdigit() or name.startswith('_') or name in seen): - names[i] = '_%d' % i + if ( + not all(c.isalnum() or c == "_" for c in name) + or keyword.iskeyword(name) + or not name + or name[0].isdigit() + or name.startswith("_") + or name in seen + ): + names[i] = "_%d" % i seen.add(name) return tuple(names) def infer_enum(node, context=None): """ Specific inference function for enum Call node. """ - enum_meta = extract_node(''' + enum_meta = extract_node( + """ class EnumMeta(object): 'docstring' def __call__(self, node): @@ -255,9 +259,9 @@ def infer_enum(node, context=None): return Value() __members__ = [''] - ''') - class_node = infer_func_form(node, enum_meta, - context=context, enum=True)[0] + """ + ) + class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0] return iter([class_node.instantiate_class()]) @@ -268,12 +272,11 @@ def infer_enum_class(node): # is a hack to support enums. if basename not in ENUM_BASE_NAMES: continue - if node.root().name == 'enum': + if node.root().name == "enum": # Skip if the class is directly from enum module. break for local, values in node.locals.items(): - if any(not isinstance(value, nodes.AssignName) - for value in values): + if any(not isinstance(value, nodes.AssignName) for value in values): continue targets = [] @@ -296,7 +299,8 @@ def infer_enum_class(node): new_targets = [] for target in targets: # Replace all the assignments with our mocked class. - classdef = dedent(''' + classdef = dedent( + """ class {name}({types}): @property def value(self): @@ -304,11 +308,12 @@ def infer_enum_class(node): @property def name(self): return {name} - '''.format( - name=target.name, - types=', '.join(node.basenames), - return_value=inferred_return_value, - )) + """.format( + name=target.name, + types=", ".join(node.basenames), + return_value=inferred_return_value, + ) + ) fake = AstroidBuilder(MANAGER).string_build(classdef)[target.name] fake.parent = target.parent for method in node.mymethods(): @@ -323,21 +328,21 @@ def infer_typing_namedtuple_class(class_node, context=None): """Infer a subclass of typing.NamedTuple""" # Check if it has the corresponding bases annassigns_fields = [ - annassign.target.name for annassign in class_node.body + annassign.target.name + for annassign in class_node.body if isinstance(annassign, nodes.AnnAssign) ] - code = dedent(''' + code = dedent( + """ from collections import namedtuple namedtuple({typename!r}, {fields!r}) - ''').format( - typename=class_node.name, - fields=",".join(annassigns_fields) - ) + """ + ).format(typename=class_node.name, fields=",".join(annassigns_fields)) node = extract_node(code) generated_class_node = next(infer_named_tuple(node, context)) for method in class_node.mymethods(): generated_class_node.locals[method.name] = [method] - return iter((generated_class_node, )) + return iter((generated_class_node,)) def infer_typing_namedtuple(node, context=None): @@ -349,7 +354,7 @@ def infer_typing_namedtuple(node, context=None): except InferenceError: raise UseInferenceDefault - if func.qname() != 'typing.NamedTuple': + if func.qname() != "typing.NamedTuple": raise UseInferenceDefault if len(node.args) != 2: @@ -367,31 +372,27 @@ def infer_typing_namedtuple(node, context=None): names.append(elt.elts[0].as_string()) typename = node.args[0].as_string() - node = extract_node('namedtuple(%(typename)s, (%(fields)s,)) ' % - {'typename': typename, 'fields': ",".join(names)}) + node = extract_node( + "namedtuple(%(typename)s, (%(fields)s,)) " + % {"typename": typename, "fields": ",".join(names)} + ) return infer_named_tuple(node, context) MANAGER.register_transform( - nodes.Call, inference_tip(infer_named_tuple), - _looks_like_namedtuple, + nodes.Call, inference_tip(infer_named_tuple), _looks_like_namedtuple ) +MANAGER.register_transform(nodes.Call, inference_tip(infer_enum), _looks_like_enum) MANAGER.register_transform( - nodes.Call, inference_tip(infer_enum), - _looks_like_enum, -) -MANAGER.register_transform( - nodes.ClassDef, infer_enum_class, - predicate=lambda cls: any(basename for basename in cls.basenames - if basename in ENUM_BASE_NAMES) + nodes.ClassDef, + infer_enum_class, + predicate=lambda cls: any( + basename for basename in cls.basenames if basename in ENUM_BASE_NAMES + ), ) MANAGER.register_transform( - nodes.ClassDef, - inference_tip(infer_typing_namedtuple_class), - _has_namedtuple_base, + nodes.ClassDef, inference_tip(infer_typing_namedtuple_class), _has_namedtuple_base ) MANAGER.register_transform( - nodes.Call, - inference_tip(infer_typing_namedtuple), - _looks_like_typing_namedtuple, + nodes.Call, inference_tip(infer_typing_namedtuple), _looks_like_typing_namedtuple ) diff --git a/astroid/brain/brain_nose.py b/astroid/brain/brain_nose.py index 6aec041b..7b12d760 100644 --- a/astroid/brain/brain_nose.py +++ b/astroid/brain/brain_nose.py @@ -16,30 +16,34 @@ import astroid.builder _BUILDER = astroid.builder.AstroidBuilder(astroid.MANAGER) -def _pep8(name, caps=re.compile('([A-Z])')): - return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) +def _pep8(name, caps=re.compile("([A-Z])")): + return caps.sub(lambda m: "_" + m.groups()[0].lower(), name) def _nose_tools_functions(): """Get an iterator of names and bound methods.""" - module = _BUILDER.string_build(textwrap.dedent(''' + module = _BUILDER.string_build( + textwrap.dedent( + """ import unittest class Test(unittest.TestCase): pass a = Test() - ''')) + """ + ) + ) try: - case = next(module['a'].infer()) + case = next(module["a"].infer()) except astroid.InferenceError: return for method in case.methods(): - if method.name.startswith('assert') and '_' not in method.name: + if method.name.startswith("assert") and "_" not in method.name: pep8_name = _pep8(method.name) yield pep8_name, astroid.BoundMethod(method, case) - if method.name == 'assertEqual': + if method.name == "assertEqual": # nose also exports assert_equals. - yield 'assert_equals', astroid.BoundMethod(method, case) + yield "assert_equals", astroid.BoundMethod(method, case) def _nose_tools_transform(node): @@ -49,8 +53,8 @@ def _nose_tools_transform(node): def _nose_tools_trivial_transform(): """Custom transform for the nose.tools module.""" - stub = _BUILDER.string_build('''__all__ = []''') - all_entries = ['ok_', 'eq_'] + stub = _BUILDER.string_build("""__all__ = []""") + all_entries = ["ok_", "eq_"] for pep8_name, method in _nose_tools_functions(): all_entries.append(pep8_name) @@ -58,14 +62,16 @@ def _nose_tools_trivial_transform(): # Update the __all__ variable, since nose.tools # does this manually with .append. - all_assign = stub['__all__'].parent + all_assign = stub["__all__"].parent all_object = astroid.List(all_entries) all_object.parent = all_assign all_assign.value = all_object return stub -astroid.register_module_extender(astroid.MANAGER, 'nose.tools.trivial', - _nose_tools_trivial_transform) -astroid.MANAGER.register_transform(astroid.Module, _nose_tools_transform, - lambda n: n.name == 'nose.tools') +astroid.register_module_extender( + astroid.MANAGER, "nose.tools.trivial", _nose_tools_trivial_transform +) +astroid.MANAGER.register_transform( + astroid.Module, _nose_tools_transform, lambda n: n.name == "nose.tools" +) diff --git a/astroid/brain/brain_numpy.py b/astroid/brain/brain_numpy.py index e32e3401..9d31a476 100644 --- a/astroid/brain/brain_numpy.py +++ b/astroid/brain/brain_numpy.py @@ -12,7 +12,8 @@ import astroid def numpy_random_mtrand_transform(): - return astroid.parse(''' + return astroid.parse( + """ def beta(a, b, size=None): pass def binomial(n, p, size=None): pass def bytes(length): pass @@ -60,13 +61,17 @@ def numpy_random_mtrand_transform(): def wald(mean, scale, size=None): pass def weibull(a, size=None): pass def zipf(a, size=None): pass - ''') + """ + ) def numpy_core_umath_transform(): - ufunc_optional_keyword_arguments = ("""out=None, where=True, casting='same_kind', order='K', """ - """dtype=None, subok=True""") - return astroid.parse(''' + ufunc_optional_keyword_arguments = ( + """out=None, where=True, casting='same_kind', order='K', """ + """dtype=None, subok=True""" + ) + return astroid.parse( + """ # Constants e = 2.718281828459045 euler_gamma = 0.5772156649015329 @@ -114,7 +119,7 @@ def numpy_core_umath_transform(): def tan(x, {opt_args:s}): pass def tanh(x, {opt_args:s}): pass def trunc(x, {opt_args:s}): pass - + # Two args functions with optional kwargs def bitwise_and(x1, x2, {opt_args:s}): pass def bitwise_or(x1, x2, {opt_args:s}): pass @@ -146,11 +151,15 @@ def numpy_core_umath_transform(): def right_shift(x1, x2, {opt_args:s}): pass def subtract(x1, x2, {opt_args:s}): pass def true_divide(x1, x2, {opt_args:s}): pass - '''.format(opt_args=ufunc_optional_keyword_arguments)) + """.format( + opt_args=ufunc_optional_keyword_arguments + ) + ) def numpy_core_numerictypes_transform(): - return astroid.parse(''' + return astroid.parse( + """ # different types defined in numerictypes.py class generic(object): def __init__(self, value): @@ -349,7 +358,7 @@ def numpy_core_numerictypes_transform(): class bool_(generic): pass class number(generic): pass class datetime64(generic): pass - + class void(flexible): def __init__(self, *args, **kwargs): @@ -375,7 +384,7 @@ def numpy_core_numerictypes_transform(): class str_(str, character): def maketrans(self, x, y=None, z=None): pass - + class bytes_(bytes, character): def fromhex(self, string): pass def maketrans(self, frm, to): pass @@ -394,9 +403,9 @@ def numpy_core_numerictypes_transform(): class float64(floating, float): - def fromhex(self, string): pass + def fromhex(self, string): pass + - class uint64(unsignedinteger): pass class complex64(complexfloating): pass class int16(signedinteger): pass @@ -453,20 +462,27 @@ def numpy_core_numerictypes_transform(): unicode_ = str_ ushort = uint16 void0 = void - ''') + """ + ) def numpy_funcs(): - return astroid.parse(''' + return astroid.parse( + """ import builtins def sum(a, axis=None, dtype=None, out=None, keepdims=None): return builtins.sum(a) - ''') - - -astroid.register_module_extender(astroid.MANAGER, 'numpy.core.umath', numpy_core_umath_transform) -astroid.register_module_extender(astroid.MANAGER, 'numpy.random.mtrand', - numpy_random_mtrand_transform) -astroid.register_module_extender(astroid.MANAGER, 'numpy.core.numerictypes', - numpy_core_numerictypes_transform) -astroid.register_module_extender(astroid.MANAGER, 'numpy', numpy_funcs) + """ + ) + + +astroid.register_module_extender( + astroid.MANAGER, "numpy.core.umath", numpy_core_umath_transform +) +astroid.register_module_extender( + astroid.MANAGER, "numpy.random.mtrand", numpy_random_mtrand_transform +) +astroid.register_module_extender( + astroid.MANAGER, "numpy.core.numerictypes", numpy_core_numerictypes_transform +) +astroid.register_module_extender(astroid.MANAGER, "numpy", numpy_funcs) diff --git a/astroid/brain/brain_pkg_resources.py b/astroid/brain/brain_pkg_resources.py index 7863105c..25e76495 100644 --- a/astroid/brain/brain_pkg_resources.py +++ b/astroid/brain/brain_pkg_resources.py @@ -13,7 +13,8 @@ from astroid import MANAGER def pkg_resources_transform(): - return parse(''' + return parse( + """ def require(*requirements): return pkg_resources.working_set.require(*requirements) @@ -67,6 +68,8 @@ def get_distribution(dist): return Distribution(dist) _namespace_packages = {} -''') +""" + ) -register_module_extender(MANAGER, 'pkg_resources', pkg_resources_transform) + +register_module_extender(MANAGER, "pkg_resources", pkg_resources_transform) diff --git a/astroid/brain/brain_pytest.py b/astroid/brain/brain_pytest.py index 01132f89..d7e3ac8a 100644 --- a/astroid/brain/brain_pytest.py +++ b/astroid/brain/brain_pytest.py @@ -14,7 +14,8 @@ from astroid.builder import AstroidBuilder def pytest_transform(): - return AstroidBuilder(MANAGER).string_build(''' + return AstroidBuilder(MANAGER).string_build( + """ try: import _pytest.mark @@ -79,7 +80,9 @@ except ImportError: yield_fixture = _pytest.python.yield_fixture except ImportError: pass -''') +""" + ) -register_module_extender(MANAGER, 'pytest', pytest_transform) -register_module_extender(MANAGER, 'py.test', pytest_transform) + +register_module_extender(MANAGER, "pytest", pytest_transform) +register_module_extender(MANAGER, "py.test", pytest_transform) diff --git a/astroid/brain/brain_qt.py b/astroid/brain/brain_qt.py index d8fcc0b4..d65f2185 100644 --- a/astroid/brain/brain_qt.py +++ b/astroid/brain/brain_qt.py @@ -14,10 +14,10 @@ from astroid import nodes from astroid import parse -def _looks_like_signal(node, signal_name='pyqtSignal'): - if '__class__' in node.instance_attrs: +def _looks_like_signal(node, signal_name="pyqtSignal"): + if "__class__" in node.instance_attrs: try: - cls = node.instance_attrs['__class__'][0] + cls = node.instance_attrs["__class__"][0] return cls.name == signal_name except AttributeError: # return False if the cls does not have a name attribute @@ -26,7 +26,8 @@ def _looks_like_signal(node, signal_name='pyqtSignal'): def transform_pyqt_signal(node): - module = parse(''' + module = parse( + """ class pyqtSignal(object): def connect(self, slot, type=None, no_receiver_check=False): pass @@ -34,15 +35,17 @@ def transform_pyqt_signal(node): pass def emit(self, *args): pass - ''') - signal_cls = module['pyqtSignal'] - node.instance_attrs['emit'] = signal_cls['emit'] - node.instance_attrs['disconnect'] = signal_cls['disconnect'] - node.instance_attrs['connect'] = signal_cls['connect'] + """ + ) + signal_cls = module["pyqtSignal"] + node.instance_attrs["emit"] = signal_cls["emit"] + node.instance_attrs["disconnect"] = signal_cls["disconnect"] + node.instance_attrs["connect"] = signal_cls["connect"] def transform_pyside_signal(node): - module = parse(''' + module = parse( + """ class NotPySideSignal(object): def connect(self, receiver, type=None): pass @@ -50,25 +53,30 @@ def transform_pyside_signal(node): pass def emit(self, *args): pass - ''') - signal_cls = module['NotPySideSignal'] - node.instance_attrs['connect'] = signal_cls['connect'] - node.instance_attrs['disconnect'] = signal_cls['disconnect'] - node.instance_attrs['emit'] = signal_cls['emit'] + """ + ) + signal_cls = module["NotPySideSignal"] + node.instance_attrs["connect"] = signal_cls["connect"] + node.instance_attrs["disconnect"] = signal_cls["disconnect"] + node.instance_attrs["emit"] = signal_cls["emit"] def pyqt4_qtcore_transform(): - return AstroidBuilder(MANAGER).string_build(''' + return AstroidBuilder(MANAGER).string_build( + """ def SIGNAL(signal_name): pass class QObject(object): def emit(self, signal): pass -''') +""" + ) -register_module_extender(MANAGER, 'PyQt4.QtCore', pyqt4_qtcore_transform) -MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal, - _looks_like_signal) -MANAGER.register_transform(nodes.ClassDef, transform_pyside_signal, - lambda node: node.qname() == 'PySide.QtCore.Signal') +register_module_extender(MANAGER, "PyQt4.QtCore", pyqt4_qtcore_transform) +MANAGER.register_transform(nodes.FunctionDef, transform_pyqt_signal, _looks_like_signal) +MANAGER.register_transform( + nodes.ClassDef, + transform_pyside_signal, + lambda node: node.qname() == "PySide.QtCore.Signal", +) diff --git a/astroid/brain/brain_random.py b/astroid/brain/brain_random.py index c76798d2..678f6001 100644 --- a/astroid/brain/brain_random.py +++ b/astroid/brain/brain_random.py @@ -7,33 +7,19 @@ from astroid import helpers from astroid import MANAGER -ACCEPTED_ITERABLES_FOR_SAMPLE = ( - astroid.List, - astroid.Set, - astroid.Tuple, -) +ACCEPTED_ITERABLES_FOR_SAMPLE = (astroid.List, astroid.Set, astroid.Tuple) def _clone_node_with_lineno(node, parent, lineno): cls = node.__class__ other_fields = node._other_fields _astroid_fields = node._astroid_fields - init_params = { - 'lineno': lineno, - 'col_offset': node.col_offset, - 'parent': parent - } - postinit_params = { - param: getattr(node, param) - for param in _astroid_fields - } + init_params = {"lineno": lineno, "col_offset": node.col_offset, "parent": parent} + postinit_params = {param: getattr(node, param) for param in _astroid_fields} if other_fields: - init_params.update({ - param: getattr(node, param) - for param in other_fields - }) + init_params.update({param: getattr(node, param) for param in other_fields}) new_node = cls(**init_params) - if hasattr(node, 'postinit') and _astroid_fields: + if hasattr(node, "postinit") and _astroid_fields: new_node.postinit(**postinit_params) return new_node @@ -65,33 +51,25 @@ def infer_random_sample(node, context=None): raise astroid.UseInferenceDefault new_node = astroid.List( - lineno=node.lineno, - col_offset=node.col_offset, - parent=node.scope(), + lineno=node.lineno, col_offset=node.col_offset, parent=node.scope() ) new_elts = [ - _clone_node_with_lineno( - elt, - parent=new_node, - lineno=new_node.lineno - ) + _clone_node_with_lineno(elt, parent=new_node, lineno=new_node.lineno) for elt in elts ] new_node.postinit(new_elts) - return iter((new_node, )) + return iter((new_node,)) def _looks_like_random_sample(node): func = node.func if isinstance(func, astroid.Attribute): - return func.attrname == 'sample' + return func.attrname == "sample" if isinstance(func, astroid.Name): - return func.name == 'sample' + return func.name == "sample" return False MANAGER.register_transform( - astroid.Call, - astroid.inference_tip(infer_random_sample), - _looks_like_random_sample, + astroid.Call, astroid.inference_tip(infer_random_sample), _looks_like_random_sample ) diff --git a/astroid/brain/brain_re.py b/astroid/brain/brain_re.py index f6e1befd..c7ee51a5 100644 --- a/astroid/brain/brain_re.py +++ b/astroid/brain/brain_re.py @@ -10,7 +10,8 @@ if PY36: # where every entry will be exposed via updating globals() def _re_transform(): - return astroid.parse(''' + return astroid.parse( + """ import sre_compile ASCII = sre_compile.SRE_FLAG_ASCII IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE @@ -29,6 +30,7 @@ if PY36: TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE T = TEMPLATE DEBUG = sre_compile.SRE_FLAG_DEBUG - ''') + """ + ) - astroid.register_module_extender(astroid.MANAGER, 're', _re_transform) + astroid.register_module_extender(astroid.MANAGER, "re", _re_transform) diff --git a/astroid/brain/brain_six.py b/astroid/brain/brain_six.py index 30ecca35..b342fbf5 100644 --- a/astroid/brain/brain_six.py +++ b/astroid/brain/brain_six.py @@ -12,11 +12,15 @@ from textwrap import dedent from astroid import MANAGER, register_module_extender from astroid.builder import AstroidBuilder -from astroid.exceptions import AstroidBuildingError, InferenceError, AttributeInferenceError +from astroid.exceptions import ( + AstroidBuildingError, + InferenceError, + AttributeInferenceError, +) from astroid import nodes -SIX_ADD_METACLASS = 'six.add_metaclass' +SIX_ADD_METACLASS = "six.add_metaclass" def _indent(text, prefix, predicate=None): @@ -33,7 +37,8 @@ def _indent(text, prefix, predicate=None): def prefixed_lines(): for line in text.splitlines(True): yield prefix + line if predicate(line) else line - return ''.join(prefixed_lines()) + + return "".join(prefixed_lines()) _IMPORTS = """ @@ -102,13 +107,15 @@ import urllib.error as urllib_error def six_moves_transform(): - code = dedent(''' + code = dedent( + """ class Moves(object): {} moves = Moves() - ''').format(_indent(_IMPORTS, " ")) + """ + ).format(_indent(_IMPORTS, " ")) module = AstroidBuilder(MANAGER).string_build(code) - module.name = 'six.moves' + module.name = "six.moves" return module @@ -126,12 +133,11 @@ def _six_fail_hook(modname): :rtype: nodes.Module """ - attribute_of = (modname != "six.moves" and - modname.startswith("six.moves")) - if modname != 'six.moves' and not attribute_of: + attribute_of = modname != "six.moves" and modname.startswith("six.moves") + if modname != "six.moves" and not attribute_of: raise AstroidBuildingError(modname=modname) module = AstroidBuilder(MANAGER).string_build(_IMPORTS) - module.name = 'six.moves' + module.name = "six.moves" if attribute_of: # Facilitate import of submodules in Moves start_index = len(module.name) @@ -182,9 +188,10 @@ def transform_six_add_metaclass(node): return node -register_module_extender(MANAGER, 'six', six_moves_transform) -register_module_extender(MANAGER, 'requests.packages.urllib3.packages.six', - six_moves_transform) +register_module_extender(MANAGER, "six", six_moves_transform) +register_module_extender( + MANAGER, "requests.packages.urllib3.packages.six", six_moves_transform +) MANAGER.register_failed_import_hook(_six_fail_hook) MANAGER.register_transform( nodes.ClassDef, diff --git a/astroid/brain/brain_ssl.py b/astroid/brain/brain_ssl.py index 132e827d..a42e04c7 100644 --- a/astroid/brain/brain_ssl.py +++ b/astroid/brain/brain_ssl.py @@ -13,7 +13,8 @@ from astroid import parse def ssl_transform(): - return parse(''' + return parse( + """ from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION from _ssl import _SSLContext, MemoryBIO from _ssl import ( @@ -65,7 +66,8 @@ def ssl_transform(): from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN from _ssl import _OPENSSL_API_VERSION from _ssl import PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 - ''') + """ + ) -register_module_extender(MANAGER, 'ssl', ssl_transform) +register_module_extender(MANAGER, "ssl", ssl_transform) diff --git a/astroid/brain/brain_subprocess.py b/astroid/brain/brain_subprocess.py index 8d654705..bba7ff3f 100644 --- a/astroid/brain/brain_subprocess.py +++ b/astroid/brain/brain_subprocess.py @@ -20,8 +20,8 @@ PY33 = sys.version_info >= (3, 3) def _subprocess_transform(): if six.PY3: - communicate = (bytes('string', 'ascii'), bytes('string', 'ascii')) - communicate_signature = 'def communicate(self, input=None, timeout=None)' + communicate = (bytes("string", "ascii"), bytes("string", "ascii")) + communicate_signature = "def communicate(self, input=None, timeout=None)" if PY36: init = """ def __init__(self, args, bufsize=0, executable=None, @@ -44,8 +44,8 @@ def _subprocess_transform(): pass """ else: - communicate = ('string', 'string') - communicate_signature = 'def communicate(self, input=None)' + communicate = ("string", "string") + communicate_signature = "def communicate(self, input=None)" init = """ def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, @@ -55,20 +55,21 @@ def _subprocess_transform(): pass """ if PY34: - wait_signature = 'def wait(self, timeout=None)' + wait_signature = "def wait(self, timeout=None)" else: - wait_signature = 'def wait(self)' + wait_signature = "def wait(self)" if six.PY3: - ctx_manager = ''' + ctx_manager = """ def __enter__(self): return self def __exit__(self, *args): pass - ''' + """ else: - ctx_manager = '' + ctx_manager = "" py3_args = "" if PY33: py3_args = "args = []" - code = textwrap.dedent(''' + code = textwrap.dedent( + """ class Popen(object): returncode = pid = 0 stdin = stdout = stderr = file() @@ -87,17 +88,20 @@ def _subprocess_transform(): def kill(self): pass %(ctx_manager)s - ''' % {'communicate': communicate, - 'communicate_signature': communicate_signature, - 'wait_signature': wait_signature, - 'ctx_manager': ctx_manager, - 'py3_args': py3_args, - }) + """ + % { + "communicate": communicate, + "communicate_signature": communicate_signature, + "wait_signature": wait_signature, + "ctx_manager": ctx_manager, + "py3_args": py3_args, + } + ) init_lines = textwrap.dedent(init).splitlines() - indented_init = '\n'.join([' ' * 4 + line for line in init_lines]) + indented_init = "\n".join([" " * 4 + line for line in init_lines]) code += indented_init return astroid.parse(code) -astroid.register_module_extender(astroid.MANAGER, 'subprocess', _subprocess_transform) +astroid.register_module_extender(astroid.MANAGER, "subprocess", _subprocess_transform) diff --git a/astroid/brain/brain_threading.py b/astroid/brain/brain_threading.py index 2313fbe4..77f5bde2 100644 --- a/astroid/brain/brain_threading.py +++ b/astroid/brain/brain_threading.py @@ -8,7 +8,8 @@ import astroid def _thread_transform(): - return astroid.parse(''' + return astroid.parse( + """ class lock(object): def acquire(self, blocking=True, timeout=-1): pass @@ -21,7 +22,8 @@ def _thread_transform(): def Lock(): return lock() - ''') + """ + ) -astroid.register_module_extender(astroid.MANAGER, 'threading', _thread_transform) +astroid.register_module_extender(astroid.MANAGER, "threading", _thread_transform) diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py index 5aa7bee5..cd9a2f40 100644 --- a/astroid/brain/brain_typing.py +++ b/astroid/brain/brain_typing.py @@ -17,12 +17,9 @@ from astroid import ( ) -TYPING_NAMEDTUPLE_BASENAMES = { - 'NamedTuple', - 'typing.NamedTuple' -} -TYPING_TYPEVARS = {'TypeVar', 'NewType'} -TYPING_TYPEVARS_QUALIFIED = {'typing.TypeVar', 'typing.NewType'} +TYPING_NAMEDTUPLE_BASENAMES = {"NamedTuple", "typing.NamedTuple"} +TYPING_TYPEVARS = {"TypeVar", "NewType"} +TYPING_TYPEVARS_QUALIFIED = {"typing.TypeVar", "typing.NewType"} TYPING_TYPE_TEMPLATE = """ class Meta(type): def __getitem__(self, item): @@ -78,20 +75,18 @@ def infer_typing_attr(node, context=None): except InferenceError as exc: raise UseInferenceDefault from exc - if not value.qname().startswith('typing.'): + if not value.qname().startswith("typing."): raise UseInferenceDefault - node = extract_node(TYPING_TYPE_TEMPLATE.format(value.qname().split('.')[-1])) + node = extract_node(TYPING_TYPE_TEMPLATE.format(value.qname().split(".")[-1])) return node.infer(context=context) MANAGER.register_transform( nodes.Call, inference_tip(infer_typing_typevar_or_newtype), - looks_like_typing_typevar_or_newtype + looks_like_typing_typevar_or_newtype, ) MANAGER.register_transform( - nodes.Subscript, - inference_tip(infer_typing_attr), - _looks_like_typing_subscript, + nodes.Subscript, inference_tip(infer_typing_attr), _looks_like_typing_subscript ) diff --git a/astroid/brain/brain_uuid.py b/astroid/brain/brain_uuid.py index ea3b277a..8bda631d 100644 --- a/astroid/brain/brain_uuid.py +++ b/astroid/brain/brain_uuid.py @@ -12,11 +12,9 @@ from astroid import nodes def _patch_uuid_class(node): # The .int member is patched using __dict__ - node.locals['int'] = [nodes.Const(0, parent=node)] + node.locals["int"] = [nodes.Const(0, parent=node)] MANAGER.register_transform( - nodes.ClassDef, - _patch_uuid_class, - lambda node: node.qname() == 'uuid.UUID' + nodes.ClassDef, _patch_uuid_class, lambda node: node.qname() == "uuid.UUID" ) |