Python inspect.html() Examples

The following are 30 code examples of inspect.html(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: decorators.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def caller_name(depth=1):
    """Get a name of a caller in the format module.class.method

       `skip` specifies how many levels of stack to skip while getting caller
       name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.

       An empty string is returned if skipped levels exceed stack height
    """
    stack = inspect.stack()
    start = 0 + depth
    if len(stack) < start + 1:
        return ''
    parentframe = stack[start][0]
    path = get_frame_path(parentframe)

    ## Avoid circular refs and frame leaks
    #  https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
    del parentframe, stack

    return path 
Example #2
Source File: langhelpers.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _inspect_func_args(fn):
    try:
        co_varkeywords = inspect.CO_VARKEYWORDS
    except AttributeError:
        # https://docs.python.org/3/library/inspect.html
        # The flags are specific to CPython, and may not be defined in other
        # Python implementations. Furthermore, the flags are an implementation
        # detail, and can be removed or deprecated in future Python releases.
        spec = compat.inspect_getfullargspec(fn)
        return spec[0], bool(spec[2])
    else:
        # use fn.__code__ plus flags to reduce method call overhead
        co = fn.__code__
        nargs = co.co_argcount
        return (
            list(co.co_varnames[:nargs]),
            bool(co.co_flags & co_varkeywords),
        ) 
Example #3
Source File: code_pointer.py    From dagster with Apache License 2.0 6 votes vote down vote up
def get_python_file_from_previous_stack_frame():
    '''inspect.stack() lets us introspect the call stack; inspect.stack()[1] is the previous
    stack frame.

    In Python < 3.5, this is just a tuple, of which the python file of the previous frame is the 1st
    element.

    In Python 3.5+, this is a FrameInfo namedtuple instance; the python file of the previous frame
    remains the 1st element.
    '''

    # Since this is now a function in this file, we need to go back two hops to find the
    # callsite file.
    previous_stack_frame = inspect.stack(0)[2]

    # See: https://docs.python.org/3/library/inspect.html
    if sys.version_info.major == 3 and sys.version_info.minor >= 5:
        check.inst(previous_stack_frame, inspect.FrameInfo)
    else:
        check.inst(previous_stack_frame, tuple)

    python_file = previous_stack_frame[1]
    return os.path.abspath(python_file) 
Example #4
Source File: common.py    From surreal with MIT License 6 votes vote down vote up
def add(self, *args, **kwargs):
        default = kwargs.get('default')
        dtype = kwargs.get('type')
        if dtype is None:
            if default is None:
                dtype = str
            else:
                dtype = type(default)
        typename = dtype.__name__
        if 'metavar' not in kwargs:
            # metavar: display --foo <float=0.05> in help string
            if 'choices' in kwargs:
                choices = kwargs['choices']
                choices_str = '/'.join(['{}']*len(choices)).format(*choices)
                kwargs['metavar'] = '<{}: {}>'.format(typename, choices_str)
            elif 'nargs' in kwargs:
                # better formatting handled in _SingleMetavarFormatter
                kwargs['metavar'] = '{}'.format(typename)
            elif not kwargs.get('action'):
                # if 'store_true', then no metavar needed
                # list of actions: https://docs.python.org/3/library/argparse.html#action
                default_str = '={}'.format(default) if default else ''
                kwargs['metavar'] = '<{}{}>'.format(typename, default_str)
        self.parser.add_argument(*args, **kwargs) 
Example #5
Source File: custom_test_helpers.py    From pycharm-courses with Apache License 2.0 6 votes vote down vote up
def normalize_call_args(call_args, func=None, signature=None, with_defaults=True):
    if func is None and signature is None:
        raise ValueError("Must supply either func or signature")
    if func is not None and signature is not None:
        raise ValueError("Must supply either func or signature; not both")

    if signature is None:
        signature = inspect.signature(func)

    args, kwargs = call_args
    bound_args = signature.bind(*args, **kwargs)

    # based on code from the Python docs:
    # https://docs.python.org/3/library/inspect.html#inspect.BoundArguments
    if with_defaults:
        for param in signature.parameters.values():
            if (
                    param.name not in bound_args.arguments
                    and param.default is not param.empty
            ):
                bound_args.arguments[param.name] = param.default

    return bound_args.args, bound_args.kwargs 
Example #6
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def mycallersname():
    """Returns the name of the caller of the caller of this function
    (hence the name of the caller of the function in which
    "mycallersname()" textually appears).  Returns None if this cannot
    be determined."""

    # http://docs.python.org/library/inspect.html#the-interpreter-stack
    import inspect

    frame = inspect.currentframe()
    if not frame:
        return None
    frame_,filename_,lineno_,funname,linelist_,listi_ = (
      inspect.getouterframes(frame)[2])
    return funname 
Example #7
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def interleave_planes(ipixels, apixels, ipsize, apsize):
    """
    Interleave (colour) planes, e.g. RGB + A = RGBA.

    Return an array of pixels consisting of the `ipsize` elements of data
    from each pixel in `ipixels` followed by the `apsize` elements of data
    from each pixel in `apixels`.  Conventionally `ipixels` and
    `apixels` are byte arrays so the sizes are bytes, but it actually
    works with any arrays of the same type.  The returned array is the
    same type as the input arrays which should be the same type as each other.
    """

    itotal = len(ipixels)
    atotal = len(apixels)
    newtotal = itotal + atotal
    newpsize = ipsize + apsize
    # Set up the output buffer
    # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
    out = array(ipixels.typecode)
    # It's annoying that there is no cheap way to set the array size :-(
    out.extend(ipixels)
    out.extend(apixels)
    # Interleave in the pixel data
    for i in range(ipsize):
        out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    for i in range(apsize):
        out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    return out 
Example #8
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #9
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #10
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def mycallersname():
    """Returns the name of the caller of the caller of this function
    (hence the name of the caller of the function in which
    "mycallersname()" textually appears).  Returns None if this cannot
    be determined."""

    # http://docs.python.org/library/inspect.html#the-interpreter-stack
    import inspect

    frame = inspect.currentframe()
    if not frame:
        return None
    frame_,filename_,lineno_,funname,linelist_,listi_ = (
      inspect.getouterframes(frame)[2])
    return funname 
Example #11
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def interleave_planes(ipixels, apixels, ipsize, apsize):
    """
    Interleave (colour) planes, e.g. RGB + A = RGBA.

    Return an array of pixels consisting of the `ipsize` elements of data
    from each pixel in `ipixels` followed by the `apsize` elements of data
    from each pixel in `apixels`.  Conventionally `ipixels` and
    `apixels` are byte arrays so the sizes are bytes, but it actually
    works with any arrays of the same type.  The returned array is the
    same type as the input arrays which should be the same type as each other.
    """

    itotal = len(ipixels)
    atotal = len(apixels)
    newtotal = itotal + atotal
    newpsize = ipsize + apsize
    # Set up the output buffer
    # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
    out = array(ipixels.typecode)
    # It's annoying that there is no cheap way to set the array size :-(
    out.extend(ipixels)
    out.extend(apixels)
    # Interleave in the pixel data
    for i in range(ipsize):
        out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    for i in range(apsize):
        out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    return out 
Example #12
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def group(s, n):
    # See
    # http://www.python.org/doc/2.6/library/functions.html#zip
    return zip(*[iter(s)]*n) 
Example #13
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def group(s, n):
    # See
    # http://www.python.org/doc/2.6/library/functions.html#zip
    return zip(*[iter(s)]*n) 
Example #14
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #15
Source File: common.py    From surreal with MIT License 5 votes vote down vote up
def _get_bound_args(func, *args, **kwargs):
    """
    https://docs.python.org/3/library/inspect.html#inspect.BoundArguments
    def f(a, b, c=5, d=6): pass
    get_bound_args(f, 3, 6, d=100) -> {'a':3, 'b':6, 'c':5, 'd':100}

    Returns:
        OrderedDict of bound arguments
    """
    arginfo = inspect.signature(func).bind(*args, **kwargs)
    arginfo.apply_defaults()
    return arginfo.arguments 
Example #16
Source File: urdf.py    From compas with MIT License 5 votes vote down vote up
def get_metadata(type):
    metadata = dict()

    if hasattr(type, 'from_urdf'):
        metadata['from_urdf'] = getattr(type, 'from_urdf')
    else:
        if sys.version_info[0] < 3:
            argspec = inspect.getargspec(type.__init__)  # this is deprecated in python3
        else:
            argspec = inspect.getfullargspec(type.__init__)
        args = {}

        required = len(argspec.args)
        if argspec.defaults:
            required -= len(argspec.defaults)

        for i in range(1, len(argspec.args)):
            data = dict(required=i < required)
            default_index = i - required

            if default_index >= 0:
                default = argspec.defaults[default_index]
                data['default'] = default
                data['sequence'] = hasattr(default, '__iter__')
            else:
                data['sequence'] = False

            args[argspec.args[i]] = data
        if sys.version_info[0] < 3:
            metadata['keywords'] = argspec.keywords is not None
        else:
            # TODO: make sure replacing keyword with kwonlyargs is correct, check at: https://docs.python.org/3/library/inspect.html#inspect.getargspec
            metadata['keywords'] = argspec.kwonlyargs is not None
        metadata['init_args'] = args

    metadata['argument_map'] = getattr(type, 'argument_map', {})

    return metadata 
Example #17
Source File: png.py    From sublime-markdown-popups with MIT License 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #18
Source File: png.py    From sublime-markdown-popups with MIT License 5 votes vote down vote up
def mycallersname():
    """Returns the name of the caller of the caller of this function
    (hence the name of the caller of the function in which
    "mycallersname()" textually appears).  Returns None if this cannot
    be determined."""

    # http://docs.python.org/library/inspect.html#the-interpreter-stack
    import inspect

    frame = inspect.currentframe()
    if not frame:
        return None
    frame_,filename_,lineno_,funname,linelist_,listi_ = (
      inspect.getouterframes(frame)[2])
    return funname 
Example #19
Source File: png.py    From sublime-markdown-popups with MIT License 5 votes vote down vote up
def interleave_planes(ipixels, apixels, ipsize, apsize):
    """
    Interleave (colour) planes, e.g. RGB + A = RGBA.

    Return an array of pixels consisting of the `ipsize` elements of data
    from each pixel in `ipixels` followed by the `apsize` elements of data
    from each pixel in `apixels`.  Conventionally `ipixels` and
    `apixels` are byte arrays so the sizes are bytes, but it actually
    works with any arrays of the same type.  The returned array is the
    same type as the input arrays which should be the same type as each other.
    """

    itotal = len(ipixels)
    atotal = len(apixels)
    newtotal = itotal + atotal
    newpsize = ipsize + apsize
    # Set up the output buffer
    # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
    out = array(ipixels.typecode)
    # It's annoying that there is no cheap way to set the array size :-(
    out.extend(ipixels)
    out.extend(apixels)
    # Interleave in the pixel data
    for i in range(ipsize):
        out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    for i in range(apsize):
        out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    return out 
Example #20
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def mycallersname():
    """Returns the name of the caller of the caller of this function
    (hence the name of the caller of the function in which
    "mycallersname()" textually appears).  Returns None if this cannot
    be determined."""

    # http://docs.python.org/library/inspect.html#the-interpreter-stack
    import inspect

    frame = inspect.currentframe()
    if not frame:
        return None
    frame_,filename_,lineno_,funname,linelist_,listi_ = (
      inspect.getouterframes(frame)[2])
    return funname 
Example #21
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def group(s, n):
    # See
    # http://www.python.org/doc/2.6/library/functions.html#zip
    return zip(*[iter(s)]*n) 
Example #22
Source File: action_tracking.py    From PocoUnit with Apache License 2.0 5 votes vote down vote up
def post_cv_match(self, cv_ret, *args, **kwargs):
        if not cv_ret:
            return

        # 如果当前函数是由loop_find调用的,那就可以找到一个rect,这个rect由airtest.core.cv._cv_match里给出
        # 以下就是从frame stack中一直找到loop_find这一帧,然后找出loop_find的第一个argument,通过argument求出tid
        frame = sys._getframe(0)
        while frame and frame.f_code.co_name != 'loop_find':
            frame = frame.f_back
        if frame:
            # more details about inspect parameter name in runtime,
            # see https://docs.python.org/2/library/inspect.html#inspect.getargvalues
            args, varargs, keywords, locals = inspect.getargvalues(frame)
            if len(args) > 0:
                v_name = args[0]
            elif varargs is not None and len(locals[varargs]) > 0:
                v_name = locals[varargs][0]
            else:
                raise ValueError('loop_find第一个参数不支持使用keyword args')

            # 取到loop_find的第一个argument
            v = locals[v_name]
            tid = id(v)
            rect = cv_ret.get("rectangle")
            if rect:
                # a rect's each vertex in screen as following
                # [0]  [3]
                # [1]  [2]
                t = rect[0][1] * 1.0
                r = rect[3][0] * 1.0
                b = rect[1][1] * 1.0
                l = rect[0][0] * 1.0
                w, h = current_device().getCurrentScreenResolution()
                self.action_recorder.bounding(tid, [t / h, r / w, b / h, l / w]) 
Example #23
Source File: trim_docstring.py    From graphene with MIT License 5 votes vote down vote up
def trim_docstring(docstring):
    # Cleans up whitespaces from an indented docstring
    #
    # See https://www.python.org/dev/peps/pep-0257/
    # and https://docs.python.org/2/library/inspect.html#inspect.cleandoc
    return inspect.cleandoc(docstring) if docstring else None 
Example #24
Source File: png.py    From coastermelt with MIT License 5 votes vote down vote up
def group(s, n):
    # See
    # http://www.python.org/doc/2.6/library/functions.html#zip
    return zip(*[iter(s)]*n) 
Example #25
Source File: png.py    From coastermelt with MIT License 5 votes vote down vote up
def interleave_planes(ipixels, apixels, ipsize, apsize):
    """
    Interleave (colour) planes, e.g. RGB + A = RGBA.

    Return an array of pixels consisting of the `ipsize` elements of data
    from each pixel in `ipixels` followed by the `apsize` elements of data
    from each pixel in `apixels`.  Conventionally `ipixels` and
    `apixels` are byte arrays so the sizes are bytes, but it actually
    works with any arrays of the same type.  The returned array is the
    same type as the input arrays which should be the same type as each other.
    """

    itotal = len(ipixels)
    atotal = len(apixels)
    newtotal = itotal + atotal
    newpsize = ipsize + apsize
    # Set up the output buffer
    # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
    out = array(ipixels.typecode)
    # It's annoying that there is no cheap way to set the array size :-(
    out.extend(ipixels)
    out.extend(apixels)
    # Interleave in the pixel data
    for i in range(ipsize):
        out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    for i in range(apsize):
        out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    return out 
Example #26
Source File: png.py    From coastermelt with MIT License 5 votes vote down vote up
def mycallersname():
    """Returns the name of the caller of the caller of this function
    (hence the name of the caller of the function in which
    "mycallersname()" textually appears).  Returns None if this cannot
    be determined."""

    # http://docs.python.org/library/inspect.html#the-interpreter-stack
    import inspect

    frame = inspect.currentframe()
    if not frame:
        return None
    frame_,filename_,lineno_,funname,linelist_,listi_ = (
      inspect.getouterframes(frame)[2])
    return funname 
Example #27
Source File: png.py    From coastermelt with MIT License 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #28
Source File: png.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def _enhex(s):
    """Convert from binary string (bytes) to hex string (str)."""

    import binascii

    return bytestostr(binascii.hexlify(s))

# Copies of PngSuite test files taken
# from http://www.schaik.com/pngsuite/pngsuite_bas_png.html
# on 2009-02-19 by drj and converted to hex.
# Some of these are not actually in PngSuite (but maybe they should
# be?), they use the same naming scheme, but start with a capital
# letter. 
Example #29
Source File: png.py    From stegoVeritas with GNU General Public License v2.0 5 votes vote down vote up
def group(s, n):
    # See
    # http://www.python.org/doc/2.6/library/functions.html#zip
    return list(zip(*[iter(s)]*n)) 
Example #30
Source File: png.py    From stegoVeritas with GNU General Public License v2.0 5 votes vote down vote up
def interleave_planes(ipixels, apixels, ipsize, apsize):
    """
    Interleave (colour) planes, e.g. RGB + A = RGBA.

    Return an array of pixels consisting of the `ipsize` elements of data
    from each pixel in `ipixels` followed by the `apsize` elements of data
    from each pixel in `apixels`.  Conventionally `ipixels` and
    `apixels` are byte arrays so the sizes are bytes, but it actually
    works with any arrays of the same type.  The returned array is the
    same type as the input arrays which should be the same type as each other.
    """

    itotal = len(ipixels)
    atotal = len(apixels)
    newtotal = itotal + atotal
    newpsize = ipsize + apsize
    # Set up the output buffer
    # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
    out = array(ipixels.typecode)
    # It's annoying that there is no cheap way to set the array size :-(
    out.extend(ipixels)
    out.extend(apixels)
    # Interleave in the pixel data
    for i in range(ipsize):
        out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
    for i in range(apsize):
        out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
    return out