def parse_with_objects(code, var, **kwargs): """Parse code and include non string/codeblock kwargs as dependencies. int/long will be inlined. Returns a CodeBlock and the resulting variable mapping. """ deps = {} for key, value in kwargs.items(): if isinstance(value, _compat.integer_types): value = str(value) if _compat.PY3: if value is None: value = str(value) if not isinstance(value, _compat.string_types) and \ not isinstance(value, CodeBlock): new_var = var(value) deps[new_var] = value kwargs[key] = new_var block, var = parse_code(code, var, **kwargs) for key, dep in _compat.iteritems(deps): block.add_dependency(key, dep) return block, var
def pprint(self, file_=sys.stdout): """Print the code block to stdout. Does syntax highlighting if possible. """ code = [] if self._deps: code.append("# dependencies:") for k, v in _compat.iteritems(self._deps): code.append("# %s: %r" % (k, v)) code.append(str(self)) code = "\n".join(code) if file_.isatty(): try: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import TerminalFormatter except ImportError: pass else: formatter = TerminalFormatter(bg="dark") lexer = PythonLexer() file_.write(highlight(code, lexer, formatter)) return file_.write(code + "\n")
def write_into(self, block, level=0): """Append this block to another one, passing all dependencies""" for line, l in self._lines: block.write_line(line, level + l) for name, obj in _compat.iteritems(self._deps): block.add_dependency(name, obj)
def load(namespace, module): global _active_module, _overrides _active_module.append(module) _overrides.append({}) try: name = __name__ + "." + namespace override_module = __import__(name, fromlist=[""]) except Exception as err: try: paths = [os.path.dirname(__file__)] fp, pn, desc = imp.find_module(namespace, paths) except ImportError: pass else: if fp: fp.close() _compat.reraise(ImportError, err, sys.exc_info()[2]) else: # FIXME!!! we need a real non-override module somewhere proxy = get_introspection_module(namespace) for name, klass in _compat.iteritems(_overrides[-1]): setattr(proxy, name, klass) # add all objects referenced in __all__ to the original module override_vars = vars(override_module) override_all = override_vars.get("__all__") or [] for var in override_all: getattr(proxy, var, None) item = override_vars.get(var) if item: # make sure new classes have a proper __module__ try: if item.__module__.split(".")[-1] == namespace: item.__module__ = namespace except AttributeError: pass setattr(module, var, item) _active_module.pop(-1) _overrides.pop(-1)