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

Inferring initial locals()

I wonder if there is a (preferably not too-hackish) solution to the
following introspection problem: given a callable and a number of
positional and/or keyword arguments, infer what would be the frame's
locals() right after the function is called. For example, given:

def f(x, y=1, *a, **k):
z = x + y
w = len(a) - len (k)
return z * w

I'd like to have a function

def get_init_locals(callable, *args, **kwds):
# TODO
pass

so that:
>>get_init_locals(f, 3)
{'a': (), 'k': {}, 'x': 3, 'y': 1}
>>get_init_locals(f, 3, 4, 5)
{'a': (5,), 'k': {}, 'x': 3, 'y': 4}
>>get_init_locals(f, 3, q=-1)
{'a': (), 'k': {'q': -1}, 'x': 3, 'y': 1}

Any takers ?

George

Jun 21 '07 #1
4 1165
On Jun 21, 8:51 pm, George Sakkis <george.sak...@gmail.comwrote:
I wonder if there is a (preferably not too-hackish) solution to the
following introspection problem: given a callable and a number of
positional and/or keyword arguments, infer what would be the frame's
locals() right after the function is called. For example, given:

def f(x, y=1, *a, **k):
z = x + y
w = len(a) - len (k)
return z * w

I'd like to have a function

def get_init_locals(callable, *args, **kwds):
# TODO
pass

so that:
>get_init_locals(f, 3)

{'a': (), 'k': {}, 'x': 3, 'y': 1}
You might be intersted in the 'inspect' module.
Jun 21 '07 #2
On Jun 21, 4:42 pm, "bruno.desthuilli...@gmail.com"
<bruno.desthuilli...@gmail.comwrote:
On Jun 21, 8:51 pm, George Sakkis <george.sak...@gmail.comwrote:
I wonder if there is a (preferably not too-hackish) solution to the
following introspection problem: given a callable and a number of
positional and/or keyword arguments, infer what would be the frame's
locals() right after the function is called. For example, given:
def f(x, y=1, *a, **k):
z = x + y
w = len(a) - len (k)
return z * w
I'd like to have a function
def get_init_locals(callable, *args, **kwds):
# TODO
pass
so that:
>>get_init_locals(f, 3)
{'a': (), 'k': {}, 'x': 3, 'y': 1}

You might be intersted in the 'inspect' module.
Turns out it wasn't that hard after all; I came up with the following:

import types, inspect
from itertools import islice, izip

def localsProber(callable):
args, varargs, varkw, defaults = inspect.getargspec(callable)
if defaults is None: defaults = ()
# create a function with the same signature as the callable and
# "return locals()" for body
context = {'__builtins__': {'locals': locals}}
iterargs = iter(args)
# - first all the required args
sig_args = list(islice(iterargs, len(args)-len(defaults)))
# - then all the default args
for arg,default in izip(iterargs,defaults):
context[arg] = default
sig_args.append('%s=%s' % (arg,arg))
# - then variable positional and keyword args (if any)
if varargs: sig_args.append('*' + varargs)
if varkw: sig_args.append('**' + varkw)
name = callable.__name__
exec 'def %s(%s): return locals()' % (name, ', '.join(sig_args))
in context
prober = context[name]
if inspect.ismethod(callable): # return a method if callable is a
method
prober = types.MethodType(prober, callable.im_self,
callable.im_class)
return prober
>>def f(x, y=1, *a, **k): pass
....
>>get_f_locals = localsProber(f)
>>get_f_locals(3)
{'a': (), 'k': {}, 'x': 3, 'y': 1}
>>get_f_locals(3,4,5)
{'a': (5,), 'k': {}, 'x': 3, 'y': 4}
>>get_f_locals(3,q=-1)
{'a': (), 'k': {'q': -1}, 'x': 3, 'y': 1}
George

Jun 21 '07 #3
George Sakkis wrote:
On Jun 21, 4:42 pm, "bruno.desthuilli...@gmail.com"
<bruno.desthuilli...@gmail.comwrote:
>On Jun 21, 8:51 pm, George Sakkis <george.sak...@gmail.comwrote:
>>I wonder if there is a (preferably not too-hackish) solution to the
following introspection problem: given a callable and a number of
positional and/or keyword arguments, infer what would be the frame's
locals() right after the function is called....

Turns out it wasn't that hard after all; I came up with the following:
....
So, what should your code do about this:

def someFunction(a, b, c=43, d=14, f=12):
print locals()

import functools

a_funct = functools.partial(someFunction, d=13, c=5)
b_funct = functools.partial(a_funct, 14, d=12)
localsProber(b_funct)

My point is simply:
Introspection code is often written with a fixed idea of what other
programmers write. The others don't use introspection, the others
don't use higher order functions to build functions, ....

--Scott David Daniels
sc***********@acm.org
Jun 25 '07 #4
On Jun 24, 10:52 pm, Scott David Daniels <scott.dani...@acm.org>
wrote:
So, what should your code do about this:

def someFunction(a, b, c=43, d=14, f=12):
print locals()

import functools

a_funct = functools.partial(someFunction, d=13, c=5)
b_funct = functools.partial(a_funct, 14, d=12)
localsProber(b_funct)
Didn't get too far :)

Traceback (most recent call last):
File "locprobe.py", line 54, in <module>
localsProber(b_funct)
File "locprobe.py", line 9, in localsProber
args, varargs, varkw, defaults = inspect.getargspec(callable)
File "C:\Python25\lib\inspect.py", line 728, in getargspec
raise TypeError('arg is not a Python function')
TypeError: arg is not a Python function

My point is simply:
Introspection code is often written with a fixed idea of what other
programmers write. The others don't use introspection, the others
don't use higher order functions to build functions, ....
Fair enough, especially since not even the standard inspect module
handles functools.partial objects. Perhaps things will improve after
2.6 with PEP 362 (Function Signature Object) in place.

What you claim about introspection code though I think holds for code
in general. There are quite often edge cases which the programmer
doesn't anticipate or care to handle. A tool that covers X% of real-
world use cases for some large X and documents the known limitations
for the rest 100-X is fine with me (e.g. the current lambda).

George

Jun 25 '07 #5

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

Similar topics

2
by: Giles Brown | last post by:
I do not understand why the following code produces NameError: name 'FirstClass' is not defined when both a global and local dict are passed into exec, but not when only a global dict is passed...
15
by: Paul Paterson | last post by:
I am trying to find a way to mimic by-reference argument passing for immutables in Python. I need to do this because I am writing an automated VB to Python converter. Here's an example of the VB...
2
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
6
by: Harald Armin Massa | last post by:
I use locals() for conveniently "filling out" SQL-Statements: def updData(id, surename): sql="""update fisch set surename=%(surename)s where id=%(id)s""" cs.execute(sql, locals())
45
by: It's me | last post by:
I am new to the Python language. How do I do something like this: I know that a = 3 y = "a" print eval(y)
13
by: John Salerno | last post by:
This is something that occurred to me a while ago, and again I was thinking about it last night. I noticed how redundant it seems to type an expression like this: SomeType x = new SomeType(); ...
2
by: xml0x1a | last post by:
How do I use exec? Python 2.4.3 ---- from math import * G = 1 def d(): L = 1 exec "def f(x): return L + log(G) " in globals(), locals() f(1)
2
by: =?iso-8859-1?B?QW5kcuk=?= | last post by:
I want to give a user the possibility of "restarting" an interactive session, by removing all the objects defined by her since the beginning. The way I make this possible is by having a "function"...
6
by: John [H2O] | last post by:
I would like to write a function to write variables to a file and modify a few 'counters'. This is to replace multiple instances of identical code in a module I am writing. This is my approach:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...

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.