473,546 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pythonic equivalent of upvar?

Dear Greater Py,

<motivation note="reading this bit is optional">
I am writing a command-line reader for python.

I'm trying to write something with the same brevity
as perl's one-liner

eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ /^(\w+)=(.*)/ && shift;

and with similar functionality. I've decided I don't like
getopt, because it seems to require me to write pages and pages
of elif's as I add new arguments. It slows me down, whereas the
perlism above liberates.

My solution is a twenty-line python chunk equivalent to the perl one-liner.
(Twenty lines because, to process a (name, value) pair, I have to find the
current type of the variable "name" before setting "name" to righttype("valu e").

I'm happy with this 20-line chunk and wish to re-use it in many python programs.
</motivation>

<question>
What is the pythonic way to embed a 20-line chunk of code into a function?
I'd love to define these 20 lines as a module, and reuse the module over and over.
but this chunk of code needs to have access to
the local variables of main, whatever they are called.

In tcl, IIRC, the command "upvar" allows one function to get access to its
parent function's local variables.

Is there a pythonic way to tell a function "you are allowed to see all your
parent's variables?" Or, to tell a chunk of code, "you are just a chunk of
code, not really a function"?
</question>

Thanks very much

David

PS -- example below illustrates the chunk of code, in case anyone is interested.

#!/usr/bin/env python
"""
This program commandline.py illustrates a command-line reader (David MacKay, license: GPL)
that works a little like perl's
eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ /^(\w+)=(.*)/ && shift;
usage: (all arguments are optional)
commandline.py -bits 5 -decode 1 -file pimple -N 10000
"""
import sys
def usage(name):
print "Usage: %s -variableName value" % name
sys.exit()

def main():
## Define DEFAULTS that can be overridden on the command line
decode=0 ## are we decoding?
verbose=0 ## verbose output?
bits=7 ## how big are the blocks?
N = 10000 ## What is the file length?
file="blah" ## file name string
## End defaults

## Command-line reader: Reads pairs of the form
## " -variableName value "
## and sets variableName=va lue. Gives error if this syntax is violated.
while ( len(sys.argv) > 1 ):
if ( sys.argv[1][0] == "-" ):
name = sys.argv.pop(1)
name = name[1:len(name)]
if( len(sys.argv) <= 1 ):
print >> sys.stderr, "could not get value for name ", name
usage(sys.argv[0])
else:
value = sys.argv.pop(1)
# here, we should assert that this variable exists!
command = "ntype = type(%s)" % (name) # find type of this variable
exec command
# convert value to the right type
command = "%s = ntype(%s) # %s" % ( name,`value`, str(ntype) )
if verbose:
print >> sys.stderr , "setting value:", command
exec command
else:
usage(sys.argv[0])
## End of command-line reader

## defaults that cannot be overridden on command line
securityLevel = 1
## end defaults

## Main program starts here

print >> sys.stderr, " N =",N," bits =",bits, \
" file = ",file, " decode = ", decode

if __name__ == '__main__': main()

--
--
David J.C. MacKay ma****@aims.ac. za 787 9336
http://www.aims.ac.za/~mackay/
Dec 20 '05 #1
3 3125
David MacKay wrote:
I'm*trying*to*w rite*something* with*the*same*b revity
as perl's one-liner

eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ ^(\w+)=(.*) && shift;


import optparse

parser = optparse.Option Parser("See the error of your ways and use
optparse")
parser.add_opti on("--decode", action="store_t rue")
parser.add_opti on("--verbose", action="store_t rue")
parser.add_opti on("--bits", type="int", default=7)
parser.add_opti on("-N", type="int", default=10000)
parser.add_opti on("--file", default="blah")

options, args = parser.parse_ar gs()
if args:
parser.error("u nexpected positional argument(s)")

# accessing option values
print options.bits

Peter

Dec 20 '05 #2
On Tue, 20 Dec 2005 16:10:30 +0200, ma****@aims.ac. za (David MacKay) wrote:
Dear Greater Py,

<motivation note="reading this bit is optional">
I am writing a command-line reader for python.

I'm trying to write something with the same brevity
as perl's one-liner

eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ /^(\w+)=(.*)/ && shift;

and with similar functionality. I've decided I don't like
getopt, because it seems to require me to write pages and pages
of elif's as I add new arguments. It slows me down, whereas the
perlism above liberates.

My solution is a twenty-line python chunk equivalent to the perl one-liner.
(Twenty lines because, to process a (name, value) pair, I have to find the
current type of the variable "name" before setting "name" to righttype("valu e").

I'm happy with this 20-line chunk and wish to re-use it in many python programs.
</motivation>

<question>
What is the pythonic way to embed a 20-line chunk of code into a function?
I'd love to define these 20 lines as a module, and reuse the module over and over.
but this chunk of code needs to have access to
the local variables of main, whatever they are called.

In tcl, IIRC, the command "upvar" allows one function to get access to its
parent function's local variables.

Is there a pythonic way to tell a function "you are allowed to see all your
parent's variables?" Or, to tell a chunk of code, "you are just a chunk of
code, not really a function"?
</question>
You can see them, but you can't rebind them without nasty hacks.
I would suggest just instantiating an object that initializes the way
you want to contain the values you pre-specify, and optionally get
overridden by command line info as you specify. E.g., a quick hack (not
tested beyond what you see ;-)

----< clvalues.py >-----------------------------------------------------
class CLValues(dict):
"""
A dict whose initialization values are overridden by
-name value pairs in the overrides list, by default taken from
command line args sys.argv[1:], but a list may be passed.
Existing values get overridden by cmd line values converted
to the same type. New values are assumed str type. Existing
values may be specified non-overridable by prefixing an underscore,
which is removed after cmd line args have been processed.
Since keys are valid names, access is also provided via attribute syntax.
"""
def __init__(self, overrides=None, *args, **kw):
dict.__init__(s elf, *args, **kw)
if overrides is None: overrides = __import__('sys ').argv[1:]
while overrides:
name = overrides.pop(0 )
if not name.startswith ('-') or not name[1:]:
raise ValueError, "Names must be non-null and prefixed with '-', unlike %r" % name
name = name[1:]
if '_'+name in self or name.startswith ('_') and name in self:
raise ValueError, "%r may not be overridden" % name
if not overrides: raise ValueError, 'No value following %r'% '-'+name
value = overrides.pop(0 )
self[name] = type(self.get(n ame, ''))(value) # default str type if not pre-existing
for k,v in self.items():
if k.startswith('_ '): # make plain names for non-overridables
self[k[1:]] = v
del self[k]
def __getattr__(sel f, name): return self[name] # provide key access as attributes

def test():
clv = CLValues(
decode=0,
verbose=0,
bits=7,
N = 10000,
file="blah",
_securityLevel = 3)
for name, value in clv.items():
print '%15s: %r' %(name, value)
print 'N accessed as clv.N => %r' % clv.N

if __name__ == '__main__':
test()
------------------------------------------------------------------------

Running it to run the test:

[ 9:54] C:\pywk\ut>py24 clvalues.py -bits 8 -file other\path\and\ file
decode: 0
securityLevel: 3
verbose: 0
file: 'other\\path\\a nd\\file'
bits: 8
N: 10000
N accessed as clv.N => 10000

[ 9:54] C:\pywk\ut>py24 clvalues.py -securityLevel 0
Traceback (most recent call last):
File "clvalues.p y", line 44, in ?
test()
File "clvalues.p y", line 38, in test
_securityLevel = 3)
File "clvalues.p y", line 21, in __init__
raise ValueError, "%r may not be overridden" % name
ValueError: 'securityLevel' may not be overridden

Quoting command line arg to make a single arg with embedded spaces:

[ 9:54] C:\pywk\ut>py24 clvalues.py -added "should be string"
decode: 0
securityLevel: 3
added: 'should be string'
verbose: 0
file: 'blah'
bits: 7
N: 10000
N accessed as clv.N => 10000

Thanks very much
De nada.
David

PS -- example below illustrates the chunk of code, in case anyone is interested.

<snip code, from which I tried to translate the functionality>

Usage in a program would go something like
from clvalues import CLValues
clv = CLValues(
# ... like test above
)
# ...
# use values spelled clv.name or clv['name'] or clv.get('name') etc
#

Regards,
Bengt Richter
Dec 20 '05 #3
ma****@aims.ac. za (David MacKay) writes:
«
<motivation note="reading this bit is optional">
I am writing a command-line reader for python.

I'm trying to write something with the same brevity
as perl's one-liner

eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ /^(\w+)=(.*)/ && shift;

and with similar functionality.
Why? Do you like to make the security hole in your code hard to find?
<question>
What is the pythonic way to embed a 20-line chunk of code into a function?
I'd love to define these 20 lines as a module, and reuse the module over and over.
but this chunk of code needs to have access to
the local variables of main, whatever they are called.


You can't do that. You don't want to do that, because it will cause
user typos to make your code break in strange and mysterious ways. Put
the variables in a dictionary, indexed by variable name.

Better yet, do what Peter suggests, and learn to use optparse.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 20 '05 #4

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

Similar topics

9
13265
by: Tom Evans | last post by:
My basic question: If I have a specific interface which I know is going to be implemented by a number of classes, but there is no implementation commonality between them, what is the preferred form for this in Python? In a staticly typed language like c++ or java, I'd describe the interface first, then create the classes eithered derived...
1
1452
by: asdf sdf | last post by:
i need some advice. i'm a back end programmer historically, but have been exploring python for webapps and enjoying it. i need to build some simple Win client-server or standalone apps. the result needs to look professional and attractive, and i need something i can get working fairly quickly with a modest learning curve. i'm looking...
7
1845
by: jelle | last post by:
I now some hostility to functional programming is flaming up now and then; still could someone suggest me a pythonic equivalent for Mathematica's FixedPoint function? For those not familiar with Mathematica: FixedPoint starts with expr, then applies f repeatedly until the result no longer changes. thanks, jelle.
11
5028
by: Charles Krug | last post by:
I've a function that needs to maintain an ordered sequence between calls. In C or C++, I'd declare the pointer (or collection object) static at the function scope. What's the Pythonic way to do this? Is there a better solution than putting the sequence at module scope?
7
2543
by: am_ggh | last post by:
Is there a PHP equivalent of TCL's "upvar" ? I will appreciate any insights. Andy
3
1535
by: andrew.fabbro | last post by:
I'm working on an app that will be deployed on several different servers. In each case, I'll want to change some config info (database name, paths, etc.) In perl, I would have done something like this: Package Config; <some exporting mechanics> $dbname = "somename"; etc.
4
1787
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design software in a more "Pythonic" way. My question is, should we as python developers be trying to write code that follows more of a python standard...
3
1302
by: jnair | last post by:
My Tead Lead my object counter code seen below is not pythonic class E(object): _count = 0 def __init__(self): E._count += 1 count = property(lambda self: E._count ) def test(): if __name__ == "__main__":
25
4664
by: Alex Popescu | last post by:
Hi all! I am pretty sure this has been asked a couple of times, but I don't seem to find it on the archives (Google seems to have a couple of problems lately). I am wondering what is the most pythonic way of dealing with missing keys and default values. According to my readings one can take the following approaches:
0
7507
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7435
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7698
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7947
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7461
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5361
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3472
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1922
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.