[Tutor] compile doesn't work

Michael P. Reilly arcege@shore.net
Sat, 9 Oct 1999 23:00:48 -0400 (EDT)


> i am having problems with compile...i looked at your help thing and 
> everyhing but nothing seems to work...can you please give me DETAILED 
> instructions on how to do this...
> Thanks,
> AndyQuake

Andy,

You don't say what your problem is or what you have tried.  The docs
are pretty clear about the builtin compile() function:
  http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-106

But basically, it goes like so.  There are three required arguments,
the string to compile, the filename it came from, and what kind of
compilation to perform (a string argument).

If the string did not come from a file, the convention is to use the
filename '<string>'.

There are three valid values for the kind of compilation argument.  The
first is 'exec', where the first argument is compiled as python
statements; for example, the string could be a for loop, a function
definition, an assignment, or combinations.  The second is 'eval' which
allows expressions, such as function calls, arithmetic, subscripting,
etc.  The last is 'single' which works just like interactive mode.  Any
python statement that does not result in None will by printed to
stdout.

Here are some examples:
  >>> c = compile('a = 10', '<string>', 'exec')
  # an assignment cannot be an expression
  >>> b = compile('a = 10', '<string>', 'eval')
  Traceback (innermost last):
    File "<stdin>", line 1, in ?
    File "<string>", line 1
      a = 10
        ^
  SyntaxError: invalid syntax
  >>> d = compile('a ** 2', '<string>', 'eval')
  # just because we compile the code doesn't mean it has run yet
  >>> v1 = eval(d)
  Traceback (innermost last):
    File "<stdin>", line 1, in ?
  NameError: a
  # we could use eval(c) too, but it would return None
  >>> exec c
  >>> v1 = eval(d)
  >>> print v1
  100
  >>> s = compile('range(a)', '<string>', 'single')
  # 'single' prints non-None values to the screen like interactive mode
  >>> v2 = eval(s)
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  >>> v2 is None
  1
  >>>

I hope this helps you understand it better; you might want to read the
Python Language Reference Manual.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------