Пример #1
0
    def __init__(self, x=(), file=None, **kw):
        super(Block, self).__init__(**kw)

        self.on_trait_change(self._structure_changed, 'sub_blocks')
        self.on_trait_change(self._structure_changed, 'sub_blocks_items')
        self.on_trait_change(self._structure_changed, 'ast')

        # Interpret arguments:

        is_file_object = lambda o: hasattr(o, 'read') and hasattr(o, 'name')

        # 'file' -> 'x'
        if file is not None:
            # Turn 'file' into a file object and move to 'x'
            if isinstance(file, basestring):
                file = open(file)
            elif not is_file_object(file):
                raise ValueError("Expected 'file' to be a file or string, "
                                 "got %r" % f)
            x = file

        # 'x': file object -> string
        saved_filename = None
        if is_file_object(x):
            self.filename = x.name
            saved_filename = self.filename
            x = x.read()

        # 'x' -> 'self.ast' or 'self.sub_blocks'
        if isinstance(x, basestring):
            # (BlockTransformer handles things like 'import *')
            self.ast = parse(x, mode='exec', transformer=BlockTransformer())
        elif isinstance(x, Node):
            self.ast = x
        elif is_sequence(x):
            self.sub_blocks = map(to_block, x)
        else:
            raise ValueError('Expecting string, Node, or sequence. Got %r' % x)

        # We really want to keep the filename for "pristine" blocks, and
        # _structure_changed nukes it most times
        self.filename = saved_filename
Пример #2
0
 def from_string(cls, s):
     ast = parse(s, mode='eval', transformer=BlockTransformer())
     assert isinstance(ast, compiler.ast.Expression)
     v = compiler.walk(ast, NameFinder())
     return Expression(ast, v.free, v.locals)