using execfile() in class/instance methods

Alex Martelli aleaxit at yahoo.com
Sat Dec 9 18:12:20 EST 2000


"Wayne Cuddy" <wcuddy at lserv.ja10629.home> wrote in message
news:slrn934t6r.s9l.wcuddy at lserv.ja10629.home...
    [snip]
> Your Example Worked But I Want Multiple Instances Of This Class And Be
> Able To Pass The Filename As An Arg.

So you don't want a class-attribute but an instance-attribute, OK, then you
do need to pass the appropriate dictionary to execfile (no need for a
locals/globals distinction here):

class Ba:
    def __init__(self, filename):
        execfile('ba.txt', self.__dict__)
    def bu(self):
        print self.bn['key']

ba = Ba('ba.txt')

ba.bu()

OK so far?

> I Also Would Prefer That Bn Be A
> Local Variable Of The Function Containing The Execfile() Call.  This

The locals() dictionary is not guaranteed to be usable this way -- it
will surely work for reading, but modifications to it will not
necessarily be reflected in your local-variables (there's an important
optimization behind this restriction, so, suffer it...!).

Just pass any old dictionary and use it...!

> Would Allow Me To Either Return It Or Bind It To Any Variable Name Of
> The Instance.  So I Want To Do Something Like This:
>
> Class Bla:
>       ...
>       ...
>       Def F1(Self,Filename):
>   Execfile(Filename)
>   Self.Dictfromdisk = Bn
>
>       Def F2(Self):
>   Print Bn

Didn't you just say that you wanted bn to be LOCAL to the function
doing execfile?  If you got your wish, then here it would be local
to f1, thus completely unknown in f2.

The only way f2 can access bn just like that if it is a GLOBAL
variable, which you can obtain by using
    execfile(filename,globals())
in f1, but is a perfectly horrid idea IMHO.

Apart from this weirdness in f2, f1 can be implemented easily:

    def f1(self, filename):
        a={}
        execfile(filename, a)
        self.dictFromDisk = a['bn']

for example.


Alex






More information about the Python-list mailing list