util.py
Go to the documentation of this file.
00001 """Miscellaneous utility functions."""
00002 
00003 from __future__ import absolute_import, division, with_statement
00004 
00005 
00006 class ObjectDict(dict):
00007     """Makes a dictionary behave like an object."""
00008     def __getattr__(self, name):
00009         try:
00010             return self[name]
00011         except KeyError:
00012             raise AttributeError(name)
00013 
00014     def __setattr__(self, name, value):
00015         self[name] = value
00016 
00017 
00018 def import_object(name):
00019     """Imports an object by name.
00020 
00021     import_object('x.y.z') is equivalent to 'from x.y import z'.
00022 
00023     >>> import tornado.escape
00024     >>> import_object('tornado.escape') is tornado.escape
00025     True
00026     >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
00027     True
00028     """
00029     parts = name.split('.')
00030     obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
00031     return getattr(obj, parts[-1])
00032 
00033 # Fake byte literal support:  In python 2.6+, you can say b"foo" to get
00034 # a byte literal (str in 2.x, bytes in 3.x).  There's no way to do this
00035 # in a way that supports 2.5, though, so we need a function wrapper
00036 # to convert our string literals.  b() should only be applied to literal
00037 # latin1 strings.  Once we drop support for 2.5, we can remove this function
00038 # and just use byte literals.
00039 if str is unicode:
00040     def b(s):
00041         return s.encode('latin1')
00042     bytes_type = bytes
00043 else:
00044     def b(s):
00045         return s
00046     bytes_type = str
00047 
00048 
00049 def raise_exc_info(exc_info):
00050     """Re-raise an exception (with original traceback) from an exc_info tuple.
00051 
00052     The argument is a ``(type, value, traceback)`` tuple as returned by
00053     `sys.exc_info`.
00054     """
00055     # 2to3 isn't smart enough to convert three-argument raise
00056     # statements correctly in some cases.
00057     if isinstance(exc_info[1], exc_info[0]):
00058         raise exc_info[1], None, exc_info[2]
00059         # After 2to3: raise exc_info[1].with_traceback(exc_info[2])
00060     else:
00061         # I think this branch is only taken for string exceptions,
00062         # which were removed in Python 2.6.
00063         raise exc_info[0], exc_info[1], exc_info[2]
00064         # After 2to3: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
00065 
00066 
00067 def doctests():
00068     import doctest
00069     return doctest.DocTestSuite()


rosbridge_server
Author(s): Jonathan Mace
autogenerated on Thu Jan 2 2014 11:53:55