Is there Python equivalent to Perl BEGIN{} block?

Jonathan Gardner jgardner at jonathangardner.net
Thu Mar 13 15:03:25 EDT 2008


On Mar 12, 6:37 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Mar 12, 8:11 pm, Justus Schwabedal <justus.schwabe... at gmx.de>
> wrote:
>
> > What do you need it for anyway? I just read about it and I think it's
> > useless
> > in python.
>
> Perl, like Python, has a separate compilation and run times.  One day,
> someone who was trying to use Perl for something asked, "You know,
> wouldn't it be neat-o if you could execute some Perl code *before* you
> compiled the script?"  And so (since that's usually enough reason to
> add something to Perl) was borne the BEGIN block.
>
> I believe the official rationale was that they wanted to add some
> magic variables that affected Perl's compilation and couldn't do it
> without a magic block that executed at compile time.
>

It's a bit different. Python's "import" and perl's "use" statements
aren't very similar at all. See, perl looks for any "use" statements
and runs those first. That's not the way for Python at all. It's ok to
import a module right before you need it in a function. If you never
call the function, you'll never import the module.

What if you want to reprogram the search path before you use a module?
Well, in Python, you just work on sys.path before the import
statement. But in perl, if you put a statement that mucks with the
perl path, then it will be ignored until it is too late. So you have
to throw it into the BEGIN block to have it do anything at all. What
was an obvious task in Python that uses only constructs and concepts
you already know about, requires a new concept and syntax that wasn't
needed before in perl.

Also, Jeff has it right. Those who don't get it should look closely at
the '-p' option passed to perl. (It has a cousin '-n' that is also
just as useful.) Here, he wants to initialize some code before the
loop starts, but he can't specify that initializing code outside of
the loop without a BEGIN block.

BEGIN is a dirty, ugly, stupid bandage to an underlying weakness in
perl. That is, there is magic that needs more magic to override it.
(And then you'll need magic to override the overriding magic, ad
infinitum.) Rather than adding more magic, what you really need to do
is get rid of magic that gets in people's way, or change the magic so
it is actually useful for everyone.

Python has it right. Tokenize, parse, (skip compile-link-import
magic), and run.

And leave out the magical -p and -n. If you want to iterate through a
file, "for line in sys.stdin:".



More information about the Python-list mailing list