473,403 Members | 2,338 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Static Modules...


I had an idea yesterday. (Yes, I know. Sorry).

If we don't need to declare variables as having a certain type, why do we
need to import modules into the program? Isn't the "import sys" redundant
if all I want is to call "sys.setrecursionlimit(5000)" ? Why couldn't we
just try loading the module of a name "sys" to see if it exists and re-try
the command?

I tried just that. This is meant as a proof of concept (I called it
autoload.py)

-------- BEGIN HERE ------
import sys, inspect

def autoload_exc(type, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_frame.f_locals
f_globals = traceback.tb_frame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_frame.f_code in f_locals, f_globals

sys.excepthook = autoload_exc

------- END HERE -------

I know there are problems here. Checking if we have a NameError exception
is the most glaring one. Still this works for simple things as a proof of
concept.

Here is an example of a simple session:
import autoload
sys.setrecursionlimit(5000)
dir(time) ['__doc__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock',
'ctime',
'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime',
'strptime', 's
truct_time', 'time', 'timezone', 'tzname'] os.path.join("usr","local","bin")

'usr\\local\\bin'

Any comments?

Greg

Advice is what we ask for when we already know the answer but wish we
didn't.
-- Erica Jong (How to Save Your Own Life, 1977)
Jul 18 '05 #1
8 1804
I tossed this in my PYTHONSTARTUP file, to see how I like it.
No complaints so far, and it might make the interactive prompt even
easier to use.

Jeff

Jul 18 '05 #2
Grzegorz Dostatni <gr******@ee.ualberta.ca> wrote in
news:Pi**************************************@e5-05.ee.ualberta.ca:

I had an idea yesterday. (Yes, I know. Sorry).

If we don't need to declare variables as having a certain type, why do
we need to import modules into the program? Isn't the "import sys"
redundant if all I want is to call "sys.setrecursionlimit(5000)" ? Why
couldn't we just try loading the module of a name "sys" to see if it
exists and re-try the command?

I tried just that. This is meant as a proof of concept (I called it
autoload.py)

-------- BEGIN HERE ------
import sys, inspect

def autoload_exc(type, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_frame.f_locals
f_globals = traceback.tb_frame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_frame.f_code in f_locals, f_globals

sys.excepthook = autoload_exc

------- END HERE -------

I know there are problems here. Checking if we have a NameError
exception is the most glaring one. Still this works for simple things
as a proof of concept.

Here is an example of a simple session:
import autoload
sys.setrecursionlimit(5000)
dir(time) ['__doc__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock',
'ctime',
'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime',
'strptime', 's
truct_time', 'time', 'timezone', 'tzname'] os.path.join("usr","local","bin")

'usr\\local\\bin'

Any comments?


"import this" -> "Explicit is better than implicit."

you dont easily see what exetrnal modules a program uses. that makes it
more difficult to debug, and it makes neat things like py2exe/installer
impossible.

a slight missconception is also there, as variables dont exist out of
nothing, they start apearing when you assign something to them. (appart
from that i dont like to say "variable" in python, more like binding names
to objects.)

so something similar to using "variables" would be:

sys = __import__("sys")

which is already possible without any hack ;-)

however, it could be a nice little hack for interactive sessions when
playing around in the interpreter. but i'd like to see a message when it
imports something, so that later when copy&pasting something to a file, i
dont forget the imports.

chris

--
Chris <cl******@gmx.net>

Jul 18 '05 #3
"import this" -> "Explicit is better than implicit."
This is exactly my point. My way will only work when you reference the
name explicitly, as in:

sys.setrecursionlimit(500)

You're referencing the sys module explicitly. Other than that this
"problem" exactly parallels the discussion between static and dynamic
typing. And we know which way python chooses to go.
you dont easily see what exetrnal modules a program uses. that makes it
more difficult to debug, and it makes neat things like py2exe/installer
impossible.
Alright. I haven't even though of py2exe/installer problem. Still a
solution to that is not outside the realm of possibility. The easiest hack
would be for the autoload to save the "imports" file in the same
directory or display a warning (which is trivially done with the warning
module).

a slight missconception is also there, as variables dont exist out of
nothing, they start apearing when you assign something to them. (appart
from that i dont like to say "variable" in python, more like binding names
to objects.)
Here I would argue that the variables did not get created out of nothing.
It's equivalent to this code:

--- BEGIN HERE ---
import Tkinter, sys
Tkinter.Button(text="Quit", command=sys.exit).pack()
--- END HERE ---

Which is representative of another python philosophy. Don't specify things
you don't need. If you can resonably figure out (without ambiguity) what
the user wants do to - just do it. Don't pester him/her with unnecessary
questions.

so something similar to using "variables" would be:

sys = __import__("sys")

which is already possible without any hack ;-)

however, it could be a nice little hack for interactive sessions when
playing around in the interpreter. but i'd like to see a message when it
imports something, so that later when copy&pasting something to a file, i
dont forget the imports.


That's a good idea.

Greg
Jul 18 '05 #4
Grzegorz Dostatni wrote:
"import this" -> "Explicit is better than implicit."


This is exactly my point. My way will only work when you reference the
name explicitly, as in:

sys.setrecursionlimit(500)

You're referencing the sys module explicitly. Other than that this
"problem" exactly parallels the discussion between static and dynamic
typing. And we know which way python chooses to go.


That's not entirely accurate, I think. With static typing, you
can't even use a variable if you don't predefine it, but predefining
it doesn't necessarily give it a value (or it gives it a benign
default value). With dynamic typing, just asking for a variable
doesn't (normally) magically create one with an appropriate value.

This hack is a cool idea for interactive prompts, but in real
code and even at the prompt it could actually be quite "dangerous".
Importing a module can cause arbitrary code to execute, so it
makes some sense to _require_ the import statement.

After all, what if I had a module called, perhaps inappropriately,
"launch" and it triggered the launch of my personal anti-aircraft
missile when imported? (Yes, bad style too, but I wrote this
control code long ago before I learned good style. ;-) Now in
one of my other modules, I have a subtle bug** which involves an
object named, perhaps unsurprisingly for this example, "launch".

The code looks like this actually (pulled right out of the source
tree!), slightly edited to preserve national security:

def checkLaunchPermission(self):
lunch = self.findLaunchController()
if launch.inhibited:
# code that doesn't launch anything...

Now if I understand it properly, when your hack is in place
this would actually import the launch module and cause all hell
to break loose.

Did I just make a case for static typing with Python? Well,
perhaps, but only in the relatively dangerous area of module
imports and there, unlike with simple variable names, Python
already requires explicit (i.e. static) definitions...

-Peter

** Thanks to Greg for starting this discussion as otherwise I
would not have discovered this bug in time to save you all...
Jul 18 '05 #5

On Sat, 17 Apr 2004, Peter Hansen wrote:
That's not entirely accurate, I think. With static typing, you
can't even use a variable if you don't predefine it, but predefining
it doesn't necessarily give it a value (or it gives it a benign
default value). With dynamic typing, just asking for a variable
doesn't (normally) magically create one with an appropriate value.
Consider this imaginary python code:

asdf.hello()

The problem is that we don't know what asdf is. It could be a module, an
object or even a function (eg.
def asdf(a="Hello", b="World"): .... print (a,b)
.... asdf.hello = asdf


) # closing the (eg.
My claim here is that we don't "magically" create the variable. You are
still required to explicitly ask for it (as in sys.setrecursionlimit -
you're asking for sys), BUT that statement is based on a fact that I KNOW
what sys is - a module. I think that is the root of this discussion. And
no, I don't like the idea of changing syntax to accomodate it ;-)
This hack is a cool idea for interactive prompts, but in real
code and even at the prompt it could actually be quite "dangerous".
Importing a module can cause arbitrary code to execute, so it
makes some sense to _require_ the import statement.
I somewhat agree with this. It is definitely a good idea to require
imports of custom modules. It is quite easy to add that check into the
code. This is a great hack for the interactive mode.
After all, what if I had a module called, perhaps inappropriately,
"launch" and it triggered the launch of my personal anti-aircraft
missile when imported? (Yes, bad style too, but I wrote this
control code long ago before I learned good style. ;-) Now in
one of my other modules, I have a subtle bug** which involves an
object named, perhaps unsurprisingly for this example, "launch".

The code looks like this actually (pulled right out of the source
tree!), slightly edited to preserve national security:

def checkLaunchPermission(self):
lunch = self.findLaunchController()
if launch.inhibited:
# code that doesn't launch anything...

Now if I understand it properly, when your hack is in place
this would actually import the launch module and cause all hell
to break loose.
Hmm.. In the interest of continual survival of human race I could include
a warning whenever including a module. Or perhaps make the binding to
sys.excepthook explicit (an extra statement), but extra statements is what
I want to avoid. Another options would be to make this work *ONLY* for
system libraries (sys,os,os.path,popen, etc.).

One thing I can't get out of my head is that if your launch module is
installed in PYTHONPATH, we're all in danger and should probably seek
cover. Isn't it more likely that launch.py is somewhere deep under
"NSA/development/python/missile" directory? So it should not be imported
automatically. Generally only the system library and custom modules to the
project you're working on are available to be imported.

Did I just make a case for static typing with Python? Well,
perhaps, but only in the relatively dangerous area of module
imports and there, unlike with simple variable names, Python
already requires explicit (i.e. static) definitions...

-Peter


Greg

Jul 18 '05 #6
Grzegorz Dostatni:
Here is another version of the autoload module. This is now at 0.3 and
moving on.


Thanks. Seems to work here under Cygwin (my main Python interactive
shell). What's in a name anyway.

Anton

Jul 18 '05 #7
Grzegorz Dostatni <gr******@ee.ualberta.ca> wrote in message news:<Pi**************************************@e5-05.ee.ualberta.ca>...
I had an idea yesterday. (Yes, I know. Sorry).

-------- BEGIN HERE ------
import sys, inspect

def autoload_exc(type, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_frame.f_locals
f_globals = traceback.tb_frame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_frame.f_code in f_locals, f_globals

sys.excepthook = autoload_exc

------- END HERE -------


Nice hack! The earlier pundits have a point that explicit imports
are a Good Thing for most code, but for the interactive session this
will be really handy. (...considers putting it in .pythonrc)
Jul 18 '05 #8
On Sat, 17 Apr 2004 15:11:16 -0400, rumours say that Peter Hansen
<pe***@engcorp.com> might have written:
After all, what if I had a module called, perhaps inappropriately,
"launch" and it triggered the launch of my personal anti-aircraft
missile when imported? (Yes, bad style too, but I wrote this
control code long ago before I learned good style. ;-) Now in
one of my other modules, I have a subtle bug** which involves an
object named, perhaps unsurprisingly for this example, "launch".


Peter, don't worry. There ain't no such thing as a free launch.
--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #9

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

Similar topics

6
by: Alexandre Gillet | last post by:
Hi, I am trying to build a python interpreter that is static link. My python interpreter was build on RedHat 8.0 using gcc 2.3 and GLIBC 2.3 When running on other linux flavor that still have...
3
by: mudd | last post by:
How do I build Python so that I get static libraries instead of dynamic libraries (e.g. build/lib.solaris-2.8-sun4u-2.3/math.so)? John
49
by: bearophileHUGS | last post by:
Adding Optional Static Typing to Python looks like a quite complex thing, but useful too: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I have just a couple of notes: Boo...
4
by: Torsten Mohr | last post by:
Hi, i'd like to build an executable file that is linked with a python library and executes a script via PyRun_SimpleString or similar functions. Is there a static library of python available,...
3
by: Rickard Lind | last post by:
Is there any way to build the python executable statically and still be able to load modules built as shared libraries? I'm trying to run python scripts on a stripped down FreeBSD (4.9) machine...
12
by: codefixer | last post by:
Hello: I am trying to understand the use of static in this program. http://nanocrew.net/sw/nscdec.c for "inverse" matrix. What difference would it make if it were not static and just "const...
8
by: Robert A Riedel | last post by:
I have an application that requires a DLL and an executable that uses the DLL, both of which were implemented in Visual C++ using unmanged code. Both the executable and the DLL are linked with...
3
by: Phillip Ian | last post by:
Just a quick architecture question. I'm just looking for discussion, not a flame war, please. In the past, I've tended to use a public module for my data layer functions. Something like: ...
3
by: =?Utf-8?B?UGF0UA==?= | last post by:
We have a site that gets many requests for nonexistent pages, files and folders. We want those requests redirected to the index page. However, for static files (i.e. images and some other...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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...

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.