473,799 Members | 3,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there Python equivalent to Perl BEGIN{} block?

Hi all,

The subject says pretty much all, i would very appreciate an answer. I
tried to search the various forums and groups, but didn't find any
specific answer...

Thanks,
Alex.
Mar 12 '08 #1
12 4568
On Mar 12, 6:19 pm, Alex <alex.pul...@gm ail.comwrote:
Hi all,

The subject says pretty much all, i would very appreciate an answer. I
tried to search the various forums and groups, but didn't find any
specific answer...

Thanks,
Alex.
No not really.

There are lots of other ways to structure a Python program though
which makes its omission hardly felt.

- Paddy.
Mar 12 '08 #2
The subject says pretty much all,

Given what I understand about the BEGIN block[1], this is how
Python works automatically:

bash$ cat a.py
print 'a1'
import b
print 'a2'

bash$ cat b.py
print 'b'

bash$ python a.py
a1
b
a2

However, the first import does win and Python caches
module-loading, so take care:

bash$ cat x.py
print 'one'
import a
print 'two'
import b
print 'three'

bash$ python x.py
one
a1
B
a2
two
three

-tkc

[1]
http://www.cs.cf.ac.uk/Dave/PERL/node133.html

Mar 12 '08 #3
On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote:
Hi all,

The subject says pretty much all
Only to people who know what the Perl BEGIN{} block means.

--
Steven

Mar 13 '08 #4
What do you need it for anyway? I just read about it and I think it's
useless
in python.

On Mar 13, 2008, at 1:03 AM, Steven D'Aprano wrote:
On Wed, 12 Mar 2008 11:19:05 -0700, Alex wrote:
>Hi all,

The subject says pretty much all

Only to people who know what the Perl BEGIN{} block means.

--
Steven

--
http://mail.python.org/mailman/listinfo/python-list
Mar 13 '08 #5
On Mar 12, 8:11 pm, Justus Schwabedal <justus.schwabe ...@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.

Python solved a similar problem by introducing __future__ imports.
Carl Banks
Mar 13 '08 #6
Alex wrote:
The subject says pretty much all, i would very appreciate an answer. I
tried to search the various forums and groups, but didn't find any
specific answer...
I'd like an answer to this, too. In Perl, I mostly used it for
one-liners, when a variable needed to be initialized to some non-default
value; for example, perl -ple 'BEGIN { $sum = 42 } $sum += $_'.
Mar 13 '08 #7
On Mar 13, 1:37 am, Carl Banks <pavlovevide... @gmail.comwrote :
On Mar 12, 8:11 pm, Justus Schwabedal <justus.schwabe ...@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.

Python solved a similar problem by introducing __future__ imports.

Carl Banks
And theres me thinking it was part of Perls AWK compatibility code.

- Paddy.
Mar 13 '08 #8
Alex a écrit :
(sni)
First of all thanks all for answering!

I have some environment check and setup in the beginning of the code.
I would like to move it to the end of the script.
Why ? (if I may ask...)
But I want it to
execute first, so the script will exit if the environment is not
configured properly.
If you want some code to execute first when the script/module is loaded,
then keep this code where it belongs : at the beginning of the script.

Mar 13 '08 #9
On Mar 13, 7:02 am, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
Alex a écrit :
(sni)
First of all thanks all for answering!
I have some environment check and setup in the beginning of the code.
I would like to move it to the end of the script.

Why ? (if I may ask...)
But I want it to
execute first, so the script will exit if the environment is not
configured properly.

If you want some code to execute first when the script/module is loaded,
then keep this code where it belongs : at the beginning of the script.

I concur with Bruno's recommendation: stuff you want to do first
should come first in the script. Things like BEGIN blocks hurt
readability because you can't identify where execution begins without
reading the whole file.

Having said that, one thing that often happens in Python scripts is
that all the functions are defined first, then the script logic
follows. So you could put the meat of your script in a function, then
the "BEGIN" stuff after that functions:
def run_script():
#
# script contained in this long function
#

# Then test preconditions here...
if os.environ["HELLO"] != "WORLD":
sys.exit(2)

# Then call the run_script functions
run_script()
But having said THAT, I don't recommend you do that with
preconditions. If the script has a quick early exit scenario, you
really ought to put that near the top, before the function
definitions, to clearly show to a human reader what is necessary to
run the script.
Carl Banks
Mar 13 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

699
34267
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
226
12719
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
31
4813
by: surfunbear | last post by:
I've read some posts on Perl versus Python and studied a bit of my Python book. I'm a software engineer, familiar with C++ objected oriented development, but have been using Perl because it is great for pattern matching, text processing, and automated testing. Our company is really fixated on risk managnemt and the only way I can do enough testing without working overtime (which some people have ended up doing) is by automating my...
20
4085
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort†method. For example: li=;
65
5548
by: Amol Vaidya | last post by:
Hi. I am interested in learning a new programming language, and have been debating whether to learn Ruby or Python. How do these compare and contrast with one another, and what advantages does one language provide over the other? I would like to consider as many opinions as I can on this matter before I start studying either language in depth. Any help/comments are greatly appreciated. Thanks in advance for your help.
0
2267
by: Xah Lee | last post by:
One-Liner Loop in Functional Style Xah Lee, 200510 Today we show a example of a loop done as a one-liner of Functional Programing style. Suppose you have a list of file full paths of images: /Users/t/t4/oh/DSCN2059m-s.jpg
4
1788
by: pmcgover | last post by:
I enjoyed Paul Barry's September article in Linux Journal entitled, "Web Reporting with MySQL, CSS and Perl". It provides a simple, elegant way to use HTML to display database content without any sql markup in the cgi script. The cgi script simply calls the Mysql command line with the HTML option (-H) and the SQL script file directed to that command. This provides complete separation of the markup from the sql code. The plain vanila...
10
14835
by: mm | last post by:
Is there a Perl to Python converter? Or in general: a XY to Python converter? Is see, that Python is much better then Perl anyway. But for beginners, they whant to konw how is this done with Python etc. Sure, there are some docus out there in the internet. But a converter?
8
7467
by: js | last post by:
HI guys, How do you write Perl's print a ... z, A ... Z, "\n"' in Python In Python?
0
10470
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10023
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9067
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7561
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5459
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5583
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4135
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2935
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.