• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python astroid.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中astroid.parse函数的典型用法代码示例。如果您正苦于以下问题:Python parse函数的具体用法?Python parse怎么用?Python parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _multiprocessing_transform

def _multiprocessing_transform():
    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('''
    from multiprocessing.context import DefaultContext, BaseContext
    default = DefaultContext()
    base = BaseContext()
    ''')
    try:
        context = next(node['default'].infer())
        base = next(node['base'].infer())
    except exceptions.InferenceError:
        return module

    for node in (context, base):
        for key, value in node.locals.items():
            if key.startswith("_"):
                continue

            value = value[0]
            if isinstance(value, astroid.FunctionDef):
                # We need to rebound this, since otherwise
                # it will have an extra argument (self).
                value = astroid.BoundMethod(value, node)
            module[key] = value
    return module
开发者ID:my88899,项目名称:astroid,代码行数:35,代码来源:brain_multiprocessing.py


示例2: test_absolute_import

 def test_absolute_import(self):
     module_import = astroid.parse(
         'from __future__ import absolute_import; import os')
     module_from = astroid.parse(
         'from __future__ import absolute_import; from os import path')
     with self.assertNoMessages():
         for module in (module_import, module_from):
             self.walk(module)
开发者ID:Vauxoo,项目名称:pylint,代码行数:8,代码来源:unittest_checker_python3.py


示例3: test_raise_python_2

    def test_raise_python_2(self):
        first = 'raise'
        self.assertEqual(parse(first).as_string().strip(), first)

        second = 'raise 1, 2'
        self.assertEqual(parse(second).as_string().strip(), second)

        third = 'raise 1, 2, 3'
        self.assertEqual(parse(third).as_string().strip(), third)
开发者ID:PCManticore,项目名称:astroid,代码行数:9,代码来源:unittest_nodes.py


示例4: test_modules_as_string

 def test_modules_as_string(self):
     for name in (os.path.join(p, n) for p, _, ns in os.walk('astroid/') for n in ns if n.endswith('.py')):
         with open(name, 'r') as source_file:
             ast = parse(source_file.read())
             # if ast != parse(ast.as_string()):
             #     print(name)
             #     print(ast == ast)
             #     ast.print_tree()
             #     parse(ast.as_string()).print_tree()
             self.assertEqual(ast, parse(ast.as_string()))
开发者ID:PCManticore,项目名称:astroid,代码行数:10,代码来源:unittest_nodes.py


示例5: test_module_level_names

    def test_module_level_names(self):
        assign = astroid.extract_node("""
        import collections
        Class = collections.namedtuple("a", ("b", "c")) #@
        """)
        with self.assertNoMessages():
            self.checker.visit_assignname(assign.targets[0])

        assign = astroid.extract_node("""
        class ClassA(object):
            pass
        ClassB = ClassA
        """)
        with self.assertNoMessages():
            self.checker.visit_assignname(assign.targets[0])

        module = astroid.parse("""
        def A():
          return 1, 2, 3
        CONSTA, CONSTB, CONSTC = A()
        CONSTD = A()""")
        with self.assertNoMessages():
            self.checker.visit_assignname(module.body[1].targets[0].elts[0])
            self.checker.visit_assignname(module.body[2].targets[0])

        assign = astroid.extract_node("""
        CONST = "12 34 ".rstrip().split()""")
        with self.assertNoMessages():
            self.checker.visit_assignname(assign.targets[0])
开发者ID:glennmatthews,项目名称:pylint,代码行数:29,代码来源:unittest_checker_base.py


示例6: _hashlib_transform

def _hashlib_transform():
    template = '''
    class %(name)s(object):
      def __init__(self, value=''): pass
      def digest(self):
        return %(digest)s
      def copy(self):
        return self
      def update(self, value): pass
      def hexdigest(self):
        return ''
      @property
      def name(self):
        return %(name)r
      @property
      def block_size(self):
        return 1
      @property
      def digest_size(self):
        return 1
    '''
    algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
    classes = "".join(
        template % {'name': hashfunc, 'digest': 'b""' if six.PY3 else '""'}
        for hashfunc in algorithms)
    return astroid.parse(classes)
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:26,代码来源:brain_hashlib.py


示例7: test_invalid_metaclass

    def test_invalid_metaclass(self):
        module = astroid.parse(
            """
        import six

        class InvalidAsMetaclass(object):
            pass

        @six.add_metaclass(int)
        class FirstInvalid(object):
            pass

        @six.add_metaclass(InvalidAsMetaclass)
        class SecondInvalid(object):
            pass

        @six.add_metaclass(2)
        class ThirdInvalid(object):
            pass
        """
        )
        for class_obj, metaclass_name in (
            ("ThirdInvalid", "2"),
            ("SecondInvalid", "InvalidAsMetaclass"),
            ("FirstInvalid", "int"),
        ):
            classdef = module[class_obj]
            message = Message(
                "invalid-metaclass", node=classdef, args=(metaclass_name,)
            )
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef)
开发者ID:bluesheeptoken,项目名称:pylint,代码行数:32,代码来源:unittest_checker_typecheck.py


示例8: numpy_core_numerictypes_transform

def numpy_core_numerictypes_transform():
    return astroid.parse('''
    # different types defined in numerictypes.py
    uint16 = type('uint16') 
    uint32 = type('uint32')
    uint64 = type('uint64')
    int128 = type('int128')
    uint128 = type('uint128')
    float16 = type('float16')
    float32 = type('float32')
    float64 = type('float64')
    float80 = type('float80')
    float96 = type('float96')
    float128 = type('float128')
    float256 = type('float256')
    complex32 = type('complex32')
    complex64 = type('complex64')
    complex128 = type('complex128')
    complex160 = type('complex160')
    complex192 = type('complex192')
    complex256 = type('complex256')
    complex512 = type('complex512')
    timedelta64 = type('timedelta64')
    datetime64 = type('datetime64')
    unicode_ = type('unicode_')
    string_ = type('string_')
    object_ = type('object_')
    ''')
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:28,代码来源:brain_numpy.py


示例9: test_invalid_metaclass

    def test_invalid_metaclass(self):
        module = astroid.parse('''
        import six

        class InvalidAsMetaclass(object):
            pass

        @six.add_metaclass(int)
        class FirstInvalid(object):
            pass

        @six.add_metaclass(InvalidAsMetaclass)
        class SecondInvalid(object):
            pass

        @six.add_metaclass(2)
        class ThirdInvalid(object):
            pass
        ''')
        for class_obj, metaclass_name in (('ThirdInvalid', '2'),
                                          ('SecondInvalid', 'InvalidAsMetaclass'),
                                          ('FirstInvalid', 'int')):
            classdef = module[class_obj]
            message = Message('invalid-metaclass', node=classdef, args=(metaclass_name, ))
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef)
开发者ID:eriksf,项目名称:dotfiles,代码行数:26,代码来源:unittest_checker_typecheck.py


示例10: test_ignored_argument_names_starred_args

 def test_ignored_argument_names_starred_args(self):
     node = astroid.parse('''
     def fooby(*args, **kwargs):
         pass
     ''')
     with self.assertNoMessages():
         self.walk(node)
开发者ID:Marslo,项目名称:VimConfig,代码行数:7,代码来源:unittest_checker_variables.py


示例11: test_deprecated_methods

    def test_deprecated_methods(self):
        class Checker(object):
            def __init__(self):
                self.called = False

            @check_messages('first-message')
            def visit_assname(self, node):
                self.called = True

        linter = self.MockLinter({'first-message': True})
        walker = utils.PyLintASTWalker(linter)
        checker = Checker()
        walker.add_checker(checker)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            walker.walk(astroid.parse("x = 1"))

        if __pkginfo__.numversion < (2, 0):
            expected = ('Implemented method visit_assname instead of '
                        'visit_assignname. This will be supported until '
                        'Pylint 2.0.')
            self.assertEqual(len(w), 1)
            self.assertIsInstance(w[0].message, PendingDeprecationWarning)
            self.assertEqual(str(w[0].message), expected)
            self.assertTrue(checker.called)
        else:
            self.assertNotEqual(len(w), 1)
            self.assertFalse(checker.called)
开发者ID:arusahni,项目名称:pylint,代码行数:28,代码来源:unittest_utils.py


示例12: _collections_transform

def _collections_transform():
    return astroid.parse('''
    class defaultdict(dict):
        default_factory = None
        def __missing__(self, key): pass

    class deque(object):
        maxlen = 0
        def __init__(self, iterable=None, maxlen=None):
            self.iterable = iterable
        def append(self, x): pass
        def appendleft(self, x): pass
        def clear(self): pass
        def count(self, x): return 0
        def extend(self, iterable): pass
        def extendleft(self, iterable): pass
        def pop(self): pass
        def popleft(self): pass
        def remove(self, value): pass
        def reverse(self): pass
        def rotate(self, n): pass
        def __iter__(self): return self
        def __reversed__(self): return self.iterable[::-1]
        def __getitem__(self, index): pass
        def __setitem__(self, index, value): pass
        def __delitem__(self, index): pass
    ''')
开发者ID:PyCQA,项目名称:astroid,代码行数:27,代码来源:brain_collections.py


示例13: test_check_messages

 def test_check_messages(self):
     linter = self.MockLinter({"first-message": True, "second-message": False, "third-message": True})
     walker = utils.PyLintASTWalker(linter)
     checker = self.Checker()
     walker.add_checker(checker)
     walker.walk(astroid.parse("x = func()"))
     self.assertEqual(set(["module", "assname"]), checker.called)
开发者ID:PyCQA,项目名称:pylint,代码行数:7,代码来源:unittest_utils.py


示例14: test_func_signature_issue_185

 def test_func_signature_issue_185(self):
     code = textwrap.dedent('''
     def test(a, b, c=42, *, x=42, **kwargs):
         print(a, b, c, args)
     ''')
     node = parse(code)
     self.assertEqual(node.as_string().strip(), code.strip())
开发者ID:rogalski,项目名称:astroid,代码行数:7,代码来源:unittest_nodes.py


示例15: test_priority_to_local_defined_values

 def test_priority_to_local_defined_values(self):
     ast_node = astroid.parse('''
     __file__ = "mine"
     ''')
     file_value = next(ast_node.igetattr('__file__'))
     self.assertIsInstance(file_value, astroid.Const)
     self.assertEqual(file_value.value, "mine")
开发者ID:PyCQA,项目名称:astroid,代码行数:7,代码来源:unittest_object_model.py


示例16: test_dict_methods_in_iterating_context

    def test_dict_methods_in_iterating_context(self):
        iterating_code = [
            'for x in {}: pass',
            '(x for x in {})',
            '[x for x in {}]',
            'func({})',
            'a, b = {}'
        ]
        non_iterating_code = [
            'x = __({}())',
            '__({}())[0]'
        ]

        for method in ('keys', 'items', 'values'):
            dict_method = '{{}}.{}'.format(method)

            for code in iterating_code:
                with_value = code.format(dict_method)
                module = astroid.parse(with_value)
                with self.assertNoMessages():
                    self.walk(module)

            for code in non_iterating_code:
                with_value = code.format(dict_method)
                node = astroid.extract_node(with_value)

                checker = 'dict-{}-not-iterating'.format(method)
                message = testutils.Message(checker, node=node)
                with self.assertAddsMessages(message):
                    self.checker.visit_call(node)
开发者ID:eladm26,项目名称:pylint,代码行数:30,代码来源:unittest_checker_python3.py


示例17: test_redefined_builtin_modname_not_ignored

 def test_redefined_builtin_modname_not_ignored(self):
     node = astroid.parse('''
     from future.builtins import open
     ''')
     with self.assertAddsMessages(
             Message('redefined-builtin', node=node.body[0], args='open')):
         self.checker.visit_module(node)
开发者ID:glennmatthews,项目名称:pylint,代码行数:7,代码来源:unittest_checker_variables.py


示例18: test_dont_crash_on_invalid_format_string

 def test_dont_crash_on_invalid_format_string(self):
     node = astroid.parse(
         """
     import logging
     logging.error('0} - {1}'.format(1, 2))
     """
     )
     self.walk(node)
开发者ID:aluoch-sheila,项目名称:NEIGHBOURHOOD,代码行数:8,代码来源:unittest_checker_logging.py


示例19: _collections_transform

def _collections_transform():
    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())
开发者ID:eriksf,项目名称:dotfiles,代码行数:8,代码来源:brain_collections.py


示例20: test_redefined_builtin_custom_modules

 def test_redefined_builtin_custom_modules(self):
     node = astroid.parse(
         """
     from os import open
     """
     )
     with self.assertNoMessages():
         self.checker.visit_module(node)
开发者ID:aluoch-sheila,项目名称:NEIGHBOURHOOD,代码行数:8,代码来源:unittest_checker_variables.py



注:本文中的astroid.parse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python astroid.register_module_extender函数代码示例发布时间:2022-05-24
下一篇:
Python astroid.extract_node函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap