Altering the namespace of the calling function

A

Andrew Wilkinson

Hi,

First off I know that in almost all cases this would be a terrible thing to
do, but this is an unusual case where this makes sense.

Basically I have a procedure where you pass a string containting a template
for a tuple, the function then finds a tuple that matches this template and
then returns it. The template may contain variable names, which match
against anything in that position in the tuple - this is all working fine,
except that I would like a variable to be created in the caller's scope by
the matching function.

I can retrieve the scope of the calling function using
sys._getframe(1).f_locals however whenever I try to modify it the changes
are made but the variable doesn't match to the new variable in the scope. I
tried creating a variable of the same name before calling the matching
function, but when the matching function returns the changes to the scope
for that variable are discarded.

Can anyone suggest how to make this work?
Andrew Wilkinson
 
E

Emile van Sebille

Andrew Wilkinson asks:
except that I would like a variable to be created in the caller's scope by
the matching function.

Pass in a mutable or use return. The obvious intent is to use this in the
calling routine, and you're asking how to change the called routine, so
you've got access to both.
I can retrieve the scope of the calling function using
sys._getframe(1).f_locals however whenever I try to modify it the changes
are made but the variable doesn't match to the new variable in the scope.
I

No surprise here. From the manual:
"The contents of this dictionary should not be modified; changes may not
affect the values of local variables used by the interpreter. "

tried creating a variable of the same name before calling the matching
function, but when the matching function returns the changes to the scope
for that variable are discarded.

Can anyone suggest how to make this work?

If both routines are within the same global module scope, you could use
global. If not, you could hang shared variables on a mutually imported
module.

HTH,

Emile van Sebille
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,060
Latest member
BuyKetozenseACV

Latest Threads

Top