473,811 Members | 2,324 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.setrecursi onlimit(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(ty pe, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_fr ame.f_locals
f_globals = traceback.tb_fr ame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_fr ame.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.setrecursio nlimit(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("u sr","local","bi n")

'usr\\local\\bi n'

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 1827
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.ua lberta.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.setrecursi onlimit(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(ty pe, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_fr ame.f_locals
f_globals = traceback.tb_fr ame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_fr ame.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.setrecursio nlimit(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("u sr","local","bi n")

'usr\\local\\bi n'

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.n et>

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.setrecursio nlimit(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.exi t).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.setrecursio nlimit(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 checkLaunchPerm ission(self):
lunch = self.findLaunch Controller()
if launch.inhibite d:
# 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.setrecursio nlimit -
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 checkLaunchPerm ission(self):
lunch = self.findLaunch Controller()
if launch.inhibite d:
# 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.ua lberta.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(ty pe, value, traceback):
modulename = value.args[0].split()[1][1:-1]
f_locals = traceback.tb_fr ame.f_locals
f_globals = traceback.tb_fr ame.f_globals

exec "import " + modulename in f_locals, f_globals
exec traceback.tb_fr ame.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
22739
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 GLIBC 2.2, the interpreter won't start. (error message: /lib/libc.so.6: version `GLIBC_2.3' not found (required by /mgl/python/i86Linux2/bin/python2.3) Is there a way to build a static python interpreter using gcc 2.3 that can run on any machine...
3
7311
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
3131
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 (http://boo.codehaus.org/) is a different language, but I like its "as" instead of ":" and "->", to have: def min(a as iterable(T)) as T: Instead of:
4
4732
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, so the users don't need to install python?
3
2613
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 which has no shared system libraries so I want to link it statically against libc et al, but it would be nice to still be able to load modules which were built as shared libraries. In particular I have a library for which I've generated a wrapper...
12
1925
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 unsigned char inverse" in global space which it already is ? Thanks.
8
3024
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 functions that are stored in a static library. During initialization of the executable, classes and static globals within functions linked from the static library appear to be initialized twice, once when the executable initializes the run-time code,...
3
1879
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: public module db Friend ConnectionString As String = "" Public Sub InitializeDB(ByVal AConnectionString As String)
3
2740
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 extensions) we do not want to redirect and in that case want to return nothing. We had been using the 404 error page to redirect but need to discriminate the type of file being requested so that we do not return a page when an image is required. We'd...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10648
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
10402
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
10135
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
9205
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
7670
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
6890
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();...
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3018
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.