On 13/04/2006 12:26 PM, James Stroud wrote:
> John Machin wrote:
>> On 13/04/2006 11:23 AM, James Stroud wrote:
>
>>> opt_map = {'m': 'Queue Manager', 's': 'Server', 'p': 'Port',
>>> 'o': 'Object', 'k': 'Key', 't': 'To',
>>> 'c': 'Check', 'd': 'Report', 'q': 'Display}
>>>
>>
>> 'Queue Manager' is not suitable for later use as an attribute name.
>
> Who said anything about attribute names? I did it this way to show the
> OP that not every value has to be "select variables which would
> eventually be included in a class object".
Sorry, I don't understand that sentence.
> Using a dict would be far
> more attractive than a bunch of "setattr" & "getattr"s later.
Who said anything about a bunch of *attrs later?
Instead of
settings[opt_map[flag]] = option
you'd have
setattr(anobj, opt_map[flag], option)
with the __init__ for the class setting up the default values.
And no getattrs, you'd use the names like qmgr and port as per the OP:
anobj.qmgr, anobj.port, etc ...
>
>>> afile = open("filename")
>>>
>>> settings = {}
>>> for aline in afile:
>>> splitline = aline.split()
>>> flags, options = splitline[::2], splitline[1::2]
>>> flags = [f[1] for f in flags] # get rid of pesky "-"s
>>
>>
>> Actually that's getting rid of the first character irrespective of
>> whether it's "-" or not -- except when there's only one character in
>> which case it will die in a hole.
>
> Who said the "-" was optional?
Nobody. Who said the user data was going to be syntactically correct?
>
>>> for flag, option in zip(flags, options):
>>> settings[opt_map(flag)] = option
>>> print "%s = %s" % (opt_map(flag), option)
>>
>>
>> opt_map is a dict; should be opt_map[flag] in above two lines
>
> Typos.
>
>>> afile.close()
>>>
>>
>> Like Peter said, use optparse -- it handles the no-argument flags, has
>> error detection, defaults, can be told the type of the flag, already
>> returns the goodies as attributes of an object, ...
>
> Peter's post was up when I responded, but it does not give the OP any
> ideas about how to write better python code.
Yes it does. It gives the OP the idea that if there's a Python standard
module that does the job, the best Python code that the OP could write
would be calls to that module.
> Note the 4 page if...elif
> construct.
I did. I read *all* of it.
> optparse might be logical for vet pythonistas, but if someone
> is writing code like to OP, it might be better to give him some coding
> hints at the expense of sophistication.
The "sophistication" of optparse appears to match what the OP appears to
want to do; IMO preferable to the sophistry of something like
flags, options = splitline[::2], splitline[1::2]
which is sure to cause the OP some headscratching and needs to be thrown
away immediately he starts to consider (a) variable number of parameters
(b) error detection.
--
http://mail.python.org/mailman/listinfo/python-list