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

Optparse object containing generators: only seem to work if givenparticular names?

Here's a strange one for you:

I have a generator function which produces lists of numbers and takes options
which influence the output. The generator contains a loop, and to enable the
options to have a different value on each iteration, the options may
themselves be instances of the same generator, in the form of attributes of
an optparse object. In the body of the loop, the next() method is called on
each generator to get the new value each time.

This enables me to either:

- pass an option either a single value as and have it yielded repeatedly by a
dummy generator,

- or, by using the (arbitrarily chosen) word "CTRL:" after the option,
followed by another set of options - in quotes - suitable for the main
generator, to pass a changing value.

The problem: whether it works or not depends on what name is given to the
destination in parser.values()! Strange but true.

I haven't yet been able to figure out if there's any pattern to this, but
names that work include: "add", "A", "rand", and "updown". Some that don't
are "descend", "random", and "Z".

When it doesn't work, the error is:

TypeError: unsupported operand type(s) for +: 'int' and 'generator'

So apparently when given one of the "wrong" names, calling options.
[wrongname].next() yields another generator object, whereas with the "right"
names, it yields the expected value.

Below is a working "sandbox" version of the relevant part of the actual
program, but with a hard-coded value for the number list and only a single
option, --add, which either adds the number given next on the command line to
each element of the list, or, if followed by CTRL: '' " (that's a pair of
empty quotes) will sequentially do the same for each member of the list. (If
the option is repeated inside the quotes, the altered list will be used to
apply the addition, and so on.)

If you don't believe me (and I'm finding this hard to believe myself), try
some different names in the two inline-commented places (of course, both have
to be the same). Some will work, others won't.

I'm baffled, and hope someone here may be interested in figuring out why this
is happening.

Thanks,

John O'Hagan

Here's the code:

import sys
from optparse import OptionParser

def my_callback(option, opt_str, value, parser):

rargs = parser.rargs

if rargs[0] == "CTRL:" :
setattr(parser.values, option.dest+"_ctrl", rargs[1].split())
else:
value = abs(int(rargs[0]))
setattr(parser.values, option.dest, value)

def parse(option_list):

parser = OptionParser()

parser.add_option("--add", action="callback", callback=my_callback,
dest="add") ## The troublesome name!

(options, args) = parser.parse_args(option_list)
return options
def numerical_ctrl(generator):

for number_list in generator:
for number in number_list:
yield number

def dummy_ctrl(value):
while 1:
yield value

#This next bit should ideally be incorporated into the callback function above
#(later!)
#It converts the attributes of the "options" object to generators.

def iterizer( options ):

for opt in vars( options ) :

if "_ctrl" in opt:
ctrl_opts_list = getattr( options, opt )
setattr(options, opt, dummy_ctrl( getattr( options, opt ) ) )
opt = opt.replace( "_ctrl", "" )
ctrl_opts = parse( ctrl_opts_list )
ctrl_opts = iterizer( ctrl_opts )
generator = phrase_engine( ctrl_opts )
generator = numerical_ctrl( generator )
else:
generator = dummy_ctrl( getattr( options, opt ) )

setattr (options, opt , generator)

return options

#The number list generator:

def phrase_engine(options):

counter = 0
while counter < 10:

sequence = [1, 2, 3]

add = options.add.next() ##Here is the troublesome name again.

if add :
sequence = [ i + add for i in sequence ]

yield sequence

counter += 1

options = parse( sys.argv[ 1: ] )
options = iterizer(options)

for i in phrase_engine(options):
print i
Oct 31 '08 #1
0 1254

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

Similar topics

8
by: Hans-Joachim Widmaier | last post by:
I was really pleased when the Optik module found its way into the standard Python battery compartment, as it matched all my option parsing requirements. But, as always, there's really nothing that...
1
by: Eric O. Angell | last post by:
Say I have class Header: def __init__(self): self.foo = 0 # ... more fields and I have some commandline options that can specify better values for things in the header, such as foo. If I try...
2
by: Kenneth McDonald | last post by:
I'd like to propose a new PEP , for a standard library module that deals with files and file paths in an object oriented manner. I believe this module should be included as part of the standard...
1
by: Pupeno | last post by:
Hello, I am doing some extreme use of optparse, that is, extending it as explained on http://docs.python.org/lib/optparse-other-reasons-to-extend-optparse.html I have subclassed OptionParser and...
4
by: Mathias Waack | last post by:
We've integrated python into a legacy application. Everything works fine (of course because its python;). There's only one small problem: the application reads the commandline and consumes all...
1
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that...
0
by: Robert Kern | last post by:
Jeff Keasler wrote: If you code it up with unit tests and documentation, it has a good chance. But in the meantime, you can tell optparse to stop processing options using the standard "--"...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
1
by: John O'Hagan | last post by:
Hello, I've recently found it convenient to do something like this: options = optparse_function(sys.argv) ##print options => ##{option_one:4, option_two:, option_three:'/home/files'} ...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...

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.