using execfile() in class/instance methods

Wayne Cuddy wcuddy at lserv.ja10629.home
Sat Dec 9 13:07:03 EST 2000


In article <90tb1302s27 at news2.newsguy.com>, Alex Martelli wrote:
>"Wayne Cuddy" <wcuddy at lserv.ja10629.home> wrote in message
>news:slrn932qna.rtk.wcuddy at lserv.ja10629.home...
>> I am attempting to use the execfile() function to "source" a file that
>> has valid python code to create a diction object:
>>
>> bn { 'key' : 'value1',
>>         'key2' : 'value2' }
>
>This is not valid Python code -- it's probably missing an equal-sign
>between the identified bn and the open-brace.
I made a typo, there actually was an '=' after the bn in my file.
>
>
>> I am issueing this command from a class constructor method and would
>> like bn to be bound the class instance.  So in the future I can say:
>>         print self.bn['key']
>
>Piece of cake.
>
>-- file: ba.txt
>bn = { 'key' : 'value1',
>     'key2' : 'value2' }
>-- end of file: ba.txt
>
>-- file: ba.py
>class Ba:
>    execfile('ba.txt')
>    def bu(self):
>        print self.bn['key']
>
>ba = Ba()
>
>ba.bu()
>-- end of file: ba.py
>
>D:\PySym>python ba.py
>value1
>
(I hit something in emacs to make everything go upper case in the
following text)
Your Example Worked But I Want Multiple Instances Of This Class And Be
Able To Pass The Filename As An Arg.  I Also Would Prefer That Bn Be A
Local Variable Of The Function Containing The Execfile() Call.  This
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

I Have Been Able To Get Different Behavior By Passing In Globals() And
Locals() But I have Not Been Able To Get Bn To Be A Local Method Variable.
>
>> Is this possible?  I assume I am screwing up the global() and locals()
>> arguments to the function which I can say that I don't fully
>
>I think it was probably just the missing '=' sign, as above.  The default
>for globals and locals seem to be OK in this case.
>
>> understand.  Also is there another better/worse way to do this???just
>> so I can see what else is out there..
>
>execfile is very risky if the textfile you're executing may contain
>undesired
>stuff, of course; then, you might want to build up the self.bn dictionary
>in a safer manner, which might then be highly preferable.
>
>But if the textfile is fully under your control, this might be quite OK.
>
I am in total control..

thanks,
Wayne
>
>Alex
>
>
>



More information about the Python-list mailing list