Пример #1
0
def printExceptionDetailsToStdErr():
    """
        No idea if all of this is needed, infact I know it is not. But for now why not.
        Taken straight from the python manual on Exceptions.
        """
    import sys, traceback

    exc_type, exc_value, exc_traceback = sys.exc_info()
    print2err("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print2err("*** print_exception:")
    traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
    print2err("*** print_exc:")
    traceback.print_exc()
    print2err("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print2err(str(formatted_lines[0]))
    print2err((formatted_lines[-1]))
    print2err("*** format_exception:")
    print2err(repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    print2err("*** extract_tb:")
    print2err(repr(traceback.extract_tb(exc_traceback)))
    print2err("*** format_tb:")
    print2err(repr(traceback.format_tb(exc_traceback)))
    print2err("*** tb_lineno:" + str(exc_traceback.tb_lineno))
Пример #2
0
def printExceptionDetailsToStdErr():
    """
        No idea if all of this is needed, infact I know it is not. But for now why not.
        Taken straight from the python manual on Exceptions.
        """
    import sys, traceback
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print2err("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print2err("*** print_exception:")
    traceback.print_exception(exc_type,
                              exc_value,
                              exc_traceback,
                              limit=2,
                              file=sys.stdout)
    print2err("*** print_exc:")
    traceback.print_exc()
    print2err("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print2err(str(formatted_lines[0]))
    print2err((formatted_lines[-1]))
    print2err("*** format_exception:")
    print2err(
        repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    print2err("*** extract_tb:")
    print2err(repr(traceback.extract_tb(exc_traceback)))
    print2err("*** format_tb:")
    print2err(repr(traceback.format_tb(exc_traceback)))
    print2err("*** tb_lineno:" + str(exc_traceback.tb_lineno))
Пример #3
0
 def repr_str(self, x, level):
     s = __builtin__.repr(x[:self.maxstring])
     if len(s) > self.maxstring:
         i = max(0, (self.maxstring - 3) // 2)
         j = max(0, self.maxstring - 3 - i)
         s = __builtin__.repr(x[:i] + x[len(x) - j:])
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #4
0
 def repr_str(self, x, level):
     s = builtins.repr(x[:self.maxstring])
     if len(s) > self.maxstring:
         i = max(0, (self.maxstring-3)//2)
         j = max(0, self.maxstring-3-i)
         s = builtins.repr(x[:i] + x[len(x)-j:])
         s = s[:i] + '...' + s[len(s)-j:]
     return s
Пример #5
0
    def _handle_self(self, given_type, name, value):
# #
        '''
            Checks given argument value against the methods bounded object.

            Examples:

            >>> def test(): pass
            >>> class A(CheckObject):
            ...     def __init__(self):
            ...         builtins.getattr(
            ...             builtins.super(
            ...                 self.__class__, self
            ...             ), inspect.stack()[0][3]
            ...         )()
            ...         self.__func__ = test
            ...         self._method_type = staticmethod
            >>> a = A()

            >>> a._handle_self(
            ...     str, 'argument_name', 'value'
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            boostnode.extension.native.SignatureError: ...instance so "self"...

            >>> a.object = A()
            >>> a._handle_self(
            ...     str, 'argument_name', 'value'
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            boostnode.extension.native.SignatureError:... but received "'val...

            >>> b = A()
            >>> a.object = b
            >>> a._handle_self(
            ...     A, 'argument_name', b
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Object of "A" with class object "None", object "Object...
        '''
        if self.object is None:
            raise __exception__(
                '"{function_path}()" wasn\'t called from an instance so '
                '"self" for parameter "{name}" couldn\'t be '
                'determined.'.format(
                    function_path=self.get_function_path(), name=name))
        elif value is not self.object:
            raise __exception__(
                '"{function_path}()" expects "{object} (self)" for "{name}" '
                'but "{type}" ({value}) received.'.format(
                    function_path=self.get_function_path(),
                    object=builtins.repr(self.object), name=name,
                    type=given_type.__name__, value=builtins.repr(value)))
        return self
Пример #6
0
    def __repr__(self):
        '''
            Invokes if this object should describe itself by a string.

            Examples:

            >>> repr(Print(buffer=Buffer())) # doctest: +ELLIPSIS
            'Object of "Print" with "Object of "Buffer"..." and default "Ob...'
        '''
        return 'Object of "{class_name}" with "{buffer}" and default '\
               '"{default_buffer}".'.format(
                   class_name=self.__class__.__name__,
                   buffer=builtins.repr(self.buffer),
                   default_buffer=builtins.repr(self.__class__.default_buffer))
Пример #7
0
    def maybe(self, func, *args, **kwargs):
        r""" Call ``func'' with the provided arguments.

        Return ``None'' on ´´AssertionError''.
        """
        if not isinstance(self, ParserSkeleton):
            raise RuntimeError, type(self)  # expecting ParserSkeleton
        if not getattr(self, func.__name__) == func:
            raise ValueError, repr(func)  # must belong to self

        try:
            with self:  # revert state on error
                return func(*args, **kwargs)
        except AssertionError:
            return None
Пример #8
0
 def repr_int(self, x, level):
     s = builtins.repr(x)  # XXX Hope this isn't too slow...
     if len(s) > self.maxlong:
         i = max(0, (self.maxlong-3)//2)
         j = max(0, self.maxlong-3-i)
         s = s[:i] + '...' + s[len(s)-j:]
     return s
Пример #9
0
 def repr_long(self, x, level):
     s = __builtin__.repr(x)  # XXX Hope this isn't too slow...
     if len(s) > self.maxlong:
         i = max(0, (self.maxlong - 3) // 2)
         j = max(0, self.maxlong - 3 - i)
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #10
0
 def other_repr_on_html(self, x, html,level):
     s = escape(__builtin__.repr(x))
     if len(s) > self.maxother:
         i = max(0, (self.maxother-3)//2)
         j = max(0, self.maxother-3-i)
         s = s[:i] + '...' + s[len(s)-j:]
     html.append('<span class="other">{0}</span>'.format(s))
Пример #11
0
 def repr_long(self, x, level):
     s = __builtin__.repr(x)
     if len(s) > self.maxlong:
         i = max(0, (self.maxlong - 3) // 2)
         j = max(0, self.maxlong - 3 - i)
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #12
0
 def repr_long(self, x, level):
     s = __builtin__.repr(x)
     if len(s) > self.maxlong:
         i = max(0, (self.maxlong - 3) // 2)
         j = max(0, self.maxlong - 3 - i)
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #13
0
    def __repr__(self):
        '''
            Describes current function wrapper.

            Examples:

            >>> function_decorator = FunctionDecorator(
            ...     FunctionDecorator.__repr__)
            >>> function_decorator.class_object = FunctionDecorator
            >>> repr(function_decorator) # doctest: +ELLIPSIS
            'Object of "FunctionDecorator" ... "__repr__" ... (NoneType).'

            >>> repr(FunctionDecorator(FunctionDecorator)) # doctest: +ELLIPSIS
            'Object of "FunctionDecorator" with wrapped function "None" and...'
        '''
        function_name = 'None'
        if self.__func__ is not None:
            function_name = self.__func__.__name__
        if self.class_object:
# # python3.5
# #             return (
# #                 'Object of "{class_name}" with class object '
# #                 '"{class_object}", object "{object}", wrapped function '
# #                 '"{wrapped_function}" and return value "{value}" '
# #                 '({type}).'.format(
# #                     class_name=self.__class__.__name__,
# #                     class_object=self.class_object.__name__,
# #                     object=builtins.repr(self.object),
# #                     wrapped_function=function_name,
# #                     value=builtins.str(self.return_value),
# #                     type=builtins.type(self.return_value).__name__))
# #         return (
# #             'Object of "{class_name}" with wrapped function '
# #             '"{wrapped_function}" and return value "{value}" '
# #             '({type}).'.format(
# #                 class_name=self.__class__.__name__,
# #                 wrapped_function=function_name,
# #                 value=builtins.str(self.return_value),
# #                 type=builtins.type(self.return_value).__name__))
            return (
                'Object of "{class_name}" with class object '
                '"{class_object}", object "{object}", wrapped function '
                '"{wrapped_function}" and return value "{value}" '
                '({type}).'.format(
                    class_name=self.__class__.__name__,
                    class_object=self.class_object.__name__,
                    object=builtins.repr(self.object),
                    wrapped_function=function_name,
                    value=convert_to_unicode(self.return_value),
                    type=builtins.type(self.return_value).__name__))
        return (
            'Object of "{class_name}" with wrapped function '
            '"{wrapped_function}" and return value "{value}" '
            '({type}).'.format(
                class_name=self.__class__.__name__,
                wrapped_function=function_name,
                value=convert_to_unicode(self.return_value),
                type=builtins.type(self.return_value).__name__))
Пример #14
0
    def __repr__(cls):
        '''
            Invokes if this object should describe itself by a string.

            Examples:

            >>> repr(Logger()) # doctest: +ELLIPSIS
            'Object of "Logger" with logger "...

            >>> logger1 = Logger.get()
            >>> repr(Logger()) # doctest: +ELLIPSIS
            'Object of "Logger" with logger "...

            >>> logger1 = Logger.get()
            >>> logger2 = Logger.get('hans')
            >>> repr(Logger()) # doctest: +ELLIPSIS
            'Object of "Logger" with logger "... and ...
        '''
        handler_string = formatter_string = ''
        for index, logger in builtins.enumerate(cls.instances):
            start = ', "'
            end = '"'
            if index + 1 == builtins.len(cls.instances):
                start = ' and "'
                end = ''
            if index == 0:
                start = ''
            handler_string += start + builtins.repr(logger.handlers[0]) + end
            formatter_string += start + builtins.repr(
                logger.handlers[0].formatter
            ) + end
# # python3.5
# #         return (
# #             'Object of "{class_name}" with logger "{handler}", formatter '
# #             '"{formatter}" and buffer "{buffer}".'.format(
# #                 class_name=cls.__name__, handler=handler_string,
# #                 formatter=formatter_string,
# #                 buffer=builtins.str(cls.buffer)))
        return (
            'Object of "{class_name}" with logger "{handler}", formatter '
            '"{formatter}" and buffer "{buffer}".'.format(
                class_name=cls.__name__, handler=handler_string,
                formatter=formatter_string,
                buffer=convert_to_unicode(cls.buffer)))
Пример #15
0
    def repr_instance(self, x, level):
        try:
            s = __builtin__.repr(x)
        except Exception:
            return '<%s instance at %x>' % (x.__class__.__name__, id(x))

        if len(s) > self.maxstring:
            i = max(0, (self.maxstring - 3) // 2)
            j = max(0, self.maxstring - 3 - i)
            s = s[:i] + '...' + s[len(s) - j:]
        return s
Пример #16
0
    def repr_instance(self, x, level):
        try:
            s = __builtin__.repr(x)
        except Exception:
            return '<%s instance at %x>' % (x.__class__.__name__, id(x))

        if len(s) > self.maxstring:
            i = max(0, (self.maxstring - 3) // 2)
            j = max(0, self.maxstring - 3 - i)
            s = s[:i] + '...' + s[len(s) - j:]
        return s
Пример #17
0
 def __repr__(self):
     '''Represents the given function call properties.'''
     return (
         'Object of "{class_name}" with class object "{class_object}", '
         'object "{object}", function "{function}", arguments "{arguments}"'
         ' and keywords "{keywords}".'.format(
             class_name=self.__class__.__name__,
             class_object=self.class_object.__name__,
             object=builtins.repr(self.object),
             function=self.__func__.__name__,
             arguments='", "'.join(self.arguments),
             keywords=builtins.str(self.keywords)))
Пример #18
0
 def repr_instance(self, x, level):
     try:
         s = __builtin__.repr(x)
         # Bugs in x.__repr__() can cause arbitrary
         # exceptions -- then make up something
     except Exception:
         return '<%s instance at %x>' % (x.__class__.__name__, id(x))
     if len(s) > self.maxstring:
         i = max(0, (self.maxstring - 3) // 2)
         j = max(0, self.maxstring - 3 - i)
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #19
0
 def repr_instance(self, x, level):
     try:
         s = builtins.repr(x)
         # Bugs in x.__repr__() can cause arbitrary
         # exceptions -- then make up something
     except Exception:
         return '<%s instance at %x>' % (x.__class__.__name__, id(x))
     if len(s) > self.maxother:
         i = max(0, (self.maxother-3)//2)
         j = max(0, self.maxother-3-i)
         s = s[:i] + '...' + s[len(s)-j:]
     return s
Пример #20
0
 def printExceptionDetails():
     """
     prints out stack stace info for an excption in multiple ways.
     No idea if all of this is needed, infact I know it is not. But for now why not.
     Taken straight from the python manual on Exceptions.
     """
     import sys, traceback
     exc_type, exc_value, exc_traceback = sys.exc_info()
     print "*** print_tb:"
     traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
     print "*** print_exception:"
     traceback.print_exception(exc_type,
                               exc_value,
                               exc_traceback,
                               limit=2,
                               file=sys.stdout)
     print "*** print_exc:"
     traceback.print_exc()
     print "*** format_exc, first and last line:"
     formatted_lines = traceback.format_exc().splitlines()
     print formatted_lines[0]
     print formatted_lines[-1]
     print "*** format_exception:"
     print repr(
         traceback.format_exception(exc_type, exc_value, exc_traceback))
     print "*** extract_tb:"
     print repr(traceback.extract_tb(exc_traceback))
     print "*** format_tb:"
     print repr(traceback.format_tb(exc_traceback))
     print "*** tb_lineno:", exc_traceback.tb_lineno
Пример #21
0
 def printExceptionDetails():
     """
     prints out stack stace info for an excption in multiple ways.
     No idea if all of this is needed, infact I know it is not. But for now why not.
     Taken straight from the python manual on Exceptions.
     """
     import sys, traceback
     exc_type, exc_value, exc_traceback = sys.exc_info()
     print "*** print_tb:"
     traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
     print "*** print_exception:"
     traceback.print_exception(exc_type, exc_value, exc_traceback,
                               limit=2, file=sys.stdout)
     print "*** print_exc:"
     traceback.print_exc()
     print "*** format_exc, first and last line:"
     formatted_lines = traceback.format_exc().splitlines()
     print formatted_lines[0]
     print formatted_lines[-1]
     print "*** format_exception:"
     print repr(traceback.format_exception(exc_type, exc_value,
                                           exc_traceback))
     print "*** extract_tb:"
     print repr(traceback.extract_tb(exc_traceback))
     print "*** format_tb:"
     print repr(traceback.format_tb(exc_traceback))
     print "*** tb_lineno:", exc_traceback.tb_lineno
 def repr1(self, x, level):
     typename = type(x).__name__
     if ' ' in typename:
         parts = typename.split()
         typename = ('_').join(parts)
     if hasattr(self, 'repr_' + typename):
         return getattr(self, 'repr_' + typename)(x, level)
     s = __builtin__.repr(x)
     if len(s) > self.maxother:
         i = max(0, (self.maxother - 3) // 2)
         j = max(0, self.maxother - 3 - i)
         s = s[:i] + '...' + s[len(s) - j:]
     return s
Пример #23
0
 def repr1(self, x, level):
     typename = type(x).__name__
     if ' ' in typename:
         parts = typename.split()
         typename = '_'.join(parts)
     if hasattr(self, 'repr_' + typename):
         return getattr(self, 'repr_' + typename)(x, level)
     else:
         s = __builtin__.repr(x)
         if len(s) > self.maxother:
             i = max(0, (self.maxother - 3) // 2)
             j = max(0, self.maxother - 3 - i)
             s = s[:i] + '...' + s[len(s) - j:]
         return s
Пример #24
0
 def repr_instance(self, x, level):
     try:
         # Try the vanilla repr and make sure that the result is a string
         s = str(__builtin__.repr(x))
     except (KeyboardInterrupt, MemoryError, SystemExit):
         raise
     except Exception, e:
         try:
             exc_name = e.__class__.__name__
         except:
             exc_name = "unknown"
         try:
             exc_info = str(e)
         except:
             exc_info = "unknown"
         return '<[%s("%s") raised in repr()] %s object at 0x%x>' % (exc_name, exc_info, x.__class__.__name__, id(x))
Пример #25
0
    def __repr__(self):
        '''
            Represents the current handled function call.

            Examples:

            >>> class A:
            ...     def a(self): pass
            >>> return_aspect = ReturnAspect()
            >>> return_aspect.class_object = A
            >>> return_aspect.object = A()
            >>> return_aspect.__func__ = A().a
            >>> return_aspect.arguments = ()
            >>> return_aspect.keywords = {}

            >>> repr(return_aspect) # doctest: +ELLIPSIS
            'Object of "ReturnAspect" with class object "A", object "...'
        '''
# # python3.5
# #         return (
# #             'Object of "{class_name}" with class object "{class_object}", '
# #             'object "{object}", function "{function}", arguments '
# #             '"{arguments}", keywords "{keywords}" and return value '
# #             '"{value}" ({type}).'.format(
# #                 class_name=self.__class__.__name__,
# #                 class_object=self.class_object.__name__,
# #                 object=builtins.repr(self.object),
# #                 function=self.__func__.__name__,
# #                 arguments='", "'.join(self.arguments),
# #                 keywords=builtins.str(self.keywords),
# #                 value=builtins.str(self.return_value),
# #                 type=builtins.str(builtins.type(self.return_value))))
        return (
            'Object of "{class_name}" with class object "{class_object}", '
            'object "{object}", function "{function}", arguments '
            '"{arguments}", keywords "{keywords}" and return value '
            '"{value}" ({type}).'.format(
                class_name=self.__class__.__name__,
                class_object=self.class_object.__name__,
                object=builtins.repr(self.object),
                function=self.__func__.__name__,
                arguments='", "'.join(self.arguments),
                keywords=builtins.str(self.keywords),
                value=convert_to_unicode(self.return_value),
                type=builtins.str(builtins.type(self.return_value))))
Пример #26
0
    def __repr__(self):
        '''
            Invokes if this object should describe itself by a string.

            Examples:

            >>> repr(Buffer())
            'Object of "Buffer" (memory buffered) with content "".'

            >>> buffer = Buffer(file=__test_folder__.path + '__repr__')
            >>> buffer.write('hans') # doctest: +ELLIPSIS
            Object of "Buffer" (file buffered with "...__repr__" (type: file...

            >>> repr(Buffer(queue=True))
            'Object of "Buffer" (queue buffered) with content "".'

            >>> repr(Buffer(queue=native_queue.Queue()))
            'Object of "Buffer" (queue buffered) with content "".'
        '''
        buffer_type = 'memory'
        type_addition = ''
        if self.file:
            buffer_type = 'file'
            type_addition = ' with "%s"' % builtins.repr(self.file)
        elif self.queue:
            buffer_type = 'queue'
# # python3.5
# #         pass
        if self.force_string:
            return (
                'Object of "{class_name}" ({type} buffered{type_addition})'
                ' with content "{content}".'.format(
                    class_name=self.__class__.__name__,
                    type=buffer_type, type_addition=type_addition,
                    content=convert_to_unicode(self.content)))
# #
        return (
            'Object of "{class_name}" ({type} buffered{type_addition}) '
            'with content "{content}".'.format(
                class_name=self.__class__.__name__, type=buffer_type,
                type_addition=type_addition, content=self.content))
Пример #27
0
    def __repr__(self):
        '''
            Describes current properties of analysing object.

            Examples:

            >>> def test(self): pass
            >>> class A(CheckObject):
            ...     def __init__(self):
            ...         builtins.getattr(
            ...             builtins.super(
            ...                 self.__class__, self
            ...             ), inspect.stack()[0][3]
            ...         )()
            ...         self.__func__ = test
            ...         self._method_type = staticmethod
            >>> a = A()

            >>> repr(a) # doctest: +ELLIPSIS
            'Object of "A" with class object "None", object "None", called...'

            >>> a.class_object = A
            >>> repr(a) # doctest: +ELLIPSIS
            'Object of "A" with class object "A", object "None", called...'
        '''
        class_object_name = 'None'
        if self.class_object is not None:
            class_object_name = self.class_object.__name__
        return (
            'Object of "{class_name}" with class object "{class_object_name}",'
            ' object "{object}", called function "{function}" and method type '
            '"{method_type}".'.format(
                class_name=self.__class__.__name__,
                class_object_name=class_object_name,
                object=builtins.repr(self.object),
                function=builtins.str(self.__func__),
                method_type=builtins.str(self._method_type)))
Пример #28
0
 def __str__(self):
     return repr(self)
Пример #29
0
    def _handle_self_class(self, expected_type, given_type, name, value):
# #
        '''
            Checks given argument value against the methods bounded class.

            Examples:

            >>> def test(): pass
            >>> class A(CheckObject):
            ...     def __init__(self):
            ...         builtins.getattr(
            ...             builtins.super(
            ...                 self.__class__, self
            ...             ), inspect.stack()[0][3]
            ...         )()
            ...         self.__func__ = test
            ...         self._method_type = staticmethod
            >>> a = A()

            >>> a._handle_self_class(
            ...     SelfClass, str, 'argument_name', 'value'
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            boostnode.extension.native.SignatureError:..." wasn't called fr...

            >>> a.class_object = A
            >>> a._handle_self_class(
            ...     SelfClass, str, 'argument_name', 'value'
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            boostnode.extension.native.SignatureError: "A.test()" expects ...

            >>> a.class_object = A
            >>> a._handle_self_class(
            ...     SelfClassObject, str, 'argument_name', 'value'
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            boostnode.extension.native.SignatureError: "A.test()" expects in...

            >>> a.class_object = A
            >>> a._handle_self_class(
            ...     SelfClass, A, 'argument_name', A
            ... ) # doctest: +ELLIPSIS
            Object of "A" with class object "A", object "None", called func...

            >>> a.class_object = A
            >>> a._handle_self_class(
            ...     SelfClassObject, A, 'argument_name', a
            ... ) # doctest: +ELLIPSIS
            Object of "A" with class object "A", object "None", called funct...
        '''
        if self.class_object is None:
            raise __exception__(
                '"{function_path}()" wasn\'t called from '
                'a class so "self class" for "{name}" couldn\'t be '
                'determined.'.format(
                    function_path=self.get_function_path(), name=name))
        elif expected_type is SelfClass and value is not self.class_object:
            raise __exception__(
                '"{function_path}()" expects "{object} '
                '(self class)" for "{name}" but "{type}" ({value}) '
                'received.'.format(
                    function_path=self.get_function_path(),
                    object=self.class_object, name=name,
                    type=given_type.__name__,
                    value=builtins.repr(value)))
        elif(expected_type is SelfClassObject and given_type is not
             self.class_object):
            raise __exception__(
                '"{function_path}()" expects instance of '
                '"{object} (self class)" for "{name}" but "{type}" '
                '({value}) received.'.format(
                    function_path=self.get_function_path(),
                    object=self.class_object, name=name,
                    type=given_type.__name__,
                    value=builtins.repr(value)))
        return self
Пример #30
0
print twice(5)
print bool(0)
print bool(5)
print '#--------------------------------#'
# exec语句用来执行储存在字符串或文件中的Python语句
exec 'print "hello"'
# eval语句用来计算存储在字符串中的有效Python表达式。
print eval("2*3")

print '#--------------------------------#'
mylist = ['item']
assert len(mylist) >= 1
print mylist
print mylist.pop()
print mylist

# assert len(mylist) >= 1 #AssertionError
print '#--------------------------------#'
# repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。注意,在大多数时候有eval(repr(object)) == object。
print 2 == eval(repr(2))
print 2 == eval(`(2)`)









Пример #31
0
 def __str__(self):
     return repr(self)
Пример #32
0
 def __repr__(self):
     _s = ["ParserSkeleton.State(", repr(self.data), ")"]
     return ''.join(_s)
Пример #33
0
 e2 = (2*xy)/(x2+y2)
 #print e1
 
 theta = numpy.arctan2(e2,e1)/2.
 r = numpy.sqrt(e1**2 + e2**2)
 u = r*numpy.cos(theta)
 v = r*numpy.sin(theta)
 
 #convert LSST pixels to arcsec
 x1 = x/5.
 y1 = y/5.
 
 fig = plt.figure()
 
 from __builtin__ import repr
 print repr(x)
 
 ax = fig.gca(projection='3d')
 ax.plot_trisurf(x, y, 3.1415*aa*bb, cmap=cm.jet, linewidth=0.2)
 #ax.plot_surface(x, y, area, rstride=10, cstride=10)
 #ax.plot_wireframe(x, y, area, rstride=10, cstride=10)
 #cset = ax.contourf(x, y, area, zdir='z', offset=-100, cmap=cm.coolwarm)
 #cset = ax.contourf(x, y, area, zdir='x', offset=-40, cmap=cm.coolwarm)
 #cset = ax.contourf(x, y, area, zdir='y', offset=40, cmap=cm.coolwarm)
 
 ax.set_xlabel('x')
 #ax.set_xlim(-40, 40)
 ax.set_ylabel('y')
 #ax.set_ylim(-40, 40)
 ax.set_zlabel('PSF area')
 #ax.set_zlim(-100, 100)
Пример #34
0
    def _check_type(
        self, expected_type, given_type, value, name='return value'
    ):
# #
        '''
            Checks if the given value is of its specified type.

            Examples:

            >>> class A(CheckObject): pass

            >>> A()._check_type(
            ...     builtins.type(None), int, 5
            ... ) # doctest: +ELLIPSIS
            Object of "A" with class object "None", object "None", called ...

            >>> A()._check_type(
            ...     int, int, 5
            ... ) # doctest: +ELLIPSIS
            Object of "A" with class object "None", object "None", called ...

            >>> class B:
            ...     def b(self): pass
            >>> a = A()
            >>> b = B()
            >>> a.class_object = B
            >>> a.object = b
            >>> a.__func__ = B.b
            >>> a._check_type(Self, B, b) # doctest: +ELLIPSIS
            Object of "A" with class object "B", object "...

            Check if self type instances can be distinguished.

            >>> a = A()
            >>> a.class_object = B
            >>> a.object = B()
            >>> a.__func__ = B.b
            >>> a._check_type(
            ...     Self, B, B()
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            SignatureError: "B.b()" expects "... (self)" for "return va..."...

            >>> a = A()
            >>> a.class_object = B
            >>> a.object = B()
            >>> a.__func__ = B.b
            >>> a._check_type(SelfClass, B, B) # doctest: +ELLIPSIS
            Object of "A" with class object "B", object "...

            >>> a = A()
            >>> a.class_object = B
            >>> a.object = B()
            >>> a.__func__ = B.b
            >>> a._check_type(SelfClassObject, B, B()) # doctest: +ELLIPSIS
            Object of "A" with class object "B", object "...

            >>> a = A()
            >>> a.class_object = B
            >>> a.object = B()
            >>> a.__func__ = B.b
            >>> a._check_type(
            ...     SelfClassObject, int, 5
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            SignatureError: "B.b()" expects instance of "__main__.B (self c...

            >>> a = A()
            >>> a.class_object = B
            >>> a.object = B()
            >>> a.__func__ = B.b
            >>> a._check_type(
            ...     bool, int, 5
            ... ) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            SignatureError: "B.b()" expects instance of "bool" for "return ...
        '''
        if not self._is_right_type(given_type, expected_type):
            if expected_type is Self:
                self._handle_self(given_type, name, value)
            elif(expected_type is SelfClass or
                 expected_type is SelfClassObject):
                self._handle_self_class(expected_type, given_type, name, value)
            else:
                raise __exception__(
                    '"{function_path}()" expects instance of "{object}" for '
                    '"{name}" but received "{type}" ({value}).'.format(
                        function_path=self.get_function_path(),
                        object=expected_type.__name__, name=name,
                        type=given_type.__name__, value=builtins.repr(value)))
        return self