What is a class?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 8 19:32:03 EST 2008


On Sat, 08 Mar 2008 09:52:41 -0800, castironpi wrote:

> On Mar 7, 6:16 am, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote:
>> > you
>> > could say exec( open( 'modA.py' ).read() ) ==> import modA
>>
>> Yes, you could say that, but you'd be wrong. Please test your code
>> before making such claims in the future.
> 
> Aye aye.  -1 response not phrased in the form of a question.

All the words in that sentence are English, but as a whole it makes no 
sense.


> Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA
> import * create "effectively" same results,

You're getting closer now. (By the way, exec is a statement, so you don't 
need brackets around its arguments.)

    exec open('modA.py').read()

gives *almost* the same results as

    from modA import *


The differences I can think of:

(1) The exec version doesn't cache the results, so if you execute the 
line repeatedly you will execute the same code over and over again, 
possibly causing unexpected side-effects. import caches the results, and 
so will be faster.

(2) The import version may read from modA.pyc, modA.pyo or modA.so even 
if there is a modA.py file. The exec version can't import from anything 
but modA.py. 

(3) The exec version as written always puts the results in the global 
scope, even if you execute it inside a function. (In the future, "from 
modA import *" will be forbidden inside functions, but at the moment it 
is still legal.)

(4) The exec version doesn't search sys.path for modA; import does.

(5) The exec version can't read modules inside a zip file; import can.

There may be other differences I haven't thought of.



> such as in the remaning
> program not checking __module__ attributes?

Again, I don't understand what you are saying.


> Is there a slight modification of both sides that does cover a non-
> trivial volume of programs, such as maybe, exec( open( 'modA.py'
> ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import
> *, or something?


*Slight* modification, no.

I'm sure that with sufficient effort, you could add caching, search 
sys.path, and look inside zip files. Those three things wouldn't be 
horribly difficult, but it wouldn't be a one-liner -- off the top of my 
head, I'd guess fifty to a hundred lines of code to re-invent those 
particular wheels correctly.

However, recreating the rest of the import mechanism would be terribly 
complicated. I'm not really sure it could be done. For example, how would 
you deal with modules written in C from within Python? You'd need access 
to Python internals that, as far as I know, aren't available.



-- 
Steven



More information about the Python-list mailing list