473,395 Members | 1,938 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,395 software developers and data experts.

function namespaces

Hi,

I have a variable saved in a file like this

#contents of myfile.py:
testvar = [1,2,3,4]

and I am trying to write a function that does something like this:

def myfunction(filename):
execfile(filename)
print testvar

The problem I am running into is that the global name testvar is not
defined, but I dont understand why. I tried calling dir() in the function,
which does list testvar. I tried declaring tesvar a global before calling
execfile, and that didnt help. If I just run execfile('myfile.py') in the
interactive interpretter, testvar is loaded and I can continue my work.

What am I doing wrong?
Jul 18 '05 #1
5 1540
Darren Dale wrote:
def myfunction(filename):
execfile(filename)
print testvar
What am I doing wrong?


I'm not familiar enough with execfile or the interactive interpreter to
know what you are doing wrong, but something like:

def myfunction(filename):
ns=dict()
execfile(filename, ns)
print ns['testvar']

should at least get you going. There is probably a way to pass the
namespace of the function to execfile, but I do not know it.

max

Jul 18 '05 #2
Hello Darren,
I am not sure why you are using execfile().
Py> help(execfile)
Help on built-in function execfile:

execfile(...)
execfile(filename[, globals[, locals]])

Read and execute a Python script from a file.
The globals and locals are dictionaries, defaulting to the current
globals and locals. If only globals is given, locals defaults to
it.
Do you realize that execfile actually runs your script?

A simple import would probably be the best way to go.
#contents of myfile.py:
testvar = [1,2,3,4]

# someother.py
import myfile
print myfile.testvar

But to answer the question :
#contents of myfile.py:
testvar = [1,2,3,4]

# someother.py
# the problem is you are executing a script
# then searching in the wrong namespace.
def myfunction(filename):
execfile(filename, globals())
print testvar
hth,
M.E.Farmer

Jul 18 '05 #3
Darren Dale wrote:
Hi,

I have a variable saved in a file like this

#contents of myfile.py:
testvar = [1,2,3,4]

and I am trying to write a function that does something like this:

def myfunction(filename):
execfile(filename)
print testvar

The problem I am running into is that the global name testvar is not
defined, but I dont understand why. I tried calling dir() in the function,
which does list testvar. I tried declaring tesvar a global before calling
execfile, and that didnt help. If I just run execfile('myfile.py') in the
interactive interpretter, testvar is loaded and I can continue my work.

What am I doing wrong?


I believe the problem is that, when myfunction is compiled, testvar is
determined to be a global variable (since it's not assigned to in the
function body). Thus, even though execfile properly adds testvar as a
local, the code object for myfunction is trying to look testvar up as a
global. You can check this using dis.dis:

py> dis.dis(myfunction)
2 0 LOAD_GLOBAL 0 (execfile)
3 LOAD_FAST 0 (filename)
6 CALL_FUNCTION 1
9 POP_TOP

3 10 LOAD_GLOBAL 2 (testvar)
13 PRINT_ITEM
14 PRINT_NEWLINE
15 LOAD_CONST 0 (None)
18 RETURN_VALUE

So yes, Python is trying to load testvar as a global.

If testvar should be a global, do something like:

py> def myfunction(filename):
.... execfile(filename, globals())
.... print testvar
....
py> myfunction('myfile.py')
[1, 2, 3, 4]
py> testvar
[1, 2, 3, 4]

and your code should run fine.

If testvar should be a local, you'll have troubles using execfile. Read
the execfile docs[1] which have the warning:

"Warning: The default locals act as described for function locals()
below: modifications to the default locals dictionary should not be
attempted. Pass an explicit locals dictionary if you need to see
effects of the code on locals after function execfile() returns.
execfile() cannot be used reliably to modify a function's locals."

The fact that testvar shows up in the locals() is just part of that
"cannot be used reliably" part. Don't rely on this -- AFAICT, it's a
implementation detail, not something guaranteed by the language.

It does seem to work for me with the exec statement though:

py> def myfunction(filename):
.... exec file(filename).read()
.... print testvar
....
py> myfunction('myfile.py')
[1, 2, 3, 4]
py> testvar
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'testvar' is not defined

So you might approach it this way.
Generally, I avoid execfile within a function. What's your use case?
There may be a better way to approach this problem...

STeVe

[1] http://docs.python.org/lib/built-in-funcs.html#l2h-24
Jul 18 '05 #4
Generally, I avoid execfile within a function. What's your use case?
There may be a better way to approach this problem...


I am writing a simulation that loads some predefined constants, depending on
the options called by the user. I originally had it set up to parse the
file, and load the constants explicitly, but then I thought that with the
existence of this handy builtin execfile, I could make write my constants
file in python, and just load it. I guess it is not the best approach.
Thanks for the advice though (everyone), I learned something.

Jul 18 '05 #5
Darren Dale wrote:
Generally, I avoid execfile within a function. What's your use case?
There may be a better way to approach this problem...

I am writing a simulation that loads some predefined constants, depending on
the options called by the user. I originally had it set up to parse the
file, and load the constants explicitly, but then I thought that with the
existence of this handy builtin execfile, I could make write my constants
file in python, and just load it. I guess it is not the best approach.
Thanks for the advice though (everyone), I learned something.

Aha!

Think about using the dreaded (and dangerous, but in your case
potentially extremely useful)

from config import *

regards
Steve

Jul 18 '05 #6

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

Similar topics

10
by: Malay Haldar | last post by:
I have a function object, from which I derive another function object in which I overwrite the operator(). But now the operator() in the base class seems inaccessible. For example, the following...
12
by: RA Scheltema | last post by:
Hi all, I have the following code: namespace A { inline void func(int) { ...; } inline void func(float) { ...; } inline void func(char) { ...; } }
11
by: Random | last post by:
I'm confused about the proper use and usefulness of namespaces. I beleive I understand the purpose is so the developer can put classes within namespaces to essentially organize your code. And I...
13
by: Lonnie Princehouse | last post by:
Can anyone think of a way to substitute a user-supplied dictionary as the local dict for a function call? e.g. def f(): x = 5 d = {}
5
by: Sakcee | last post by:
python provides a great way of dynamically creating fuctions calls and class names from string a function/class name can be stored as string and called/initilzed e.g def foo(a,b): return...
3
by: jason | last post by:
Please pardon my completely lack of understanding on the topic. I have a website I developed with another developer. We are both far from experts in VB.NET and OOP. We developed the site WITHOUT...
4
by: Ranginald | last post by:
Sorry for the simple question but thanks in advance: My goal is to create reusale code for a web app in C#. I have written the code already as a windows app but here is where I am confused: ...
78
by: Josiah Manson | last post by:
I found that I was repeating the same couple of lines over and over in a function and decided to split those lines into a nested function after copying one too many minor changes all over. The only...
19
by: xdevel | last post by:
Hi, I know there are in stdlib.h many functions to perform conversion from string to int, double ecc. but I don't understand if there are some standards function to perform conversion from...
0
by: Matthew | last post by:
Hi - apologies in advance if this is the wrong list for the following php/soap related question; would appreciate a pointer to the right group. The quick way to phrase my question is - is the...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
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
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,...

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.