473,320 Members | 2,041 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,320 software developers and data experts.

Gathering variable names from within a function.

Greetings,

I was wondering if there was a way to get a list of all the variables which
were executed/created/modified within a function?

Here is a simple example that comes to my mind:

def getVars(func):
...
...
...

def modVar(arg, arg2):

Var1 = arg
Var2 = arg2
Var3 = arg+arg2
return Var3

def main():

print getVars(modVar('test', 'test2'))

# end

naturally, "Var1", "Var2" and "Var3" should be printed to the user. Any
idea?

-- Xavier

oderint dum metuant

Jul 18 '05 #1
3 5291
Xavier wrote:

I was wondering if there was a way to get a list of all the variables which
were executed/created/modified within a function?


Have you looked at the "inspect" standard module?
Jul 18 '05 #2
"Xavier" <sa**@pure-elite.org> wrote in message news:<ma**********************************@python. org>...
Greetings,

I was wondering if there was a way to get a list of all the variables which
were executed/created/modified within a function?

Here is a simple example that comes to my mind:

def getVars(func):
...
...
...

def modVar(arg, arg2):

Var1 = arg
Var2 = arg2
Var3 = arg+arg2
return Var3

def main():

print getVars(modVar('test', 'test2'))

# end

naturally, "Var1", "Var2" and "Var3" should be printed to the user. Any
idea?

What about

def modVar(arg, arg2):
Var1 = arg
Var2 = arg2
Var3 = arg+arg2
print vars()
return Var3

modVar('test', 'test2')

=>

{'arg2': 'test2',
'arg': 'test',
'Var1': 'test',
'Var3': 'testtest2',
'Var2': 'test2'}
-- Xavier

oderint dum metuant


Michele
Jul 18 '05 #3
This will seem excessive, but it`s a little hack I`ve been playing with.
WARNING: It`s incomplete, and, in general, it should probably *not* be
used. Still, here it is, if you`re interested:

import inspect

class ThisResolutionError(Exception):
pass

def this():
"returns the function object that calls it"
# get calling function's name from outer frame
fname = inspect.currentframe(1).f_code.co_name
frameno = 2
func = None
while func is None:
# search the outer frames for a reference to this function
try:
func = inspect.currentframe(frameno).f_locals.get(fname, None)
frameno += 1
except ValueError:
# reached end of call stack
raise ThisResolutionError, "could not resolve %s"%fname
return func # return this function object

'this()' can be used to get hold of the function that you're currently in;
you may then manipulate or inspect that function as you please.

for example:

def modvars(arg1, arg2):
"records it's own modified variables"
var1 = arg1
var2 = arg2
var3 = arg1+arg2
this().__dict__ = vars()
print this().__doc__
return var3

modvars(1,2)
print modvars.__dict__

# OUTPUT:
# records it's own modified variables
# {'arg1': 1, 'arg2': 2, 'var1': 1, 'var3': 3, 'var2': 2}
'this()' appears to work for functions, including nested functions, but it
does not work for bound/unbound methods, or functions stored in a dictionary
(yet). For instance, you can do the following:

def f():
def g():
print "g says 'Hello'"
this().g = g
print f.g
print f.g()
# <function g at 0x00958C60>
# g says 'Hello'

But you can't do this:

def f():
def g():
"g says 'Hello'"
print this().__doc__
this().g = g
print f.g()
# ThisResolutionError: could not resolve g

Anyway, it's still pretty neat to be able to grab hold of a function, from
inside itself, and work with it.
Sean
Jul 18 '05 #4

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

Similar topics

15
by: James | last post by:
Hi, I am finding it increasingly difficult to name my variables. I am not able to think in the right way. Expert C programmers please Help. Regards,
18
by: Carramba | last post by:
Hi! I am wondering what is the best way to control that compiler manage variable names longer then 8 signs. Does it enought to set 2 variables with the same name and difference after 8 sign and...
14
by: Denny | last post by:
For most of my variable names, I use Hungarian notation to determine between one and the other. But what names can I use for public and private variables? I was using prv_varName and pub_varName...
15
by: Thomas Scheiderich | last post by:
I thought I read that the case for the variable names is important. For example Dim Wheel As Integer Wheel here is a different variable from WHEEL. Is this correct?
23
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
6
by: Marcus Kwok | last post by:
I am designing a GUI (my question is not about GUIs) and I have named my variables using a regular naming scheme. However, in order to simplify the code using these variables, I have created an...
1
by: I.am.the.Buddha | last post by:
I am still learning asp and sql. I am having trouble with passing a variable to within an sql statement. I am sure it is something simple like misuse of quotes. Since it may help if i say what i...
16
by: John | last post by:
Does the length of my C variable names have any affect, performance-wise, on my final executable program? I mean, once compiled, etc., is there any difference between these two: number = 3; n =...
4
by: Victor Lagerkvist | last post by:
Hello, I have the need to parse variable names from a string and save them somewhere safe for future usage. Here's my first attempt (I don't have any rules for valid names yet) - but I have a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.