b3j0f.utils.runtime module

Code from http://code.activestate.com/recipes/277940-decorator-for-bindingconstants-at-compile-time/

Decorator for automatic code optimization. If a global is known at compile time, replace it with a constant. Fold tuples of constants into a single constant. Fold constant attribute lookups into a single constant.

Modifications:

  • Add constants values from opmap constants (STORE_GLOBAL, etc.) in order to

    avoid to update globals.

  • Modify verbose argument which is None or use a function with one argument

    which can be bound to a print function or a logging function.

  • Set attributes from originary function such as __dict__, __module__, etc.

b3j0f.utils.runtime.SAFE_BUILTINS = {'__builtins__': {'bytearray': <type 'bytearray'>, 'all': <built-in function all>, 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'sorted': <built-in function sorted>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'NameError': <type 'exceptions.NameError'>, 'BytesWarning': <type 'exceptions.BytesWarning'>, 'dict': <type 'dict'>, 'IOError': <type 'exceptions.IOError'>, 'oct': <built-in function oct>, 'bin': <built-in function bin>, 'SystemExit': <type 'exceptions.SystemExit'>, 'StandardError': <type 'exceptions.StandardError'>, 'format': <built-in function format>, 'TabError': <type 'exceptions.TabError'>, 'next': <built-in function next>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'IndexError': <type 'exceptions.IndexError'>, 'RuntimeWarning': <type 'exceptions.RuntimeWarning'>, 'bytes': <type 'str'>, 'iter': <built-in function iter>, 'Warning': <type 'exceptions.Warning'>, 'round': <built-in function round>, 'dir': <built-in function dir>, 'cmp': <built-in function cmp>, 'False': False, 'set': <type 'set'>, 'list': <type 'list'>, 'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>, 'issubclass': <built-in function issubclass>, 'apply': <built-in function apply>, 'EOFError': <type 'exceptions.EOFError'>, 'BufferError': <type 'exceptions.BufferError'>, 'slice': <type 'slice'>, 'FloatingPointError': <type 'exceptions.FloatingPointError'>, 'sum': <built-in function sum>, 'getattr': <built-in function getattr>, 'abs': <built-in function abs>, 'True': True, 'FutureWarning': <type 'exceptions.FutureWarning'>, 'ImportWarning': <type 'exceptions.ImportWarning'>, 'None': None, 'hash': <built-in function hash>, 'len': <built-in function len>, 'frozenset': <type 'frozenset'>, 'ord': <built-in function ord>, 'super': <type 'super'>, 'TypeError': <type 'exceptions.TypeError'>, 'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>, 'UserWarning': <type 'exceptions.UserWarning'>, 'filter': <built-in function filter>, 'range': <built-in function range>, 'staticmethod': <type 'staticmethod'>, 'SystemError': <type 'exceptions.SystemError'>, 'BaseException': <type 'exceptions.BaseException'>, 'pow': <built-in function pow>, 'RuntimeError': <type 'exceptions.RuntimeError'>, 'float': <type 'float'>, 'MemoryError': <type 'exceptions.MemoryError'>, 'StopIteration': <type 'exceptions.StopIteration'>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'Ellipsis': Ellipsis, 'LookupError': <type 'exceptions.LookupError'>, 'basestring': <type 'basestring'>, 'UnicodeError': <type 'exceptions.UnicodeError'>, 'zip': <built-in function zip>, 'hex': <built-in function hex>, 'long': <type 'long'>, 'IndentationError': <type 'exceptions.IndentationError'>, 'int': <type 'int'>, 'chr': <built-in function chr>, 'type': <type 'type'>, 'Exception': <type 'exceptions.Exception'>, 'tuple': <type 'tuple'>, 'reduce': <built-in function reduce>, 'reversed': <type 'reversed'>, 'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>, 'hasattr': <built-in function hasattr>, 'delattr': <built-in function delattr>, 'setattr': <built-in function setattr>, 'SyntaxWarning': <type 'exceptions.SyntaxWarning'>, 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'str': <type 'str'>, 'property': <type 'property'>, 'GeneratorExit': <type 'exceptions.GeneratorExit'>, 'ImportError': <type 'exceptions.ImportError'>, 'xrange': <type 'xrange'>, 'KeyError': <type 'exceptions.KeyError'>, 'coerce': <built-in function coerce>, 'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>, 'EnvironmentError': <type 'exceptions.EnvironmentError'>, 'unichr': <built-in function unichr>, 'id': <built-in function id>, 'OSError': <type 'exceptions.OSError'>, 'DeprecationWarning': <type 'exceptions.DeprecationWarning'>, 'min': <built-in function min>, 'UnicodeWarning': <type 'exceptions.UnicodeWarning'>, 'any': <built-in function any>, 'complex': <type 'complex'>, 'bool': <type 'bool'>, 'ValueError': <type 'exceptions.ValueError'>, 'NotImplemented': NotImplemented, 'map': <built-in function map>, 'buffer': <type 'buffer'>, 'max': <built-in function max>, 'object': <type 'object'>, 'repr': <built-in function repr>, 'callable': <built-in function callable>, 'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>, 'ReferenceError': <type 'exceptions.ReferenceError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 'NotImplementedError': <type 'exceptions.NotImplementedError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 'exceptions.OverflowError'>}}

safe builtins.

b3j0f.utils.runtime.safe_eval(source, _globals=None, _locals=None)[source]

Process a safe evaluation.

b3j0f.utils.runtime.safe_exec(source, _globals=None, _locals=None)[source]

Do a safe python execution.

b3j0f.utils.runtime.bind_all(morc, builtin_only=False, stoplist=None, verbose=None)[source]

Recursively apply constant binding to functions in a module or class.

Use as the last line of the module (after everything is defined, but before test code). In modules that need modifiable globals, set builtin_only to True.

Parameters:
  • morc – module or class to transform.
  • builtin_only (bool) – only transform builtin objects.
  • stoplist (list) – attribute names to not transform.
  • verbose (function) – logger function which takes in parameter a message
b3j0f.utils.runtime.make_constants(builtin_only=False, stoplist=None, verbose=None)[source]

Return a decorator for optimizing global references.

Replaces global references with their currently defined values. If not defined, the dynamic (runtime) global lookup is left undisturbed. If builtin_only is True, then only builtins are optimized. Variable names in the stoplist are also left undisturbed. Also, folds constant attr lookups and tuples of constants. If verbose is True, prints each substitution as is occurs.

Parameters:
  • builtin_only (bool) – only transform builtin objects.
  • stoplist (list) – attribute names to not transform.
  • verbose (function) – logger function which takes in parameter a message
b3j0f.utils.runtime.singleton_per_scope(_cls, _scope=None, _renew=False, *args, **kwargs)[source]

Instanciate a singleton per scope.

b3j0f.utils.runtime.getcodeobj(consts, intcode, newcodeobj, oldcodeobj)[source]

Get code object from decompiled code.

Parameters:
  • consts (list) – constants to add in the result.
  • intcode (list) – list of byte code to use.
  • newcodeobj – new code object with empty body.
  • oldcodeobj – old code object.
Returns:

new code object to produce.