473,795 Members | 3,255 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proposal: add sys to __builtins__

What would people think about adding sys to __builtins__ so that
"import sys" is no longer necessary? This is something I must add to
every script I write that's not a one-liner since they have this idiom
at the bottom:

if __name__ == "__main__":
sys.exit(main(s ys.argv[1:]))

Additionally, the necessity of "import sys" makes some one-liners a
little more unwieldy than they should be--it is surely the module I am
missing the most in one-liners. For example, with this proposal, this
inelegant one-liner:

$ python -c "import sys; print ''.join(sorted( sys.stdin.readl ines()))"

could be replaced by:

$ python -c "print ''.join(sorted( sys.stdin.readl ines()))"

Since sys is surely the most commonly used module (it is imported in 108
of 188 Python 2.4 stdlib modules on my system, and certainly more than
any other module), I would hope few people would be affected by a
namespace collision.

Other languages (e.g. C#) always make their system namespace available
without needing a special import.

In short, given the wide use of sys, its unambiguous nature, and the
fact that it really is built-in already, although not exposed as such, I
think we would be better off if sys were always allowed even without an
import statement.
--
Michael Hoffman
Sep 1 '05
21 1533
Rick Wotnaz wrote:
Michael Hoffman <ca*******@mh39 1.invalid> wrote in
news:df******** **@gemini.csx.c am.ac.uk:

What would people think about adding sys to __builtins__ so that
"import sys" is no longer necessary? This is something I must
add to every script I write that's not a one-liner since they
have this idiom at the bottom:

if __name__ == "__main__":
sys.exit(main(s ys.argv[1:]))

Additionall y, the necessity of "import sys" makes some
one-liners a little more unwieldy than they should be--it is
surely the module I am missing the most in one-liners. For
example, with this proposal, this inelegant one-liner:

$ python -c "import sys; print
''.join(sorte d(sys.stdin.rea dlines()))"

could be replaced by:

$ python -c "print ''.join(sorted( sys.stdin.readl ines()))"

Since sys is surely the most commonly used module (it is
imported in 108 of 188 Python 2.4 stdlib modules on my system,
and certainly more than any other module), I would hope few
people would be affected by a namespace collision.

Other languages (e.g. C#) always make their system namespace
available without needing a special import.

In short, given the wide use of sys, its unambiguous nature, and
the fact that it really is built-in already, although not
exposed as such, I think we would be better off if sys were
always allowed even without an import statement.

+1 here. As far as I'm concerned, both os and sys could be special-
cased that way. That said, I would guess the likelihood of that
happening is 0.

+1 for both.

Colin W.
Sep 4 '05 #11

"Colin J. Williams" <cj*@sympatico. ca> wrote in message
news:JE******** ******@news20.b ellglobal.com.. .
Rick Wotnaz wrote:
+1 here. As far as I'm concerned, both os and sys could be special-
cased that way. That said, I would guess the likelihood of that
happening is 0.

+1 for both.


Some people might prefer that math be special cased. Or some other module.
A neutral criterion is needed.

Terry J. Reedy

Sep 5 '05 #12
"Terry Reedy" <tj*****@udel.e du> wrote in
news:ma******** *************** **************@ python.org:

"Colin J. Williams" <cj*@sympatico. ca> wrote in message
news:JE******** ******@news20.b ellglobal.com.. .
Rick Wotnaz wrote:
+1 here. As far as I'm concerned, both os and sys could be
special- cased that way. That said, I would guess the
likelihood of that happening is 0.

+1 for both.


Some people might prefer that math be special cased. Or some
other module. A neutral criterion is needed.


Actually, I don't think it's beyond reason to suggest that any
module included with the standard distribution be special-cased in
this way. That is, a reference to xxx.func(), without a previous
import of xxx *could* be resolvable automatically, at least for
those modules that can be found in a standard location. Whether
it's a good idea to do so is another question.

Offhand, I am not sure why it would be an insanely poor idea. It
would mean some funky namespace building and possibly redundant
imports, I guess. I'll certainly defer to just about anybody else's
opinion as to the difficulty and advisability, but I believe it
would be possible to do.

Note that I am not saying that a reference to, say, 'argv' should
provoke an automatic import. I don't mean that some automatic
search for a matching function name should be done through some
undefined module chain. I'm talking only about qualified
references, like os.path or sys.stderr.

As it is, a NameError is generated if the proper import has not
been done. At the point of that error, the module name is known.
For the programmer to fix the situation, an import statement has to
be added to the code and then the code must be rerun. I don't see
why it would be impossible to make that happen automatically,
provided the module to be imported was recognized (through some
undefined magic). I'd think the module would have to be known,
because trying to import a nonexistent module -- "import ssy", say
(in the event of a typo for "sys") -- would fail, so there would
have to be a way to avoid looping on the "ssy.func() " line.

Is it worth adding that kind of complexity to execution of a Python
program? Probably not.

Is it even a good idea to try to make it happen automatically?
Possibly not. For one thing, it wouldn't always be the right thing
to do. A developer would most likely want to set up the imports
properly, and to know when they were not correctly set up instead
of having Python fix things quietly. There's a reason why Explicit
is better than Implicit.

But *could* it be done? I'd think so.

--
rzed
Sep 5 '05 #13
Rick Wotnaz enlightened us with:
That is, a reference to xxx.func(), without a previous import of xxx
*could* be resolvable automatically, at least for those modules that
can be found in a standard location.
-1 on that one. If I want to use a module, I'll write an import
statement for it. Those import statements make it very easy to get an
overview of the modules in use.

Automatically importing modules has the counter-effect of not
generating errors when they should be. Someone could have a class
stored in a variable 'os' and call a function on it. If this person
forgets to assign a value to 'os', an error message should be given
instead of importing the 'os' module.

Another issue is speed. If every reference in the form xxx.yyy has to
trigger an import when xxx isn't known, it will probably slow down
programs quite badly.

A programming language should not be ambiguous. The choice between
importing a module and calling a function should not depend on the
availability of a (local) variable.
I don't see why it would be impossible to make that happen
automatically, provided the module to be imported was recognized
(through some undefined magic).
The question is not if it's possible or not - in principle, everything
is possible. The question is if it is desirable.
A developer would most likely want to set up the imports properly,
and to know when they were not correctly set up instead of having
Python fix things quietly.
Yep.
But *could* it be done? I'd think so.


Sure.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Sep 5 '05 #14
In article <Xn************ *********@63.22 3.7.253>,
Rick Wotnaz <de*****@wtf.co m> wrote:
Michael Hoffman <ca*******@mh39 1.invalid> wrote in
news:df******** **@gemini.csx.c am.ac.uk:
What would people think about adding sys to __builtins__ so that
"import sys" is no longer necessary? This is something I must
add to every script I write that's not a one-liner since they
have this idiom at the bottom:

if __name__ == "__main__":
sys.exit(main(s ys.argv[1:]))

[...]

In short, given the wide use of sys, its unambiguous nature, and
the fact that it really is built-in already, although not
exposed as such, I think we would be better off if sys were
always allowed even without an import statement.


+1 here. As far as I'm concerned, both os and sys could be special-
cased that way. That said, I would guess the likelihood of that
happening is 0.


While I'm mildly uncomfortable with the precedent that would be set by
including the contents of "sys" as built-ins, I must confess my
objections are primarily aesthetic: I don't want to see the built-in
namespace any more cluttered than is necessary -- or at least, any more
than it already is.

But "os" is another matter -- the "os" module contains things which
might well not be present in an embedded Python environment (e.g., file
and directory structure navigation, stat). Do you really want to force
everyone to deal with that? Is it so much more work to add "import os"
to those Python programs that require it?

Of course, you might counter "why should we force everybody else to type
`import os' just in case somebody wants to imbed Python?" But then, why
don't we just include the whole standard library in __builtins__? Or,
since that would be too much, maybe we survey the user community and
include the top fifteen most included modules! Where do you draw the
line? Do you really want to hard-code user opinions into the language?

Right now, we have a nice, simple yet effective mechanism for
controlling the contents of our namespaces. I don't think this would be
a worthwhile change. -1.

-M

--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
Sep 5 '05 #15
"Michael J. Fromberger"
<Mi************ ******@Clothing .Dartmouth.EDU> wrote in
news:Michael.J. Fromberger-3F0330.09342305 092005@localhos t:
In article <Xn************ *********@63.22 3.7.253>,
Rick Wotnaz <de*****@wtf.co m> wrote:
Michael Hoffman <ca*******@mh39 1.invalid> wrote in
news:df******** **@gemini.csx.c am.ac.uk:
> What would people think about adding sys to __builtins__ so
> that "import sys" is no longer necessary? This is something I
> must add to every script I write that's not a one-liner since
> they have this idiom at the bottom:
>
> if __name__ == "__main__":
> sys.exit(main(s ys.argv[1:]))
>
> [...]
>
> In short, given the wide use of sys, its unambiguous nature,
> and the fact that it really is built-in already, although not
> exposed as such, I think we would be better off if sys were
> always allowed even without an import statement.


+1 here. As far as I'm concerned, both os and sys could be
special- cased that way. That said, I would guess the
likelihood of that happening is 0.


While I'm mildly uncomfortable with the precedent that would be
set by including the contents of "sys" as built-ins, I must
confess my objections are primarily aesthetic: I don't want to
see the built-in namespace any more cluttered than is necessary
-- or at least, any more than it already is.

But "os" is another matter -- the "os" module contains things
which might well not be present in an embedded Python
environment (e.g., file and directory structure navigation,
stat). Do you really want to force everyone to deal with that?
Is it so much more work to add "import os" to those Python
programs that require it?

Of course, you might counter "why should we force everybody else
to type `import os' just in case somebody wants to imbed
Python?" But then, why don't we just include the whole standard
library in __builtins__? Or, since that would be too much,
maybe we survey the user community and include the top fifteen
most included modules! Where do you draw the line? Do you
really want to hard-code user opinions into the language?

Right now, we have a nice, simple yet effective mechanism for
controlling the contents of our namespaces. I don't think this
would be a worthwhile change. -1.


You're right that there is no necessity for such a change. I was
not actually talking about importing *any* module in every case,
but rather about importing, say, 'sys' when, for example, sys.argv
appeared in the code and no import had been specified. In another
post I go into a little more detail about what I meant, but in any
case I did not and do not think it's necessary. I have no problem
keying in the import statement and the current system works fine.
It could be argued that it would be convenient in the case of quick
utility code not to have to import well-known modules explicitly,
and it could be argued that 'sys' in particular contains much that
is so seemingly fundamental that it could be built in. I'd not
argue that it should be split out if it were already built in; it
seems to be borderline standard as it is. I suppose it's a C
mindset talking, there.

When I'm cobbling together a Q&D script, my routine often involves
running it once and then going back in and inserting the single
import line that I forgot. It's a minor annoyance, because it seems
clear to me that the needed information is actually available to
Python when it kicks out its NameError. But it *is* minor, and I am
not seriously proposing a change to Python in this regard.

--
rzed
Sep 5 '05 #16
Michael J. Fromberger wrote:
While I'm mildly uncomfortable with the precedent that would be set

by including the contents of "sys" as built-ins, I must confess my
objections are primarily aesthetic: I don't want to see the built-in
namespace any more cluttered than is necessary -- or at least, any more
than it already is.
I agree with this sentiment, and I'll also additionally say that 'import
sys' doesn't seem to be needed when writing sufficiently high-level
code. My python mud client (forever in development, but the
structure-code is mostly done) uses TKinter, Twisted, and glue code for
just about everything.

In currently 1,080 lines of Python code (reported by wc -l, so it
includes a few blank lines) in 9 files, I needed "import sys" once. [1]

After I import sys, I use it exactly once -- I check the platform so I
can use the higher resolution time.clock on win32 [time.time on win32
(win2k) seems to have a resolution of 10ms, while on a 'nix I tested
with time.time has at least ms resolution]. I'll probably use sys again
somewhere to build an automagic version/platform string, but uses for it
seem to be very limited.

I also have 0 imports of 'os', and the only immediately useful case that
comes to mind is implementation of a #dir scripting command -- providing
a minimal shell functionality, and this is certainly not a core
component of the program.

In my opinion, using 'sys' and 'os' are extreme examples of "low-level"
Python programming. This sort of thing is probably very useful for
writing actual scripts that replace the sort of work done by shell
scripts, but as programs get more complicated I think they'd be used
(proportionally ) less and less.

I'm -0.9 on sys (really don't like the idea but it wouldn't be awful to
see it included in __builtins__, provided it's namespaced appropriately)
and -1 on os.

[1] Actually, it's in there three times, but they're all in the same
file -- I'd just left a legacy 'import sys' in a couple local scopes and
forgot to remove them.
Sep 6 '05 #17
In article <Xn************ *********@63.22 3.7.253>,
Rick Wotnaz <de*****@wtf.co m> wrote:
You're right that there is no necessity for such a change. I was
not actually talking about importing *any* module in every case,
but rather about importing, say, 'sys' when, for example, sys.argv
appeared in the code and no import had been specified.


I think I must have missed that post; I will go back and look at it.
However, while I'm here, how would your proposal deal with code like
this:

import foobar

# ... some while later ...
def f( ... ):
...
global foobar, sys
sys = foobar
...

# ... some while even later ...
f( ... )
sys.wallaby("Fe ar and loathing!")

In particular, we have no import of sys, but the name "sys" is
meaningful as a local alias for a different module. I'm not saying you
couldn't deal with this, but it rules out some of the more obvious ways
of detecting and automatically handling this kind of substitution.

Naturally, you might well ask, "why would you do such a fool thing?" To
this I can only respond: "Never underestimate the ingenuity of fools."

-M

--
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
Sep 7 '05 #18
Sybren Stuvel wrote:
A programming language should not be ambiguous. The choice
between importing a module and calling a function should not
depend on the availability of a (local) variable.
Yeah, this behavior would be as ambiguous as if we had a system-defined
search-path for modules, where you might get one module or another
depending on the path order. Oh, wait -- we have one of those.
The question is not if it's possible or not - in principle, everything
is possible. The question is if it is desirable.


Exactly. So it pays to try to understand what the payoff might be, and
I always try to be open-minded about that (although I sometimes fail
miserably in this goal). In the case of sys.path, the payoff is that a
Python application has a small chance of running on a completely
different system. In the case of automagic importation, the only
payoff I have seen discussed is that some people would be happier with
a little less typing.

The thing I always find baffling is that people who find it hard to
type "import sys" seem to find it quite easy to write eight paragraphs
explaining why it's bad to have to type "import sys."

Regards,
Pat

Sep 7 '05 #19
"Michael J. Fromberger"
<Mi************ ******@Clothing .Dartmouth.EDU> wrote in
news:Michael.J. Fromberger-F58CC8.20585806 092005@localhos t:
In article <Xn************ *********@63.22 3.7.253>,
Rick Wotnaz <de*****@wtf.co m> wrote:
You're right that there is no necessity for such a change. I
was not actually talking about importing *any* module in every
case, but rather about importing, say, 'sys' when, for example,
sys.argv appeared in the code and no import had been specified.


I think I must have missed that post; I will go back and look at
it. However, while I'm here, how would your proposal deal with
code like this:

import foobar

# ... some while later ...
def f( ... ):
...
global foobar, sys
sys = foobar
...

# ... some while even later ...
f( ... )
sys.wallaby("Fe ar and loathing!")

In particular, we have no import of sys, but the name "sys" is
meaningful as a local alias for a different module. I'm not
saying you couldn't deal with this, but it rules out some of the
more obvious ways of detecting and automatically handling this
kind of substitution.

Naturally, you might well ask, "why would you do such a fool
thing?" To this I can only respond: "Never underestimate the
ingenuity of fools."


I don't know that this would cause any particular problem with the
[not exactly-]proposed method. The automagic lookup would not be
triggered until a NameError occurred, which would not happen in this
case. As you say, why would anyone -- at least anyone who wanted to
rely on sys.xxx being automatically resolved -- do such a thing? Even
under the current scheme, occluding 'sys' would prevent correct
interpretation of sys.argv. An error is an error in either case.

Now, if 'wallaby' is not part of the foobar namespace, the automagic
system would kick in an incorrectly import sys, and on retry would
still not find 'wallaby' in the namespace. Much merriment would
ensue, I'm sure. At that point, I'd want such a system to have a
nervous breakdown and allow the debugging to begin. Whether I hand-
entered an import statement or not wouldn't change that.

--
rzed
Sep 7 '05 #20

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

Similar topics

1
1809
by: Opinder | last post by:
Hi, For the Python experts out there: Are there any side effects in assigning new variables to the __builtins__ module for the purpose of exposing variables to imported modules. For example.
0
1762
by: Mathieu Fenniak | last post by:
Good day, I'm writing an application which creates modules and runs Python code on the fly, embedding Python. The main function of the code is loaded into the __main__ module: (Error checking omitted for brevity.) PyObject* module = PyImport_AddModule("__main__"); PyObject* moduleDict = PyModule_GetDict(module); PyObject* runRetval = PyRun_String(codeStr, Py_file_input, moduleDict, moduleDict);
1
1370
by: Michael Hohn | last post by:
Hi, using the file builtin_check.py with content # Module builtin_check # Inconstency in the binding of __builtins__ def get_binding(name): return locals() def get_global_binding(name):
4
1493
by: Collin Winter | last post by:
Hallo all, As it currently stands, the type of the global __builtins__ differs depending on whether you're in the __main__ namespace (__builtins__ is a module) or not (its a dict). I was recently tripped up by this discrepancy, and googling the issue brings up half-a-dozen or so c.l.p threads where others have been bitten by this, too. I'd like to propose that in Py3.0 (if not earlier), __builtins__ will be the same type regardless of...
1
1743
by: Adam Hupp | last post by:
I've noticed some unexpected behavior with __builtins__ during module import. It seems that during module import __builtins__ is a dict but at all other times it is a module. For example, if the file testmod.py has these contents: print type(__builtins__) print "has str attr", hasattr(__builtins__, 'str') The output differs depending on how it is run:
3
4177
by: loquehumaine | last post by:
Hi there, I'm a newby in python (I know a little in programmation) and I have a lot of questions on builtins but my first one is about modules... I have seen that if I type help() at a prompt, and then 'modules', I'll be given a list of all modules available, thanks to this group.. But I have seen the differences between them and the one in dir(__builtins__). Why are some modules in __builtins__ and others don't ? (UserDict for example)
0
1086
by: Patrick Maupin | last post by:
__builtins__ in 2.5.2 doesn't seem to behave like I remember it did the last time I did some custom stuff with it, a very long time ago. This isn't surprising, because of ongoing optimization, but it's hard to google for '__builtins__' so I didn't really find any documentation on the current CPython behavior, which in some cases seems quite strange to me. The documentation node at http://docs.python.org/ref/naming.html has a "here be...
3
1374
by: Gabriel Genellina | last post by:
En Sun, 07 Sep 2008 14:00:48 -0300, Patrick Maupin <pmaupin@gmail.comescribió: Python takes some shortcuts when dealing with builtins. I'll just describe what happens (I won't say whether it is "right" or "wrong"). The exec statement, when given a string source, compiles it and eventually calls PyEval_EvalCodeEx, which creates a new frame using PyFrame_New and finally executes it. A frame object contains a pointer to the previous frame,...
0
1218
by: Lie Ryan | last post by:
On Tue, 30 Sep 2008 16:04:34 -0500, William Purcell wrote: when you pass mydict, it is used as the global variables in the eval, right? Then, you passed a code to eval('...', mydict), sometimes you might create global variable inside eval, and you want to see the value of that inner global, that's why python modified mydict as a side-effect. Then what is __builtins__ doing there? Because when eval created an environment for the code...
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10438
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...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
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
9042
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
7540
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
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
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...
3
2920
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.