コード例 #1
0
            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"]


def pyqt4_qtcore_transform():
    return AstroidBuilder(AstroidManager()).string_build("""

def SIGNAL(signal_name): pass

class QObject(object):
    def emit(self, signal): pass
""")


register_module_extender(AstroidManager(), "PyQt4.QtCore",
                         pyqt4_qtcore_transform)
AstroidManager().register_transform(nodes.FunctionDef, transform_pyqt_signal,
                                    _looks_like_signal)
AstroidManager().register_transform(
    nodes.ClassDef,
    transform_pyside_signal,
    lambda node: node.qname() in
    {"PySide.QtCore.Signal", "PySide2.QtCore.Signal"},
)
コード例 #2
0
# Copyright (c) 2019-2021 hippo91 <*****@*****.**>
# Copyright (c) 2020 Claudiu Popa <*****@*****.**>
# Copyright (c) 2021 Pierre Sassoulas <*****@*****.**>
# Copyright (c) 2021 Marc Mueller <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
"""Astroid hooks for numpy.core.fromnumeric module."""
from astroid.brain.helpers import register_module_extender
from astroid.builder import parse
from astroid.manager import AstroidManager


def numpy_core_fromnumeric_transform():
    return parse("""
    def sum(a, axis=None, dtype=None, out=None, keepdims=None, initial=None):
        return numpy.ndarray([0, 0])
    """)


register_module_extender(AstroidManager(), "numpy.core.fromnumeric",
                         numpy_core_fromnumeric_transform)
コード例 #3
0
ファイル: brain_numpy_ma.py プロジェクト: michael-k/astroid
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
"""Astroid hooks for numpy ma module"""

from astroid.brain.helpers import register_module_extender
from astroid.builder import parse
from astroid.manager import AstroidManager


def numpy_ma_transform():
    """
    Infer the call of the masked_where function

    :param node: node to infer
    :param context: inference context
    """
    return parse("""
    import numpy.ma
    def masked_where(condition, a, copy=True):
        return numpy.ma.masked_array(a, mask=[])
    """)


register_module_extender(AstroidManager(), "numpy.ma", numpy_ma_transform)
コード例 #4
0
    int_ = int32
    intc = int32
    intp = int32
    long = int32
    longcomplex = complex192
    longdouble = float96
    longfloat = float96
    longlong = int64
    object0 = object_
    object_ = object_
    short = int16
    single = float32
    singlecomplex = complex64
    str0 = str_
    string_ = bytes_
    ubyte = uint8
    uint = uint32
    uint0 = uint32
    uintc = uint32
    uintp = uint32
    ulonglong = uint64
    unicode = str_
    unicode_ = str_
    ushort = uint16
    void0 = void
    """)


register_module_extender(AstroidManager(), "numpy.core.numerictypes",
                         numpy_core_numerictypes_transform)
コード例 #5
0
ファイル: brain_re.py プロジェクト: hippo91/astroid
    DOTALL = sre_compile.SRE_FLAG_DOTALL
    VERBOSE = sre_compile.SRE_FLAG_VERBOSE
    A = ASCII
    I = IGNORECASE
    L = LOCALE
    U = UNICODE
    M = MULTILINE
    S = DOTALL
    X = VERBOSE
    TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE
    T = TEMPLATE
    DEBUG = sre_compile.SRE_FLAG_DEBUG
    """)


register_module_extender(AstroidManager(), "re", _re_transform)

CLASS_GETITEM_TEMPLATE = """
@classmethod
def __class_getitem__(cls, item):
    return cls
"""


def _looks_like_pattern_or_match(node: nodes.Call) -> bool:
    """Check for re.Pattern or re.Match call in stdlib.

    Match these patterns from stdlib/re.py
    ```py
    Pattern = type(...)
    Match = type(...)
コード例 #6
0
"""Astroid hooks for unittest module"""
from astroid.brain.helpers import register_module_extender
from astroid.builder import parse
from astroid.const import PY38_PLUS
from astroid.manager import AstroidManager


def IsolatedAsyncioTestCaseImport():
    """
    In the unittest package, the IsolatedAsyncioTestCase class is imported lazily, i.e only
    when the __getattr__ method of the unittest module is called with 'IsolatedAsyncioTestCase' as
    argument. Thus the IsolatedAsyncioTestCase is not imported statically (during import time).
    This function mocks a classical static import of the IsolatedAsyncioTestCase.

    (see https://github.com/PyCQA/pylint/issues/4060)
    """
    return parse("""
    from .async_case import IsolatedAsyncioTestCase
    """)


if PY38_PLUS:
    register_module_extender(AstroidManager(), "unittest",
                             IsolatedAsyncioTestCaseImport)
コード例 #7
0
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
"""
Astroid hooks for numpy.core.einsumfunc module:
https://github.com/numpy/numpy/blob/main/numpy/core/einsumfunc.py
"""

from astroid import nodes
from astroid.brain.helpers import register_module_extender
from astroid.builder import parse
from astroid.manager import AstroidManager


def numpy_core_einsumfunc_transform() -> nodes.Module:
    return parse("""
    def einsum(*operands, out=None, optimize=False, **kwargs):
        return numpy.ndarray([0, 0])
    """)


register_module_extender(AstroidManager(), "numpy.core.einsumfunc",
                         numpy_core_einsumfunc_transform)
コード例 #8
0
        def replace(method_or_response=None, url=None, body="", *args, **kwargs):
            return

        def add_callback(
            method, url, callback, match_querystring=False, content_type="text/plain"
        ):
            return

        calls = []

        def __enter__():
            return

        def __exit__(type, value, traceback):
            success = type is None
            return success

        def activate(func):
            return func

        def start():
            return

        def stop(allow_assert=True):
            return
        """)


register_module_extender(AstroidManager(), "responses", responses_funcs)
コード例 #9
0
from astroid.manager import AstroidManager
from astroid.node_classes import Attribute, Name


def numpy_core_multiarray_transform():
    return parse("""
    # different functions defined in multiarray.py
    def inner(a, b):
        return numpy.ndarray([0, 0])

    def vdot(a, b):
        return numpy.ndarray([0, 0])
        """)


register_module_extender(AstroidManager(), "numpy.core.multiarray",
                         numpy_core_multiarray_transform)

METHODS_TO_BE_INFERRED = {
    "array":
    """def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
            return numpy.ndarray([0, 0])""",
    "dot":
    """def dot(a, b, out=None):
            return numpy.ndarray([0, 0])""",
    "empty_like":
    """def empty_like(a, dtype=None, order='K', subok=True):
            return numpy.ndarray((0, 0))""",
    "concatenate":
    """def concatenate(arrays, axis=None, out=None):
            return numpy.ndarray((0, 0))""",
    "where":
コード例 #10
0
    def hanning(M, sym=True):
        return numpy.ndarray([0])

    def impulse2(system, X0=None, T=None, N=None, **kwargs):
        return numpy.ndarray([0]), numpy.ndarray([0])

    def kaiser(M, beta, sym=True):
        return numpy.ndarray([0])

    def nuttall(M, sym=True):
        return numpy.ndarray([0])

    def parzen(M, sym=True):
        return numpy.ndarray([0])

    def slepian(M, width, sym=True):
        return numpy.ndarray([0])

    def step2(system, X0=None, T=None, N=None, **kwargs):
        return numpy.ndarray([0]), numpy.ndarray([0])

    def triang(M, sym=True):
        return numpy.ndarray([0])

    def tukey(M, alpha=0.5, sym=True):
        return numpy.ndarray([0])
        """)


register_module_extender(AstroidManager(), "scipy.signal", scipy_signal)
コード例 #11
0
def _session_transform():
    return parse("""
    from sqlalchemy.orm.session import Session

    class sessionmaker:
        def __init__(
            self,
            bind=None,
            class_=Session,
            autoflush=True,
            autocommit=False,
            expire_on_commit=True,
            info=None,
            **kw
        ):
            return

        def __call__(self, **local_kw):
            return Session()

        def configure(self, **new_kw):
            return

        return Session()
    """)


register_module_extender(AstroidManager(), "sqlalchemy.orm.session",
                         _session_transform)
コード例 #12
0
ファイル: brain_pytest.py プロジェクト: michael-k/astroid
        freeze_includes = _pytest.genscript.freeze_includes
    except ImportError:
        pass

try:
    import _pytest.debugging
    set_trace = _pytest.debugging.pytestPDB().set_trace
except ImportError:
    try:
        import _pytest.pdb
        set_trace = _pytest.pdb.pytestPDB().set_trace
    except ImportError:
        pass

try:
    import _pytest.fixtures
    fixture = _pytest.fixtures.fixture
    yield_fixture = _pytest.fixtures.yield_fixture
except ImportError:
    try:
        import _pytest.python
        fixture = _pytest.python.fixture
        yield_fixture = _pytest.python.yield_fixture
    except ImportError:
        pass
""")


register_module_extender(AstroidManager(), "pytest", pytest_transform)
register_module_extender(AstroidManager(), "py.test", pytest_transform)
コード例 #13
0
ファイル: brain_hashlib.py プロジェクト: michael-k/astroid
        ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"], signature)
    blake2b_signature = f"data=b'', *, digest_size=64, key=b'', salt=b'', \
            person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
            node_depth=0, inner_size=0, last_node=False{maybe_usedforsecurity}"

    blake2s_signature = f"data=b'', *, digest_size=32, key=b'', salt=b'', \
            person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, \
            node_depth=0, inner_size=0, last_node=False{maybe_usedforsecurity}"

    new_algorithms = dict.fromkeys(
        [
            "sha3_224", "sha3_256", "sha3_384", "sha3_512", "shake_128",
            "shake_256"
        ],
        signature,
    )
    algorithms_with_signature.update(new_algorithms)
    algorithms_with_signature.update({
        "blake2b": blake2b_signature,
        "blake2s": blake2s_signature
    })
    classes = "".join(template % {
        "name": hashfunc,
        "digest": 'b""',
        "signature": signature
    } for hashfunc, signature in algorithms_with_signature.items())
    return parse(classes)


register_module_extender(AstroidManager(), "hashlib", _hashlib_transform)
コード例 #14
0
    def poisson(lam=1.0, size=None): return uninferable
    def power(a, size=None): return uninferable
    def rand(*args): return uninferable
    def randint(low, high=None, size=None, dtype='l'):
        import numpy
        return numpy.ndarray((1,1))
    def randn(*args): return uninferable
    def random(size=None): return uninferable
    def random_integers(low, high=None, size=None): return uninferable
    def random_sample(size=None): return uninferable
    def rayleigh(scale=1.0, size=None): return uninferable
    def seed(seed=None): return uninferable
    def set_state(state): return uninferable
    def shuffle(x): return uninferable
    def standard_cauchy(size=None): return uninferable
    def standard_exponential(size=None): return uninferable
    def standard_gamma(shape, size=None): return uninferable
    def standard_normal(size=None): return uninferable
    def standard_t(df, size=None): return uninferable
    def triangular(left, mode, right, size=None): return uninferable
    def uniform(low=0.0, high=1.0, size=None): return uninferable
    def vonmises(mu, kappa, size=None): return uninferable
    def wald(mean, scale, size=None): return uninferable
    def weibull(a, size=None): return uninferable
    def zipf(a, size=None): return uninferable
    """)


register_module_extender(AstroidManager(), "numpy.random.mtrand",
                         numpy_random_mtrand_transform)
コード例 #15
0
            yield "assert_equals", astroid.BoundMethod(method, case)


def _nose_tools_transform(node):
    for method_name, method in _nose_tools_functions():
        node.locals[method_name] = [method]


def _nose_tools_trivial_transform():
    """Custom transform for the nose.tools module."""
    stub = _BUILDER.string_build("""__all__ = []""")
    all_entries = ["ok_", "eq_"]

    for pep8_name, method in _nose_tools_functions():
        all_entries.append(pep8_name)
        stub[pep8_name] = method

    # Update the __all__ variable, since nose.tools
    # does this manually with .append.
    all_assign = stub["__all__"].parent
    all_object = astroid.List(all_entries)
    all_object.parent = all_assign
    all_assign.value = all_object
    return stub


register_module_extender(AstroidManager(), "nose.tools.trivial",
                         _nose_tools_trivial_transform)
AstroidManager().register_transform(astroid.Module, _nose_tools_transform,
                                    lambda n: n.name == "nose.tools")
コード例 #16
0
            return self.returncode
        def send_signal(self, signal):
            pass
        def terminate(self):
            pass
        def kill(self):
            pass
        %(ctx_manager)s
       """ % {
            "check_output_signature": check_output_signature,
            "communicate": communicate,
            "communicate_signature": communicate_signature,
            "wait_signature": wait_signature,
            "ctx_manager": ctx_manager,
            "py3_args": py3_args,
        })
    if PY39_PLUS:
        code += """
    @classmethod
    def __class_getitem__(cls, item):
        pass
        """

    init_lines = textwrap.dedent(init).splitlines()
    indented_init = "\n".join(" " * 4 + line for line in init_lines)
    code += indented_init
    return parse(code)


register_module_extender(AstroidManager(), "subprocess", _subprocess_transform)
コード例 #17
0
    def reload(self):
        return None
    def response(self):
        return None
    def select_form(self, name=None, predicate=None, nr=None, **attrs):
        return None
    def set_cookie(self, cookie_string):
        return None
    def set_handle_referer(self, handle):
        return None
    def set_header(self, header, value=None):
        return None
    def set_html(self, html, url="http://example.com/"):
        return None
    def set_response(self, response):
        return None
    def set_simple_cookie(self, name, value, domain, path='/'):
        return None
    def submit(self, *args, **kwds):
        return None
    def title(self):
        return None
    def viewing_html(self):
        return None
    def visit_response(self, response, request=None):
        return None
""")


register_module_extender(AstroidManager(), "mechanize", mechanize_transform)
コード例 #18
0
                      ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE,
                      ALERT_DESCRIPTION_CLOSE_NOTIFY, ALERT_DESCRIPTION_DECODE_ERROR,
                      ALERT_DESCRIPTION_DECOMPRESSION_FAILURE,
                      ALERT_DESCRIPTION_DECRYPT_ERROR,
                      ALERT_DESCRIPTION_HANDSHAKE_FAILURE,
                      ALERT_DESCRIPTION_ILLEGAL_PARAMETER,
                      ALERT_DESCRIPTION_INSUFFICIENT_SECURITY,
                      ALERT_DESCRIPTION_INTERNAL_ERROR,
                      ALERT_DESCRIPTION_NO_RENEGOTIATION,
                      ALERT_DESCRIPTION_PROTOCOL_VERSION,
                      ALERT_DESCRIPTION_RECORD_OVERFLOW,
                      ALERT_DESCRIPTION_UNEXPECTED_MESSAGE,
                      ALERT_DESCRIPTION_UNKNOWN_CA,
                      ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY,
                      ALERT_DESCRIPTION_UNRECOGNIZED_NAME,
                      ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE,
                      ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION,
                      ALERT_DESCRIPTION_USER_CANCELLED)
    from _ssl import (SSL_ERROR_EOF, SSL_ERROR_INVALID_ERROR_CODE, SSL_ERROR_SSL,
                      SSL_ERROR_SYSCALL, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ,
                      SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_ZERO_RETURN)
    from _ssl import VERIFY_CRL_CHECK_CHAIN, VERIFY_CRL_CHECK_LEAF, VERIFY_DEFAULT, VERIFY_X509_STRICT
    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
    from _ssl import PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, PROTOCOL_TLS_SERVER
    """)


register_module_extender(AstroidManager(), "ssl", ssl_transform)
コード例 #19
0
    except (AttributeError, KeyError, IndexError):
        return False
    return func == SIX_WITH_METACLASS


def transform_six_with_metaclass(node):
    """Check if the given class node is defined with *six.with_metaclass*

    If so, inject its argument as the metaclass of the underlying class.
    """
    call = node.bases[0]
    node._metaclass = call.args[0]
    return node


register_module_extender(AstroidManager(), "six", six_moves_transform)
register_module_extender(AstroidManager(),
                         "requests.packages.urllib3.packages.six",
                         six_moves_transform)
AstroidManager().register_failed_import_hook(_six_fail_hook)
AstroidManager().register_transform(
    nodes.ClassDef,
    transform_six_add_metaclass,
    _looks_like_decorated_with_six_add_metaclass,
)
AstroidManager().register_transform(
    nodes.ClassDef,
    transform_six_with_metaclass,
    _looks_like_nested_from_six_with_metaclass,
)
コード例 #20
0
    hypot = FakeUfuncTwoArgs()
    heaviside = FakeUfuncTwoArgs()
    lcm = FakeUfuncTwoArgs()
    ldexp = FakeUfuncTwoArgs()
    left_shift = FakeUfuncTwoArgs()
    less = FakeUfuncTwoArgs()
    logaddexp = FakeUfuncTwoArgs()
    logaddexp2 = FakeUfuncTwoArgs()
    logical_and = FakeUfuncTwoArgs()
    logical_or = FakeUfuncTwoArgs()
    logical_xor = FakeUfuncTwoArgs()
    maximum = FakeUfuncTwoArgs()
    minimum = FakeUfuncTwoArgs()
    multiply = FakeUfuncTwoArgs()
    nextafter = FakeUfuncTwoArgs()
    not_equal = FakeUfuncTwoArgs()
    power = FakeUfuncTwoArgs()
    remainder = FakeUfuncTwoArgs()
    right_shift = FakeUfuncTwoArgs()
    subtract = FakeUfuncTwoArgs()
    true_divide = FakeUfuncTwoArgs()
    """.format(
            opt_args=ufunc_optional_keyword_arguments
        )
    )


register_module_extender(
    AstroidManager(), "numpy.core.umath", numpy_core_umath_transform
)
コード例 #21
0
ファイル: brain_signal.py プロジェクト: michael-k/astroid
        SIGRTMAX  = enum.auto()
        SIGRTMIN  = enum.auto()
        """
    return signals_enum


def _handlers_enum():
    """Generates the source code for the Handlers int enum."""
    return """
    import enum
    class Handlers(enum.IntEnum):
        SIG_DFL = enum.auto()
        SIG_IGN = eunm.auto()
    """


def _sigmasks_enum():
    """Generates the source code for the Sigmasks int enum."""
    if sys.platform != "win32":
        return """
    import enum
    class Sigmasks(enum.IntEnum):
        SIG_BLOCK   = enum.auto()
        SIG_UNBLOCK = enum.auto()
        SIG_SETMASK = enum.auto()
        """
    return ""


register_module_extender(AstroidManager(), "signal", _signals_enums_transform)
コード例 #22
0
# Copyright (c) 2021 Marc Mueller <*****@*****.**>

# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE

from astroid.brain.helpers import register_module_extender
from astroid.builder import parse
from astroid.manager import AstroidManager


def _thread_transform():
    return parse("""
    class lock(object):
        def acquire(self, blocking=True, timeout=-1):
            return False
        def release(self):
            pass
        def __enter__(self):
            return True
        def __exit__(self, *args):
            pass
        def locked(self):
            return False

    def Lock():
        return lock()
    """)


register_module_extender(AstroidManager(), "threading", _thread_transform)
コード例 #23
0
    return base_deque_class


def _ordered_dict_mock():
    base_ordered_dict_class = """
    class OrderedDict(dict):
        def __reversed__(self): return self[::-1]
        def move_to_end(self, key, last=False): pass"""
    if PY39_PLUS:
        base_ordered_dict_class += """
        @classmethod
        def __class_getitem__(cls, item): return cls"""
    return base_ordered_dict_class


register_module_extender(AstroidManager(), "collections",
                         _collections_transform)


def _looks_like_subscriptable(node: ClassDef) -> bool:
    """
    Returns True if the node corresponds to a ClassDef of the Collections.abc module that
    supports subscripting

    :param node: ClassDef node
    """
    if node.qname().startswith("_collections") or node.qname().startswith(
            "collections"):
        try:
            node.getattr("__class_getitem__")
            return True
        except AttributeInferenceError:
コード例 #24
0
ファイル: brain_dateutil.py プロジェクト: michael-k/astroid
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
"""Astroid hooks for dateutil"""

import textwrap

from astroid.brain.helpers import register_module_extender
from astroid.builder import AstroidBuilder
from astroid.manager import AstroidManager


def dateutil_transform():
    return AstroidBuilder(AstroidManager()).string_build(
        textwrap.dedent("""
    import datetime
    def parse(timestr, parserinfo=None, **kwargs):
        return datetime.datetime()
    """))


register_module_extender(AstroidManager(), "dateutil.parser",
                         dateutil_transform)
コード例 #25
0
def resource_listdir(package_or_requirement, resource_name):
    return get_provider(package_or_requirement).resource_listdir(
        resource_name)

def extraction_error():
    pass

def get_cache_path(archive_name, names=()):
    extract_path = self.extraction_path or get_default_cache()
    target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
    return target_path

def postprocess(tempname, filename):
    pass

def set_extraction_path(path):
    pass

def cleanup_resources(force=False):
    pass

def get_distribution(dist):
    return Distribution(dist)

_namespace_packages = {}
""")


register_module_extender(AstroidManager(), "pkg_resources",
                         pkg_resources_transform)
コード例 #26
0
    def Array(typecode, sequence, lock=True):
        return array.array(typecode, sequence)

    class SyncManager(object):
        Queue = JoinableQueue = queue.Queue
        Event = threading.Event
        RLock = threading.RLock
        BoundedSemaphore = threading.BoundedSemaphore
        Condition = threading.Condition
        Barrier = threading.Barrier
        Pool = pool.Pool
        list = list
        dict = dict
        Value = Value
        Array = Array
        Namespace = Namespace
        __enter__ = lambda self: self
        __exit__ = lambda *args: args

        def start(self, initializer=None, initargs=None):
            pass
        def shutdown(self):
            pass
    """)


register_module_extender(AstroidManager(), "multiprocessing.managers",
                         _multiprocessing_managers_transform)
register_module_extender(AstroidManager(), "multiprocessing",
                         _multiprocessing_transform)
コード例 #27
0
        ("c_ushort", "int", "H"),
        ("c_wchar", "str", "u"),
    )

    src = [
        """
from _ctypes import _SimpleCData

class c_bool(_SimpleCData):
    def __init__(self, value):
        self.value = True
        self._type_ = '?'
    """
    ]

    for c_type, builtin_type, type_code in c_class_to_type:
        src.append(f"""
class {c_type}(_SimpleCData):
    def __init__(self, value):
        self.value = {builtin_type}(value)
        self._type_ = '{type_code}'
        """)

    return parse("\n".join(src))


if not hasattr(sys, "pypy_version_info"):
    # No need of this module in pypy where everything is written in python
    register_module_extender(AstroidManager(), "ctypes",
                             enrich_ctypes_redefined_types)
コード例 #28
0
ファイル: brain_curses.py プロジェクト: michael-k/astroid
    ACS_RTEE = 1
    ACS_S1 = 1
    ACS_S3 = 1
    ACS_S7 = 1
    ACS_S9 = 1
    ACS_SBBS = 1
    ACS_SBSB = 1
    ACS_SBSS = 1
    ACS_SSBB = 1
    ACS_SSBS = 1
    ACS_SSSB = 1
    ACS_SSSS = 1
    ACS_STERLING = 1
    ACS_TTEE = 1
    ACS_UARROW = 1
    ACS_ULCORNER = 1
    ACS_URCORNER = 1
    ACS_VLINE = 1
    COLOR_BLACK = 1
    COLOR_BLUE = 1
    COLOR_CYAN = 1
    COLOR_GREEN = 1
    COLOR_MAGENTA = 1
    COLOR_RED = 1
    COLOR_WHITE = 1
    COLOR_YELLOW = 1
        """)


register_module_extender(AstroidManager(), "curses", _curses_transform)
コード例 #29
0
    PRECONDITION_FAILED = HTTPStatus.PRECONDITION_FAILED
    REQUEST_ENTITY_TOO_LARGE = HTTPStatus.REQUEST_ENTITY_TOO_LARGE
    REQUEST_URI_TOO_LONG = HTTPStatus.REQUEST_URI_TOO_LONG
    UNSUPPORTED_MEDIA_TYPE = HTTPStatus.UNSUPPORTED_MEDIA_TYPE
    REQUESTED_RANGE_NOT_SATISFIABLE = HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE
    EXPECTATION_FAILED = HTTPStatus.EXPECTATION_FAILED
    UNPROCESSABLE_ENTITY = HTTPStatus.UNPROCESSABLE_ENTITY
    LOCKED = HTTPStatus.LOCKED
    FAILED_DEPENDENCY = HTTPStatus.FAILED_DEPENDENCY
    UPGRADE_REQUIRED = HTTPStatus.UPGRADE_REQUIRED
    PRECONDITION_REQUIRED = HTTPStatus.PRECONDITION_REQUIRED
    TOO_MANY_REQUESTS = HTTPStatus.TOO_MANY_REQUESTS
    REQUEST_HEADER_FIELDS_TOO_LARGE = HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE
    INTERNAL_SERVER_ERROR = HTTPStatus.INTERNAL_SERVER_ERROR
    NOT_IMPLEMENTED = HTTPStatus.NOT_IMPLEMENTED
    BAD_GATEWAY = HTTPStatus.BAD_GATEWAY
    SERVICE_UNAVAILABLE = HTTPStatus.SERVICE_UNAVAILABLE
    GATEWAY_TIMEOUT = HTTPStatus.GATEWAY_TIMEOUT
    HTTP_VERSION_NOT_SUPPORTED = HTTPStatus.HTTP_VERSION_NOT_SUPPORTED
    VARIANT_ALSO_NEGOTIATES = HTTPStatus.VARIANT_ALSO_NEGOTIATES
    INSUFFICIENT_STORAGE = HTTPStatus.INSUFFICIENT_STORAGE
    LOOP_DETECTED = HTTPStatus.LOOP_DETECTED
    NOT_EXTENDED = HTTPStatus.NOT_EXTENDED
    NETWORK_AUTHENTICATION_REQUIRED = HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED
    """))


register_module_extender(AstroidManager(), "http", _http_transform)
register_module_extender(AstroidManager(), "http.client",
                         _http_client_transform)