Object default value

2005-09-20 Thread ago
Is it possible to have a default value associated python objects? I.e.
to flag an attribute in such a way that the assignment operator for the
object returns the default attribute instead of the object itself, but
calls to other object attributes are properly resolved? (I don't think
so, but I am not sure)

Example:

class obj(object):
 x=1 #assume x is somehow made into a default value
 y=2

Ideally this should be the result:

myobj=obj()
print myobj #-> 1
print myobj.y #-> 2
x=myobj
print x #-> 1
print type(x) #int

Those are my half-working solutions so far:

1) using __get__ descriptor within the class,

def __get__(self,parent,parenttype): return self.x

then

print myobj #works
print myobj.y #does not work! equivalent to: print 1.y

2) Use a __call__ method without a __get__ descriptor.

def __call__(self): return self.x

then:

print myobj() #works, but not the same as: print myobj
print myobj.y #works

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread Larry Bates
The prints can be done by defining an __str__ method on the
class, but I don't think you will get the type(obj) to work
the way you want.

class obj(object):
__default=1
y=2

def __str__(self):
return str(self.__default)

myobj=obj()
print "myobj=", myobj
print "myobj.y=", myobj.y

>>> myobj= 1
>>> myobj.y= 2

ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)
> 
> Example:
> 
> class obj(object):
>  x=1 #assume x is somehow made into a default value
>  y=2
> 
> Ideally this should be the result:
> 
> myobj=obj()
> print myobj #-> 1
> print myobj.y #-> 2
> x=myobj
> print x #-> 1
> print type(x) #int
> 
> Those are my half-working solutions so far:
> 
> 1) using __get__ descriptor within the class,
> 
> def __get__(self,parent,parenttype): return self.x
> 
> then
> 
> print myobj #works
> print myobj.y #does not work! equivalent to: print 1.y
> 
> 2) Use a __call__ method without a __get__ descriptor.
> 
> def __call__(self): return self.x
> 
> then:
> 
> print myobj() #works, but not the same as: print myobj
> print myobj.y #works
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
The print statement was only for illustrative purposes, when calling
varx=myobj I need to receive obj.x as opposed to the instance of obj,
but I also need to call vary=myobj.y. Something like that exists for
com objects/VB, for instance an excel range object uses value as the
default attribute, so that you can write

set rng=range(...); 
x=rng
y=rng.value
'x==y
z=rng.attributeXYZ

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread James Stroud
I think you want to overload the assignment operator here. I'm not sure that 
is allowed in python (I've never seen it done). You can overload the 
equality, lt, gt, le, ge operators (==, <, ...) such that

class Thing:
  x = 5
  def __str__(self):
return str(self.x)
  def __eq__(self, other):
  if hasattr(other, 'x'):
  return self.x == other.x
  else:
return self.x == other

py> athing = Thing()
py> athing.x
5
py> bob = athing.x
py> athing == bob  # having overlaoded equality for athing
True
py> athing is bob  # not the same object
False

But I don't think assignment overloading is allowed in python:

py> athing = Thing()
py> print athing  # having overloaded __str__()
5
py> bob = athing
py> type(bob) # will not be an int ==> python language constraint


James

On Tuesday 20 September 2005 13:05, ago wrote:
> The print statement was only for illustrative purposes, when calling
> varx=myobj I need to receive obj.x as opposed to the instance of obj,
> but I also need to call vary=myobj.y. Something like that exists for
> com objects/VB, for instance an excel range object uses value as the
> default attribute, so that you can write
>
> set rng=range(...);
> x=rng
> y=rng.value
> 'x==y
> z=rng.attributeXYZ

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread James Stroud
See this recent clpy thread:

http://www.thescripts.com/forum/thread19253.html

On Tuesday 20 September 2005 13:05, ago wrote:
> The print statement was only for illustrative purposes, when calling
> varx=myobj I need to receive obj.x as opposed to the instance of obj,
> but I also need to call vary=myobj.y. Something like that exists for
> com objects/VB, for instance an excel range object uses value as the
> default attribute, so that you can write
>
> set rng=range(...);
> x=rng
> y=rng.value
> 'x==y
> z=rng.attributeXYZ

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread Paul McGuire
> I think you want to overload the assignment operator here. I'm not sure
that
> is allowed in python (I've never seen it done).

You can't because assignment is not an operator in Python.

Is it safe to assume that the OP's next question will be how to invoke
functions without the ()'s?  To save you the trouble, then answer is 'no'.

Python is simple, VB is simple, but Python is not VB.

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread Diez B. Roggisch
ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)

You're descriptions aren't very clear. Maybe you can put that in a 
greater context - what do you want to achieve?

And the assignment-operator isn't overloadable - that is for sure!

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
I am trying to write a generic DataAttribute class in order to simplify
access to object attributes and attached attribute-metadata for end
users with little programming experience.

Requirement 1: accessing the "default" value should be easy (using
assignment operator, via descriptors like __get__ and __set__).

Requirement 2: access to the attribute-metadata should also be as
intuitive as possible.

Requirement 3: possibly the DataAttribute should also be callable, to
return for instance, an history of its values.

class DataAttribute(object):
 value=1 #default
 old=2
 

class Obj(object): attr=DataAttribute()

#From end user prospective, ideally:
obj=Obj()
x = obj.attr #x=1
xold = obj.attr.old #xold=2
obj.attr = 3 #obj.attr.value=3
xold = obj.attr.old #xold=1
xhistory = obj.attr(startdate, enddate) #xhistory = [[date1,
4],[date2,5],[date3,6]]
xtimestmap = x.attr.timestamp
print obj.attr == obj.attr.value #True

If I use __get__ then I cannot access the metadata.

I could create a separate Obj attribute for each metadata item, but
then I would litter the Obj namespace (typical object will have several
attributes each with lots of metadata) and potentially create name
conflicts. Not to mention that DataAttributes should be
attached/deleted on the fly and if each attribute becames a set of
attributes this operation is complex (metclasses?).

If I use __call__ + __set__ but then I am introducing an asymmetry:

x = obj.attr()
obj.attr = 2

I could use getters and setters but that is not really convenient nor
intuitive

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
> Is it safe to assume that the OP's next question will be how to invoke
functions without the ()'s?  To save you the trouble, then answer is
'no'.

You probably nailed it, thanks for the answer. I suspected that was the
case. I think I'll use __call__ + __set__

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
In fact even IF I could get a default value to work as mentioned, then
I would be creating potential name conflicts between the
DataAttribute.DefaultValue and the other metadata. I.e. when calling
obj.attr.x I could refer to DataAttribute.x or DataAttribute.value.x.
It's a no go.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread Scott David Daniels
James Stroud wrote:
> I think you want to overload the assignment operator here. I'm not sure that 
> is allowed in python (I've never seen it done)
> But I don't think assignment overloading is allowed in python:

Exactly correct.  Assignment is an operation on a namespace using a new
value, and does not involve the former value.  Something similar to
assignment overloading is possible with properties, but you need to be
using object attributes, not names in a module (or function locals).

class SomeDemo(object):
 def _read_foo(self):
 print 'Reading foo'
 return self._foo

 def _write_foo(self, value):
 print 'Writing foo as %r' % value
 return self._foo

 def _del_foo(self):
 print 'Deleting foo'
 del self._foo

 foo = property(_read_foo, _write_foo, _del_foo)

obj = SomeDemo()
obj.foo = 123
obj.foo += 1
del obj.foo

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-21 Thread Fredrik Lundh
"ago" <[EMAIL PROTECTED]> wrote:

> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)

No.

You can overload certain methods to make an object behave like one
of its attributes in certain contexts (e.g. comparisions, math operations,
conversions), but you cannot do it for all operations.

Especially not the "assignment operator", since there is no such thing in
Python.  (assignment is a statement, and it's an operation on the target
namespace, not the source object).

(As always, Python works better if you use it to write Python programs)





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-21 Thread James Stroud
On Tuesday 20 September 2005 12:31, ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)

I was thinking about this last night and it seemed an interesting problem. I 
thought you might want to change the way you look at it, using the python 
equivalent to type casting (maybe its called "coercing", sorry for my poor 
command of python vocabulary). I have overridden __int__ and __float__ for 
this example. You might want to look into __coerce__. This should have the 
behavior you desire while having the explicit syntax expected of good python 
code.

Inheriting from list allows you to use a stack-like behavior you described in 
a previous email. You can further modify __getattribute__, __setattribute__, 
__delattribute__, etc. Overriding __iter__ gives you the history in "correct" 
order, but may begin to embark on a non-intuitive interface--you be the 
judge. I think this is about as close as you can get in python to what you 
are thinking (don't know the oldest python version this is backwards 
compatible with):


py> class Thing(list):
...def __init__(self, start_value):
... list.__init__(self)
... self.append(start_value)
...def __setattr__(self, anattr, aval):
...  if (anattr == 'top'):
...self.append(aval)
...  else:
...list.__setattr__(self, anattr, aval)
...def __getattr__(self, anattr):
...  if (anattr == 'top'):
...return self[-1]
...  elif (anattr == 'old'):
...try:
...  return self[-2]
...except IndexError:
...  raise NameError, "No old value yet"
...  else:
...list.__getattr__(self, anattr)
...def __iter__(self):
...  return list.__iter__(self[::-1])
...def __int__(self):
...  return int(self.top)
...def __float__(self):
...  return float(self.top)
...def __str__(self):
...  return str(self.top)
...
py> athing = Thing(5)# should init with a reasonable value
py> athing.top   # __getattr__
5
py> int(athing)  # __int__
5
py> print athing # __str__
5
py> float(athing)# __float__
5.0
py> athing.top = 4   # __setattr__
py> print athing
4
py> athing.old   # __getattr__
5
py> athing.top = 42  # __setattr__
py> [x for x in athing]  # __iter__
[42, 4, 5]
py> y = float(athing)# closest you can get to assignment overloading
py> print y  # y is a float
42.0
py> athing # Thing inherits from list, so you get list.__repr__() here
[5, 4, 42]



Here it is without the prompts:

class Thing(list):
   def __init__(self, start_value):
list.__init__(self)
self.append(start_value)
   def __setattr__(self, anattr, aval):
 if (anattr == 'top'):
   self.append(aval)
 else:
   list.__setattr__(self, anattr, aval)
   def __getattr__(self, anattr):
 if (anattr == 'top'):
   return self[-1]
 elif (anattr == 'old'):
   try:
 return self[-2]
   except IndexError:
 raise NameError, "No old value yet"
 else:
   list.__getattr__(self, anattr)
   def __iter__(self):
 return list.__iter__(self[::-1])
   def __int__(self):
 return int(self.top)
   def __float__(self):
 return float(self.top)
   def __str__(self):
 return str(self.top)

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-22 Thread Bengt Richter
On 20 Sep 2005 12:31:19 -0700, "ago" <[EMAIL PROTECTED]> wrote:

>Is it possible to have a default value associated python objects? I.e.
>to flag an attribute in such a way that the assignment operator for the
>object returns the default attribute instead of the object itself, but
>calls to other object attributes are properly resolved? (I don't think
>so, but I am not sure)
>
>Example:
>
>class obj(object):
> x=1 #assume x is somehow made into a default value
> y=2
>
>Ideally this should be the result:
>
>myobj=obj()
normal

>print myobj #-> 1
expression myobj interpreted as myobj.x?

>print myobj.y #-> 2
normal

>x=myobj
normal, because expression myobj in this context of immediate assignment does 
not mean myobj.x?

>print x #-> 1
expression x is the same as expression myobj, which is intrpreted as myobj.x 
(alias x.x) if not assigned?

>print type(x) #int
ditto

>
If you wanted to have this effect inside a function, you could write a 
byte-code-munging
decorator to evaluate selected_name as selected_name.selected_attr except where
assigning to an alias name is all that a statement does, as in x = myobj.

But what if you actually wanted to pass the object per se somewhere, or return 
it from
a function? Maybe you could have the expression myobj.x mean the normal myobj, 
and vice
versa in a kind of terrible symmetry ;-)

Then usage might be something like
@agostino_effect(myobj='x') # eval myobj as myobj.x
def foo():
myobj=obj()
print myobj #-> 1
print myobj.y #-> 2
x = myobj
print x #-> 1
return x, myobj, x.y, myobj.x # with .x having "symmetrically-other" effect 
;-)

xval, myobjval, x_dot_y_val, myobj_per_se = foo() # assignment from 
function is not interfered with
myobj_per_se.y #->2
myobj_per_se #-> 1
myobj_val.y -> AttributeError: 'int' object has no attribute 'y'

I'm not suggesting this is a good way to go forward, I am just playing with the 
feasibility of
doing what you want, even if it's not good for you ;-) I suspect there is a 
better way, but
it wouldn't be that hard to do the above, as you can see from the code of foo
that the agostino_effect decorator would be modifying:

 >>> def foo():
 ... myobj=obj()
 ... print myobj #-> 1
 ... print myobj.y #-> 2
 ... x = myobj
 ... print x #-> 1
 ... return x, myobj, x.y, myobj.x # with .x having "symmetrically-other" 
effect ;-)
 ...
 >>> import dis
 >>> dis.dis(foo)
   2   0 LOAD_GLOBAL  0 (obj)
   3 CALL_FUNCTION0
   6 STORE_FAST   0 (myobj)

   3   9 LOAD_FAST0 (myobj)
Here you'd notice that the next instruction was not STORE_FAST
so you'd insert a
 LOAD_ATTR1 (x)
similar to the .y access below

  12 PRINT_ITEM
  13 PRINT_NEWLINE

   4  14 LOAD_FAST0 (myobj)
  17 LOAD_ATTR2 (y)
Here you'd notice the above wasn't LOAD_ATTR (x) (which you'd otherwise have to 
remove for object-per-se)

  20 PRINT_ITEM
  21 PRINT_NEWLINE

   5  22 LOAD_FAST0 (myobj)
  25 STORE_FAST   1 (x)
This you notice is an immediate assignment and you leave it alone, and note the 
alias

   6  28 LOAD_FAST1 (x)
Here you notice the alias and insert
 LOAD_ATTR1 (x)
as before with myobj

  31 PRINT_ITEM
  32 PRINT_NEWLINE

   7  33 LOAD_FAST1 (x)
insert
 LOAD_ATTR1 (x)
again
  36 LOAD_FAST0 (myobj)
insert
 LOAD_ATTR1 (x)
again
  39 LOAD_FAST1 (x)
  42 LOAD_ATTR2 (y)
other attribute, no change to above byte code
  45 LOAD_FAST0 (myobj)
  48 LOAD_ATTR3 (x)
anti-attribute, remove above byte code
  51 BUILD_TUPLE  4
  54 RETURN_VALUE

You might want to do the same for LOAD_GLOBAL/STORE_GLOBAL, and
STORE_DEREF/LOAD_DEREF, I don't know. But it wouldn't be a big deal
to get a hack working. Thorough testing is another matter,
not to mention justifying it ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-22 Thread Reinhold Birkenfeld
ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)

Python is not Visual Basic.

In Visual Basic, objects could have a default property which was set when
the object variable was assigned to, but that was only possible because
object variables had to be set with "Set", not "Let".

Reinhold
-- 
http://mail.python.org/mailman/listinfo/python-list


default value in a list

2005-01-21 Thread TB
Hi,

Is there an elegant way to assign to a list from a list of unknown
size?  For example, how could you do something like:

>>>  a, b, c = (line.split(':'))
if line could have less than three fields?

Thanks,
TB

-- 
http://mail.python.org/mailman/listinfo/python-list


Default value for Listbox (Tkinter)

2005-02-24 Thread Harlin Seritt
Whenever I set up something similar:

vals = ['1', '2','3']
for v in vals:
   listbox.inset(END, v)

I notice that when this listbox is displayed, there is never a default
value. How can I make sure that one of the indices is selected by
default?

Thanks,

Harlin

-- 
http://mail.python.org/mailman/listinfo/python-list


default value for list access?

2005-02-27 Thread Bo Peng
Dear list,
My program needs to do calculation based on a giving data structure 
(like a sparse matrix) with  lots of missing values (invalid 
indices/keys of lists/dictionaries).

The programing is difficult in that I have to use a try...except block 
for every item access. I have written a function

def getItem(item, idx, default):
  try:
return item[idx]
  except:
return default
Then I will have to write a[1]['a'][4] as
getItem( getItem( getItem(a,1,{}), 'a', []), 4, 0)
Is there any way to automatically return 0 when any exception is raised 
for such data acceses? (automatic wrapping a[...] as
 try:
   a[...]
 except:
   0
)

Many thanks in advance.
Bo
--
http://mail.python.org/mailman/listinfo/python-list


Providing 'default' value with raw_input()?

2005-12-22 Thread planetthoughtful
Hi All,

As always, my posts come with a 'Warning: Newbie lies ahead!'
disclaimer...

I'm wondering if it's possible, using raw_input(), to provide a
'default' value with the prompt?

I would like to include the ability to edit an existing value (drawn
from an SQLite table) using a DOS console Python app, but my gut
feeling from reading what I can find about raw_input() is that it only
allows you to provide a prompt, not a default value as well.

If anyone can give me any advice on how I might achieve this, I would
be immensely appreciative!

Many thanks and much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Larry Bates
What do you want put into the "missing" variables?
I'll assume None.  Something like following
works:
values=line.split(':')
try: a=values.pop(0)
except IndexError: a=None
try: b=values.pop(0)
except IndexError: b=None
try: c=values.pop(0)
except IndexError: c=None
Larry Bates

TB wrote:
Hi,
Is there an elegant way to assign to a list from a list of unknown
size?  For example, how could you do something like:

a, b, c = (line.split(':'))
if line could have less than three fields?
Thanks,
TB
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Steve Holden
TB wrote:
Hi,
Is there an elegant way to assign to a list from a list of unknown
size?  For example, how could you do something like:

a, b, c = (line.split(':'))
if line could have less than three fields?
l = line.split(':')
l is a list, whose length will be one more than the number of colons in 
the line.

You can access the elements of the list using a[0], a[2], and so on. For 
example:

 >>> line = "This:is:a:sample:line"
 >>> l = line.split(':')
 >>> l
['This', 'is', 'a', 'sample', 'line']
 >>> for w in l:
 ...   print w
 ...
This
is
a
sample
line
 >>> len(l)
5
 >>>
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Paul McGuire
"TB" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> Is there an elegant way to assign to a list from a list of unknown
> size?  For example, how could you do something like:
>
> >>>  a, b, c = (line.split(':'))
> if line could have less than three fields?
>
> Thanks,
> TB
>
I asked a very similar question a few weeks ago, and from the various
suggestions, I came up with this:

line = ":BBB"
expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
a,b,c = expand( line.split(":"), "", 3 )
print a
print b
print c

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Steven Bethard
Paul McGuire wrote:
expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
Or if you're afraid of lambda like me:
def expand(lst,default,minlen):return (lst + [default]*minlen)[0:minlen]
or perhaps more readably:
def expand(lst, default, minlen):
return (lst + [default]*minlen)[0:minlen]
No need for an anonymous function when you're naming it. ;)
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Jeff Shannon
TB wrote:
Hi,
Is there an elegant way to assign to a list from a list of unknown
size?  For example, how could you do something like:

a, b, c = (line.split(':'))
if line could have less than three fields?
(Note that you're actually assigning to a group of local variables, 
via tuple unpacking, not assigning to a list...)

One could also do something like this:
>>> l = "a:b:c".split(':')
>>> a, b, c, d, e = l + ([None] * (5 - len(l)))
>>> print (a, b, c, d, e)
('a', 'b', 'c', None, None)
>>>
Personally, though, I can't help but think that, if you're not certain 
how many fields are in a string, then splitting it into independent 
variables (rather than, say, a list or dict) *cannot* be an elegant 
solution.  If the fields deserve independent names, then they must 
have a definite (and distinct) meaning; if they have a distinct 
meaning (as opposed to being a series of similar items, in which case 
you should keep them in a list), then which field is it that's 
missing?  Are you sure it's *always* the last fields?  This feels to 
me like the wrong solution to any problem.

Hm, speaking of fields makes me think of classes.
>>> class LineObj:
... def __init__(self, a=None, b=None, c=None, d=None, e=None):
... self.a = a
... self.b = b
... self.c = c
... self.d = d
... self.e = e
...
>>> l = "a:b:c".split(':')
>>> o = LineObj(*l)
>>> o.__dict__
{'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None}
>>>
This is a bit more likely to be meaningful, in that there's almost 
certainly some logical connection between the fields of the line 
you're splitting and keeping them as a class demonstrates that 
connection, but it still seems a bit smelly to me.

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-21 Thread Fredrik Lundh
Paul McGuire wrote:

> I asked a very similar question a few weeks ago, and from the various
> suggestions, I came up with this:
>
> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]

I wouldn't trust whoever suggested that.  if you want a function, use a 
function:

def expand(seq, default, minlen):
return (seq + [default]*minlen)[:minlen]

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Alex Martelli
TB <[EMAIL PROTECTED]> wrote:

> Is there an elegant way to assign to a list from a list of unknown
> size?  For example, how could you do something like:
> 
> >>>  a, b, c = (line.split(':'))
> if line could have less than three fields?

import itertools as it

a, b, c = it.islice(
  it.chain(
  line.split(':'), 
  it.repeat(some_default),
  ), 
  3)

I find itertools-based solutions to be generally quite elegant. 

This one assumes you want to assign some_default to variables in the LHS
target beyond the length of the RHS list.  If what you want is to repeat
the RHS list over and over instead, this simplifies the first argument
of islice:

a, b, c = it.islice(it.cycle(line.split(':')), 3)

Of course, you can always choose to write your own generator instead of
building it up with itertools.  itertools solutions tend to be faster,
and I think it's good to get familiar with that precious modules, but
without such familiarity many readers may find a specially coded
generator easier to follow.  E.g.:

def pad_with_default(N, iterable, default=None):
it = iter(iterable)
for x in it:
if N<=0: break
yield x
N -= 1
while N>0:
yield default
N -= 1

a, b, c = pad_with_default(3, line.split(':'))


The itertools-based solution hinges on a higher level of abstraction,
glueing and tweaking iterators as "atoms"; the innards of a custom coded
generator tend to be programmed at a lower level of abstraction,
reasoning in item-by-item mode.  There are pluses and minuses to each
approach; I think in the long range higher abstraction pays off, so it's
worth the investment to train yourself to use itertools.


In the Python Cookbook new 2nd edition, due out in a couple months,
we've added a whole new chapter about iterators and generators, since
it's such a major subfield in today's Python (as evidenced by the wealth
of recipes submitted to Activestate's online cookbook sites on the
subject).  A couple of recipes have do with multiple unpacking
assignment -- one of them, in particular, is an evil hack which peers
into the caller's bytecode to find out how many items are on the LHS, so
you don't have to pass that '3' explicitly.  I guess that might be
considered "elegant", for suitably contorted meanings of "elegant"...
it's on the site, too, but I don't have the URL at hand.  It's
instructive, anyway, but I wouldn't suggest actually using it in any
kind of production code...


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Peter Otten
Paul McGuire wrote:

>> Is there an elegant way to assign to a list from a list of unknown
>> size?  For example, how could you do something like:
>>
>> >>>  a, b, c = (line.split(':'))
>> if line could have less than three fields?

> I asked a very similar question a few weeks ago, and from the various
> suggestions, I came up with this:
> 
> line = ":BBB"
> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
> a,b,c = expand( line.split(":"), "", 3 )

Here is an expand() variant that is not restricted to lists but works with
arbitrary iterables:

from itertools import chain, repeat, islice

def expand(iterable, length, default=None):
return islice(chain(iterable, repeat(default)), length)

Peter




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Peter Otten
Peter Otten wrote:

> Paul McGuire wrote:
> 
>>> Is there an elegant way to assign to a list from a list of unknown
>>> size?  For example, how could you do something like:
>>>
>>> >>>  a, b, c = (line.split(':'))
>>> if line could have less than three fields?
> 
>> I asked a very similar question a few weeks ago, and from the various
>> suggestions, I came up with this:
>> 
>> line = ":BBB"
>> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
>> a,b,c = expand( line.split(":"), "", 3 )
> 
> Here is an expand() variant that is not restricted to lists but works with
> arbitrary iterables:
> 
> from itertools import chain, repeat, islice
> 
> def expand(iterable, length, default=None):
> return islice(chain(iterable, repeat(default)), length)

Also nice, IMHO, is allowing individual defaults for different positions in
the tuple:

>>> def expand(items, defaults):
... if len(items) >= len(defaults):
... return items[:len(defaults)]
... return items + defaults[len(items):]
...
>>> expand((1, 2, 3), (10, 20, 30, 40))
(1, 2, 3, 40)
>>> expand((1, 2, 3), (10, 20))
(1, 2)

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Nick Craig-Wood
TB <[EMAIL PROTECTED]> wrote:
>  Is there an elegant way to assign to a list from a list of unknown
>  size?  For example, how could you do something like:
> 
> >>>  a, b, c = (line.split(':'))
>  if line could have less than three fields?

You could use this old trick...

  a, b, c = (line+"::").split(':')[:3]

Or this version if you want something other than "" as the default

  a, b, b = (line.split(':') + 3*[None])[:3]

BTW This is a feature I miss from perl...

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Alex Martelli
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
   ...
> Or this version if you want something other than "" as the default
> 
>   a, b, b = (line.split(':') + 3*[None])[:3]

Either you mean a, b, c -- or you're being subtler than I'm grasping.


> BTW This is a feature I miss from perl...

Hmmm, I understand missing the ``and all the rest goes here'' feature
(I'd really love it if the rejected
a, b, *c = whatever
suggestion had gone through, ah well), but I'm not sure what exactly
you'd like to borrow instead -- blissfully by now I've forgotten a lot
of the perl I used to know... care to clarify?


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Bengt Richter
On Fri, 21 Jan 2005 17:04:11 -0800, Jeff Shannon <[EMAIL PROTECTED]> wrote:

>TB wrote:
>
>> Hi,
>> 
>> Is there an elegant way to assign to a list from a list of unknown
>> size?  For example, how could you do something like:
>> 
>> 
> a, b, c = (line.split(':'))
>> 
>> if line could have less than three fields?
>
>(Note that you're actually assigning to a group of local variables, 
>via tuple unpacking, not assigning to a list...)
>
>One could also do something like this:
>
> >>> l = "a:b:c".split(':')
> >>> a, b, c, d, e = l + ([None] * (5 - len(l)))
> >>> print (a, b, c, d, e)
>('a', 'b', 'c', None, None)
> >>>

Or
 >>> a, b, c, d, e = ('a:b:c'.split(':')+[None]*4)[:5]
 >>> print (a, b, c, d, e)
 ('a', 'b', 'c', None, None)

You could even be profligate and use *5 in place of that *4,
if that makes an easier idiom ;-)

Works if there's too many too:

 >>> a, b = ('a:b:c'.split(':')+[None]*2)[:2]
 >>> print (a, b)
 ('a', 'b')



>
>Personally, though, I can't help but think that, if you're not certain 
>how many fields are in a string, then splitting it into independent 
>variables (rather than, say, a list or dict) *cannot* be an elegant 
>solution.  If the fields deserve independent names, then they must 
>have a definite (and distinct) meaning; if they have a distinct 
>meaning (as opposed to being a series of similar items, in which case 
>you should keep them in a list), then which field is it that's 
>missing?  Are you sure it's *always* the last fields?  This feels to 
>me like the wrong solution to any problem.
>
>Hm, speaking of fields makes me think of classes.
>
> >>> class LineObj:
>... def __init__(self, a=None, b=None, c=None, d=None, e=None):
>... self.a = a
>... self.b = b
>... self.c = c
>... self.d = d
>... self.e = e
>...
> >>> l = "a:b:c".split(':')
> >>> o = LineObj(*l)
> >>> o.__dict__
>{'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None}
> >>>
>
>This is a bit more likely to be meaningful, in that there's almost 
>certainly some logical connection between the fields of the line 
>you're splitting and keeping them as a class demonstrates that 
>connection, but it still seems a bit smelly to me.
>
That gives me an idea:

 >>> def foo(a=None, b=None, c=None, d=None, e=None, *ignore):
 ... return a, b, c, d, e
 ...
 >>> a, b, c, d, e = foo(*'a:b:c'.split(':'))
 >>> print (a, b, c, d, e)
 ('a', 'b', 'c', None, None)

But then, might as well do:

 >>> def bar(nreq, *args):
 ... if nreq <= len(args): return args[:nreq]
 ... return args+ (nreq-len(args))*(None,)
 ...
 >>> a, b, c, d, e = bar(5, *'a:b:c'.split(':'))
 >>> print (a, b, c, d, e)
 ('a', 'b', 'c', None, None)
 >>> a, b = bar(2, *'a:b:c'.split(':'))
 >>> print (a, b)
 ('a', 'b')
 >>> a, b, c = bar(3, *'a:b:c'.split(':'))
 >>> print (a, b, c)
 ('a', 'b', 'c')

But usually, I would like n + tail, where I know n is a safe bet, e.g.,

 >>> def ntail(n, *args):
 ... return args[:n]+(args[n:],)
 ...
 >>> a, b, t = ntail(2, *'a:b:c:d:e'.split(':'))
 >>> print (a, b, t)
 ('a', 'b', ('c', 'd', 'e'))
 >>> a, b, t = ntail(2, *'a:b'.split(':'))
 >>> print (a, b, t)
 ('a', 'b', ())


People have asked to be able to spell that as

 a, b, *t = 'a:b:c:d:e'.split(':')



Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Nick Craig-Wood
Alex Martelli <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> ...
> > Or this version if you want something other than "" as the default
> > 
> >   a, b, b = (line.split(':') + 3*[None])[:3]
> 
>  Either you mean a, b, c -- or you're being subtler than I'm
>  grasping.

Just a typo - I meant c!

> > BTW This is a feature I miss from perl...
> 
>  Hmmm, I understand missing the ``and all the rest goes here'' feature
>  (I'd really love it if the rejected
>  a, b, *c = whatever
>  suggestion had gone through, ah well), but I'm not sure what exactly
>  you'd like to borrow instead -- blissfully by now I've forgotten a lot
>  of the perl I used to know... care to clarify?

I presume your construct above is equivalent to

  my ($a, $b, @c) = split /.../;

which I do indeed miss.

Sometimes I miss the fact that in the below any unused items are set
to undef, rather than an exception being raised

  my ($a, $b, $c) = @array;

However, I do appreciate the fact (for code reliability) that the
python equivalent

  a, b, c = array

will blow up if there aren't exactly 3 elements in array.

So since I obviously can't have my cake an eat it here, I'd leave
python how it is for the second case, and put one of the suggestions
in this thread into my toolbox / the standard library.

BTW I've converted a lot of perl programs to python so I've come
across a lot of little things like this!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Michael Spencer
Alex Martelli wrote:
[explanation and the following code:]
 >>> a, b, c = it.islice(
 ...   it.chain(
 ...   line.split(':'), 
 ...   it.repeat(some_default),
 ...   ), 
 ...   3)
 ... 
 ...   
 >>> def pad_with_default(N, iterable, default=None):
 ... it = iter(iterable)
 ... for x in it:
 ... if N<=0: break
 ... yield x
 ... N -= 1
 ... while N>0:
 ... yield default
 ... N -= 1
Why not put these together and put it in itertools, since the requirement seems 
to crop up every other week?

 >>> line = "A:B:C".split(":")
 ...
 >>> def ipad(N,iterable, default = None):
 ... return it.islice(it.chain(iterable, it.repeat(default)), N)
 ...
 >>> a,b,c,d = ipad(4,line)
 >>> a,b,c,d
('A', 'B', 'C', None)
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Reinhold Birkenfeld
Michael Spencer wrote:
> Alex Martelli wrote:
> [explanation and the following code:]
> 
>>  >>> a, b, c = it.islice(
>>  ...   it.chain(
>>  ...   line.split(':'), 
>>  ...   it.repeat(some_default),
>>  ...   ), 
>>  ...   3)
>>  ... 
>>  ...   
>>  >>> def pad_with_default(N, iterable, default=None):
>>  ... it = iter(iterable)
>>  ... for x in it:
>>  ... if N<=0: break
>>  ... yield x
>>  ... N -= 1
>>  ... while N>0:
>>  ... yield default
>>  ... N -= 1
> 
> Why not put these together and put it in itertools, since the requirement 
> seems 
> to crop up every other week?
> 
>   >>> line = "A:B:C".split(":")
>   ...
>   >>> def ipad(N,iterable, default = None):
>   ... return it.islice(it.chain(iterable, it.repeat(default)), N)
>   ...
>   >>> a,b,c,d = ipad(4,line)
>   >>> a,b,c,d
> ('A', 'B', 'C', None)

Good idea!

(+1 if this was posted on python-dev!)

Reinhold
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Nick Coghlan
Reinhold Birkenfeld wrote:
Why not put these together and put it in itertools, since the requirement seems 
to crop up every other week?

 >>> line = "A:B:C".split(":")
 ...
 >>> def ipad(N,iterable, default = None):
 ... return it.islice(it.chain(iterable, it.repeat(default)), N)
 ...
 >>> a,b,c,d = ipad(4,line)
 >>> a,b,c,d
('A', 'B', 'C', None)

Good idea!
(+1 if this was posted on python-dev!)
Please, please Google the python-dev archives before doing so ;)
Cheers,
Nick.
I seem to recall 'tuple unpacking' as the appropriate phrase. . .
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-22 Thread Reinhold Birkenfeld
Nick Coghlan wrote:
> Reinhold Birkenfeld wrote:
>>>Why not put these together and put it in itertools, since the requirement 
>>>seems 
>>>to crop up every other week?
>>>
>>>  >>> line = "A:B:C".split(":")
>>>  ...
>>>  >>> def ipad(N,iterable, default = None):
>>>  ... return it.islice(it.chain(iterable, it.repeat(default)), N)
>>>  ...
>>>  >>> a,b,c,d = ipad(4,line)
>>>  >>> a,b,c,d
>>>('A', 'B', 'C', None)
>> 
>> 
>> Good idea!
>> 
>> (+1 if this was posted on python-dev!)
> 
> Please, please Google the python-dev archives before doing so ;)

I have no intent of doing so, I would leave that to more experienced
people...

Reinhold ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value in a list

2005-01-24 Thread TB
Thanks very much for all the responses.  They were useful to me and
I'll probably refer back to them again in the future.

TB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default value for Listbox (Tkinter)

2005-02-24 Thread Jørgen Cederberg
Harlin Seritt wrote:
Whenever I set up something similar:
vals = ['1', '2','3']
for v in vals:
   listbox.inset(END, v)
I notice that when this listbox is displayed, there is never a default
value. How can I make sure that one of the indices is selected by
default?
Hi Harlin,
you must use the select_set method of the listbox.
---
from Tkinter import *
root = Tk()
listbox = Listbox(root)
listbox.pack()
vals = ['1', '2','3']
for v in vals:
  listbox.insert(END, v)
listbox.select_set(0) # sets the first element
root.mainloop()
---
Some good resources for Tkinter:
http://www.pythonware.com/library/tkinter/introduction/index.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/
HTH
Jørgen Cederberg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default value for Listbox (Tkinter)

2005-02-25 Thread Harlin Seritt
Thanks Jorgen!

I was reading the Tkinter tutorial (I was looking at this particular
page:
http://www.pythonware.com/library/tkinter/introduction/x5513-methods.htm)
and saw this for select_set():


select_set(index), select_set(first, last)
Add one or more items to the selection.


I think this was why I overlooked it. The description for it says the
listbox adds one or more items to a selection. I would think the
description should say the listbox sets the index or element.

Thanks again,

Harlin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default value for list access?

2005-02-27 Thread Bo Peng
To clearify the problem:
The data is the count of something, for example a[90]=10. a may be a 
dictionary if the range is huge and a list when the range is reasonably 
small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 
does not exist. In the list case, I have to check the length of list 
before I access it (or use exception).

This becomes troublesome when I need to do the following a lot.
  b = a[80][1] + a[80][2] + a[80][3]
If I use the getItem function in my previous email, it will look like
  b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 
2, 0) + getItem(getItem(a, 80, []), 3, 0)

What would be the best solution to handle this? Something like
  b = df( a[80][1], 0) + df( a[80][2], 0) + df( a[80][3], 0)
would be reasonable but df can not be easily defined since the exception 
will be raised before function df is called. Something like

  b = df( a, [80, 1], 0) + df( a, [80,2], 0) + df( a, [80, 3], 0)
would work if df is defined as
def df(a, idx, default):
  try:
for i in range(0, idx):
  a = a[ idx[i] ]
return a
  except:
return 0
but I am afraid that a for loop would bring serious performance problem.
Thanks.
Bo
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value for list access?

2005-02-27 Thread Peter Hansen
Bo Peng wrote:
The data is the count of something, for example a[90]=10. a may be a 
dictionary if the range is huge and a list when the range is reasonably 
small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 
does not exist. In the list case, I have to check the length of list 
before I access it (or use exception).

This becomes troublesome when I need to do the following a lot.
  b = a[80][1] + a[80][2] + a[80][3]
If I use the getItem function in my previous email, it will look like
  b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 2, 
0) + getItem(getItem(a, 80, []), 3, 0)

What would be the best solution to handle this? 
Sounds to me like the best solution is to simplify the implementation
and dispense with the list alternative.  Why use a list if a dictionary
is suitable?  Don't say performance: that's premature optimization.
Dictionaries already have what you need, apparently, with setdefault(),
so just use them and keep the code simple.
...
but I am afraid that a for loop would bring serious performance problem.
More premature optimization?  The first rule of programming should be
to make it work.  Then consider making it faster, but only if it is
really unacceptably slow.  (Some would say to make it work, then make
it "right", then make it fast.  In this case, "right" doesn't mean
"correct" (that's the first step), it means making it clean and simple.
Doing it this way makes sense only if you have a really good test
suite developed along with the code, ala test-driven development.
Lacking that, you should focus on "right" and working together,
which in this case suggests leaving out the complicated list option.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value for list access?

2005-02-27 Thread Ruslan Spivak
Ð ÐÑÐ, 27/02/2005 Ð 14:03 -0600, Bo Peng ÐÐÑÐÑ:
> To clearify the problem:
> 
> The data is the count of something, for example a[90]=10. a may be a 
> dictionary if the range is huge and a list when the range is reasonably 
> small. In the dictionary case, I can use a.setdefault(80, 0) if key 80 
> does not exist. In the list case, I have to check the length of list 
> before I access it (or use exception).
> 
> This becomes troublesome when I need to do the following a lot.
> 
>b = a[80][1] + a[80][2] + a[80][3]
> 
> If I use the getItem function in my previous email, it will look like
> 
>b = getItem(getItem(a, 80, []), 1, 0) + getItem(getItem(a, 80, []), 
> 2, 0) + getItem(getItem(a, 80, []), 3, 0)
> 
> What would be the best solution to handle this? Something like
> 
>b = df( a[80][1], 0) + df( a[80][2], 0) + df( a[80][3], 0)
> 
> would be reasonable but df can not be easily defined since the exception 
> will be raised before function df is called. Something like
> 
>b = df( a, [80, 1], 0) + df( a, [80,2], 0) + df( a, [80, 3], 0)
> 
> would work if df is defined as
> 
> def df(a, idx, default):
>try:
>  for i in range(0, idx):
>a = a[ idx[i] ]
>  return a
>except:
>  return 0
> 
> but I am afraid that a for loop would bring serious performance problem.
> 
> Thanks.
> 
> Bo

I'm not sure if that's suitable for you, but you could define your own
subclasses for 'dict' and 'list' and specify your specific behaviour you
would like.

For dict something like this:

class MyDict(dict):
def __getitem__(self, key):
try:
return super(MyDict, self).__getitem__(key)
except:
return 0

a = MyDcit()

Ruslan


--
http://mail.python.org/mailman/listinfo/python-list


Re: default value for list access?

2005-02-27 Thread Bo Peng

Sounds to me like the best solution is to simplify the implementation
and dispense with the list alternative.  Why use a list if a dictionary
is suitable?  Don't say performance: that's premature optimization.
Dictionaries already have what you need, apparently, with setdefault(),
so just use them and keep the code simple.
You are right that if I use all dictionaries, I can use
  a.setdefault(4,{}).setdefault(2,0)
to access a[4][2]. Not too bad compared to the getItem function.
However, this is an scientific application. Data are stored internally 
in C format and exposed to Python as python array (arraymodule). I guess 
the best way is to modify the arraymodule interface and stop it from 
raising an exception when index is out of range. (similar to Ruslan's 
solution). But this means too much trouble for now.

I will use the df(a, idx, default) method and see if its performance is 
acceptable.

Thanks.
Bo
--
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread keirr
planetthoughtful wrote:
> I'm wondering if it's possible, using raw_input(), to provide a
> 'default' value with the prompt?
>
def get_input_with_default(default, prompt=">>> "):
result = raw_input('['+str(default)+'] '+str(prompt))
if result == "": result = default
return default

> I would like to include the ability to edit an existing value (drawn
> from an SQLite table) using a DOS console Python app, but my gut
> feeling from reading what I can find about raw_input() is that it only
> allows you to provide a prompt, not a default value as well.
>
I think it is the editing part that is going to give you a hard time.
curses and readline might be some help if you were on a Unix platform.
I can't think of any way to provided a editable  value at the dos
prompt.  

All the best,
 Keir.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Steve Holden
planetthoughtful wrote:
> Hi All,
> 
> As always, my posts come with a 'Warning: Newbie lies ahead!'
> disclaimer...
> 
> I'm wondering if it's possible, using raw_input(), to provide a
> 'default' value with the prompt?
> 
> I would like to include the ability to edit an existing value (drawn
> from an SQLite table) using a DOS console Python app, but my gut
> feeling from reading what I can find about raw_input() is that it only
> allows you to provide a prompt, not a default value as well.
> 
> If anyone can give me any advice on how I might achieve this, I would
> be immensely appreciative!
> 
> Many thanks and much warmth,
> 
> planetthoughtful
> 
You need to define your own function, with a default argument that gives 
the value. You can make it work just like raw_input if no default value 
is provided. Something like:

  >>> def raw_default(prompt, dflt=None):
  ...   if dflt:
  ... prompt = "%s [%s]: " % (prompt, dflt)
  ...   res = raw_input(prompt)
  ...   if not res and dflt:
  ... return dflt
  ...   return res
  ...
  >>> raw_default("How many beans make five", '5')
How many beans make five [5]: six
'six'
  >>> raw_default("How many beans make five")
How many beans make fiveten
'ten'
  >>> raw_default("How many beans make five", '5')
How many beans make five [5]:
'5'

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread planetthoughtful
Hi Steve,

As keir mentioned, my goal is to be able to edit the value returned
from a record stored in SQLite, so that it can be updated with the new
value.

To give a little background: as a learning exercise I'm writing a
command line app that will allow me to quickly capture todo items
(based on a similar concept used by an app for the Mac described on
43folders.com). I have the functionality working for adding todo items,
and listing items by various criteria, and updating the status of
items, but haven't included any functionality for being able to edit
items.

It seems, according to kier, that this simply can't be done via the
command line in DOS, which is a shame.

Sorry I didn't explain myself very well in my original post.

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Noah
So you are saying that something like this would not work for you?

current_record_value = get_value_in_database ('record_key')
new_record_value = raw_default ("Enter new record value",
current_record_value)
set_value_in_database ('record_key', new_record_value)

Maybe you are confusing this with TAB completion at the shell command
line.

I often use my own default_input function. I also add the ability to
HELP text
to the prompt, so if the user enters '?' then extra information is
printed.
Of course, that means 

Yours,
Noah

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread keirr
planetthoughtful wrote:

> It seems, according to keir, that this simply can't be done via the
> command line in DOS, which is a shame.

Now, I said I couldn't think of a way to do it - not that it wasn't
possible :-)
If you don't need you program to be portable you can use extensions -
in this case
I would expect you need readline for windows, and ctypes (because
readline for windows needs ctypes).

You can fetch readline from
http://sourceforge.net/project/showfiles.php?group_id=82407
and ctypes from
http://sourceforge.net/project/showfiles.php?group_id=71702

I can't promise these will work (all my python has to be 'pure' and
cross platform so I've never used readline or rlcompleter) but
functions like insert_text look to be in the right area for what (I
think) you want. 
Good luck!

Keir.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Bengt Richter
On 22 Dec 2005 08:55:17 -0800, "planetthoughtful" <[EMAIL PROTECTED]> wrote:

>Hi All,
>
>As always, my posts come with a 'Warning: Newbie lies ahead!'
>disclaimer...
>
>I'm wondering if it's possible, using raw_input(), to provide a
>'default' value with the prompt?
Sure, depending on what you mean ;-)
You can only get a prompt string printed to the screen with raw_input,
but you can build that string any way you want, so it can show e.g.,
User-friendly prose and the current value and a default value and anything else.

Then the user has to enter zero or more characters and press Enter.
Whether something changes value or not, and what value is used, depends on
what the program does with the string (possibly empty) that the user typed.

So you have to decide what user response should mean "change old value to 
default as shown"
and what should mean "make no change" and what should mean "convert the typed 
string to a value
and change the old value to that.

To have a user-friendly program, you won't want to make user errors too easy, 
and you
will probably want to have the program re-prompt if there is an input typo (or 
maybe
an input that converts ok but has bad business consequences (e.g., like that 
recent
Japanese stock sale switcheroo of price and number of shares that cost many 
megabucks).

>
>I would like to include the ability to edit an existing value (drawn
>from an SQLite table) using a DOS console Python app, but my gut
>feeling from reading what I can find about raw_input() is that it only
>allows you to provide a prompt, not a default value as well.
>
What's wrong with showing the default in the prompt itself? The thing is
what user input in response should signify the default? E.g., maybe a single
period by itself could mean "use the default" and nothing could mean "no change"
and other input would be a new value.

>If anyone can give me any advice on how I might achieve this, I would
>be immensely appreciative!

suppose you had some named values in one dict, e.g.,

 >>> for name, price in values.items():
 ... while True: # retry until satisfied
 ... uresp = raw_input(
 ... '\n'
 ... 'Current price of %s is $%.2f %s\n'
 ... 'Press Enter to leave as is, or\n'
 ... 'type "D" (without quotes) followed by Enter to change price 
to %.2f,\n'
 ... 'or enter a new value: ' % (name, price, info[name][0], 
info[name][1]))
 ... if not uresp: break
 ... if uresp=='D': values[name] = info[name][1]; break
 ... else:
 ... try: values[name] = type(values[name])(uresp); break
 ... except Exception, e:
 ... print '%s: %s'%(e.__class__.__name__, e)
 ... print 'Try again'
 ...
 
 Current price of yoghurt is $0.90 each
 Press Enter to leave as is, or
 type "D" (without quotes) followed by Enter to change price to 1.19,
 or enter a new value: D
 
 Current price of banana is $0.79 per pound
 Press Enter to leave as is, or
 type "D" (without quotes) followed by Enter to change price to 0.99,
 or enter a new value:
 
 Current price of apple is $1.29 per pound
 Press Enter to leave as is, or
 type "D" (without quotes) followed by Enter to change price to 1.49,
 or enter a new value: 1..23
 ValueError: invalid literal for float(): 1..23
 Try again
 
 Current price of apple is $1.29 per pound
 Press Enter to leave as is, or
 type "D" (without quotes) followed by Enter to change price to 1.49,
 or enter a new value: 1.23
 >>>

Ok, now we can see what happened:

 >>> for name, price in values.items(): print '%10s: %.2f'%(name,price)
 ...
yoghurt: 1.19
 banana: 0.79
  apple: 1.23
 
I'm not suggesting this as a pattern to follow, just to illustrate what you can 
do
with raw_input. IOW, it's about how you build the prompt string, and what you do
with the user response input string that solves your problem.

Voluminous prompts get old fast, so you might e.g. want to accept a '?' to get 
extra
context-sensitive info instead, followed by retry.

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread planetthoughtful
Hi Noah,

I can't find any mention of a 'raw_default' function. So, lol, yes I'm
kind of saying that it would not work for me (well, it won't unless I
can find where / how you sources and implemented that function, bearing
in mind this will be running on Windows).

Many thanks and much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread planetthoughtful

Bengt Richter wrote:
> On 22 Dec 2005 08:55:17 -0800, "planetthoughtful" <[EMAIL PROTECTED]> wrote:
>

> >I would like to include the ability to edit an existing value (drawn
> >from an SQLite table) using a DOS console Python app, but my gut
> >feeling from reading what I can find about raw_input() is that it only
> >allows you to provide a prompt, not a default value as well.
> >
> What's wrong with showing the default in the prompt itself? The thing is
> what user input in response should signify the default? E.g., maybe a single
> period by itself could mean "use the default" and nothing could mean "no 
> change"
> and other input would be a new value.

Hi Bengt,

I think that would be a great solution if the value being 'edited' was
relatively short, or numeric, etc. But the values I want to 'edit' can
be several hundred characters long (ie they're text fields containing
todo notes), and using your method, I'd either accept the existing
value, or have to retype the text for that record. I think I mislead
people when I used the word 'default' -- I meant in the sense of being
able to edit the existing value, so that value, out of each record,
would be presented as the 'default', available for editing.

Sorry for the confusion.

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread planetthoughtful
Hi Kier,

Any idea where I'd find documentation on using this extension? I've
downloaded and installed, but haven't had any luck finding docs for it.

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread keirr
planetthoughtful wrote:
> Hi Kier,
>
> Any idea where I'd find documentation on using this extension? I've
> downloaded and installed, but haven't had any luck finding docs for it.
>
As it's a windows version of the standard readline module (usually
available on Unix only)
I'd _guess_ that you could use the standard library readline
documenation, i.e. go to python.org and look up the readline module in
the library docs.

Cheers,

 Keir.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Kent Johnson
planetthoughtful wrote:
> I think that would be a great solution if the value being 'edited' was
> relatively short, or numeric, etc. But the values I want to 'edit' can
> be several hundred characters long (ie they're text fields containing
> todo notes), and using your method, I'd either accept the existing
> value, or have to retype the text for that record. I think I mislead
> people when I used the word 'default' -- I meant in the sense of being
> able to edit the existing value, so that value, out of each record,
> would be presented as the 'default', available for editing.

For fields that long I think a GUI is more appropriate than trying to use 
command-line 
editing. You might take a look at easygui - it's textbox is readonly but it 
looks like it 
wouldn't be hard to make it editable - or learn enough Tkinter to do it 
yourself.
http://www.ferg.org/easygui/

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Roger Upole
If you have Pywin32 build 205 installed, you can use the
win32console module to add the data to the typeahead
buffer before you call raw_input.

import win32console
stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

def raw_input_with_default(prompt, default_val):
keypresses=[]
for c in default_val:
evt=win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
evt.Char=unicode(c)
evt.RepeatCount=1
evt.KeyDown=True
keypresses.append(evt)
stdin.WriteConsoleInput(keypresses)
return raw_input(prompt)

data=raw_input_with_default('modify this: ','some data')
print data

   hth
 Roger


"planetthoughtful" <[EMAIL PROTECTED]> wrote:
> Hi Steve,
>
> As keir mentioned, my goal is to be able to edit the value returned
> from a record stored in SQLite, so that it can be updated with the new
> value.
>
> To give a little background: as a learning exercise I'm writing a
> command line app that will allow me to quickly capture todo items
> (based on a similar concept used by an app for the Mac described on
> 43folders.com). I have the functionality working for adding todo items,
> and listing items by various criteria, and updating the status of
> items, but haven't included any functionality for being able to edit
> items.
>
> It seems, according to kier, that this simply can't be done via the
> command line in DOS, which is a shame.
>
> Sorry I didn't explain myself very well in my original post.
>
> Much warmth,
>
> planetthoughtful
>




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Bengt Richter
On 22 Dec 2005 12:42:36 -0800, "planetthoughtful" <[EMAIL PROTECTED]> wrote:

>
>Bengt Richter wrote:
>> On 22 Dec 2005 08:55:17 -0800, "planetthoughtful" <[EMAIL PROTECTED]> wrote:
>>
>
>> >I would like to include the ability to edit an existing value (drawn
>> >from an SQLite table) using a DOS console Python app, but my gut
>> >feeling from reading what I can find about raw_input() is that it only
>> >allows you to provide a prompt, not a default value as well.
>> >
>> What's wrong with showing the default in the prompt itself? The thing is
>> what user input in response should signify the default? E.g., maybe a single
>> period by itself could mean "use the default" and nothing could mean "no 
>> change"
>> and other input would be a new value.
>
>Hi Bengt,
>
>I think that would be a great solution if the value being 'edited' was
>relatively short, or numeric, etc. But the values I want to 'edit' can
>be several hundred characters long (ie they're text fields containing
>todo notes), and using your method, I'd either accept the existing
>value, or have to retype the text for that record. I think I mislead
>people when I used the word 'default' -- I meant in the sense of being
>able to edit the existing value, so that value, out of each record,
>would be presented as the 'default', available for editing.
>
>Sorry for the confusion.
>
If you want to edit text, maybe the best thing is a text editor?
Why not write it into a temp file and start the user's favorite editor
on it, and when done, read the file back into python and delete the temp.
Maybe check whether any changes actually happened before updating the DB.

os.popen{2,3,4} and tempfile module might help.

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-22 Thread Alex Martelli
Bengt Richter <[EMAIL PROTECTED]> wrote:
   ...
> If you want to edit text, maybe the best thing is a text editor?
> Why not write it into a temp file and start the user's favorite editor

Agreed.  There's a recipe for that in the online Python Cookbook, and we
edited and enhanced that into the 2nd edition of the printed (O'Reilly)
Python Cookbook, too.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-23 Thread planetthoughtful
My intention is to build a GUI for this app, yes, but given that I'm
about a week old in my learning of Python, I thought a command-line app
was a better place to start. I'm actually quite surprised at how
featured I've managed to make this app all things considered, and now
I'm running into things that aren't easy to do in Python (and probably
also not easy to do in any scripting language on a Win machine), as
opposed to not easy for me to work out.

I had thought to build GUIs in wxPython - is Tkinter any easier to
learn?

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-23 Thread planetthoughtful
Thank you for the suggestion, I'll have a look at this as an
alternative.

I must admit, it seems a little like a 'kludge', though -- but probably
a necessary one, given the limitations of the OS.

I'm assuming os.popen() keeps track of when the editor closes? Or would
I have to manually fire an 'ok, now update the record in the db' event
after editing the value?

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-23 Thread Alex Martelli
planetthoughtful <[EMAIL PROTECTED]> wrote:

> Thank you for the suggestion, I'll have a look at this as an
> alternative.
> 
> I must admit, it seems a little like a 'kludge', though -- but probably
> a necessary one, given the limitations of the OS.

Hmmm, what OS?  The recipe I mentioned is probably the best approach on
Windows, MacOS, Linux, and other Unix variants -- what other OS do you
have in mind, that would let you submit to the user hundreds of
characters for editing without in fact using an editor?

> I'm assuming os.popen() keeps track of when the editor closes? Or would

It has to, because it needs to supply all the subprocess's output as the
contents of the file object it returns, and it couldn't be sure it has
all of the output until the subprocess has finished.  There are, of
course, other ways to control sub-processes (Python 2.4's subprocess
module, in particular).

> I have to manually fire an 'ok, now update the record in the db' event
> after editing the value?

In some situations it may be impractical to rely on the editor closing;
for example, the user's favorite editor might be a multitab one that's
big, heavy, and slow to start, so that the user doesn't close the whole
process but rather just a specific tab.  In such cases, unless you can
build in some hook specific to the user's favorite editor (so you can
know when a specific tab/file is done getting edited), you may end up
requiring the user to press enter at your prompt to indicate he or she's
done editing, or some such semi-kludge.  I cannot think of a
sufficiently general solution, given the variety of editors around, to
just magically divine the crucial "done with editing" condition...


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-23 Thread Scott David Daniels
planetthoughtful wrote:
> ...
> I had thought to build GUIs in wxPython - is Tkinter any easier to
> learn?

I certainly found Tkinter easier.  There are a couple of good tutorials
(and there is always the Grayson book) on the web to get started.  What
is easiest to learn is (in many cases) a property of the student,
however.  Were I a Linux-only GPL kind of a guy, I think Qt might be
an interesting way to go.  One thing that helps tremendously in learning
Tkinter: using Idle in single-process mode:

 C:\Python24\Python C:\Python24\Lib\idlelib\idle.pyw -n

This is obviously a WinXX example, but the "-n" parameter to idle is
the important part.  Since a single-process Idle is running the Tkinter
GUI loop, you can try operations a step at a time (letting you see what
happens).

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-24 Thread planetthoughtful
Hi Roger,

This is exactly what I was looking for!

Thank you so much!

I now have a fully functioning command-line todo app.

Anyone interested in why I picked that as my 2nd-ever-Python-app might
like to read the post over at 43folders.com about suggested uses for
Quicksilver on the Mac (http://www.43folders.com/2005/11/21/qs-redux/).
I wasn't aware of anything similar on Windows, so it seemed like a good
opportunity to build something with similar (and, in fact, better)
functionality (at least in terms of the 43folders.com use for
Quicksilver) using Python.

Anyway, thanks again -- very much appreciate everyone's input!

Much warmth,

planetthoughtful

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-24 Thread Kent Johnson
planetthoughtful wrote:
> My intention is to build a GUI for this app, yes, but given that I'm
> about a week old in my learning of Python, I thought a command-line app
> was a better place to start. 
> 
> I had thought to build GUIs in wxPython - is Tkinter any easier to
> learn?

Tkinter is quite easy to use for simple apps. Pythoncard is a layer on 
top of wxPython that makes it easier to use, you might want to look at that.

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Providing 'default' value with raw_input()?

2005-12-28 Thread Ernst Noch
Alex Martelli wrote:

> In some situations it may be impractical to rely on the editor closing;
> for example, the user's favorite editor might be a multitab one that's
> big, heavy, and slow to start, so that the user doesn't close the whole
> process but rather just a specific tab.  In such cases, unless you can
> build in some hook specific to the user's favorite editor (so you can
> know when a specific tab/file is done getting edited), you may end up
> requiring the user to press enter at your prompt to indicate he or she's
> done editing, or some such semi-kludge.  I cannot think of a
> sufficiently general solution, given the variety of editors around, to
> just magically divine the crucial "done with editing" condition...
> 
> 
> Alex

The ExternalEditor product for Zope does this in a quite clever way - 
probably not perfect, but it worked for me every time in windows and linux.
The product is used to be able to edit any Zope object in an external 
editor and automatically transfer the edited file from the client to the 
server after save.

The source can be found at http://plope.com/software/ExternalEditor.


-- 
http://mail.python.org/mailman/listinfo/python-list


Difficulty with maxsplit default value for str.split

2006-09-23 Thread Steven D'Aprano
I'm having problems passing a default value to the maxsplit argument of
str.split. I'm trying to write a function which acts as a wrapper to
split, something like this:

def mysplit(S, sep=None, maxsplit=None):
pre_processing()
result = S.split(sep, maxsplit)
post_processing()
return result

But the split method doesn't accept a value of None for maxsplit, and I
don't know what default value I should be using. Passing 0 as the default
isn't correct, because then it splits zero times.

By experimentation, I have discovered that passing -1 as the default
instead of None *appears* to work, but I'm not sure if I can rely on it or
if that is an accidental implementation detail. According to the
documentation at
http://docs.python.org/lib/string-methods.html#string-methods

split([sep [,maxsplit]])
Return a list of the words in the string, using sep as the delimiter
string. If maxsplit is given, at most maxsplit splits are done. (thus,
the list will have at most maxsplit+1 elements). If maxsplit is not
specified, then there is no limit on the number of splits (all
possible splits are made).


If I take that literally, then the correct way to wrap split is something
like this:

def mysplit(S, sep=None, maxsplit=None):
pre_processing()
if maxsplit is None:
# don't specify maxsplit
result = S.split(sep)
else:
result = S.split(sep, maxsplit)
post_processing()
return result

Is it safe for me to pass -1 as the default to maxsplit, meaning
"unlimited splits"? Should the docs be fixed to mention that?

Thanks,



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty with maxsplit default value for str.split

2006-09-23 Thread Nick Vatamaniuc
Steven,

According to the current Python source the default value of
maxsplit=-1. I think you can count on that as I don't think there would
be a reason to change it in the future. If you are really worried about
it then your version of calling a particular version of split should
work.

By the way, if you use Python 2.5 and when your maxsplit function is
called there is a clear common case  in regards to maxsplit, you could
use the new conditional expression. Say most of the time mysplit is
used with a default value of maxsplit, then you can re-write your 'if'
code as
-
result=S.split(sep) if maxsplit is None else S.split(sep,maxsplit)
-

-Nick Vatamaniuc



Steven D'Aprano wrote:
> I'm having problems passing a default value to the maxsplit argument of
> str.split. I'm trying to write a function which acts as a wrapper to
> split, something like this:
>
> def mysplit(S, sep=None, maxsplit=None):
> pre_processing()
> result = S.split(sep, maxsplit)
> post_processing()
> return result
>
> But the split method doesn't accept a value of None for maxsplit, and I
> don't know what default value I should be using. Passing 0 as the default
> isn't correct, because then it splits zero times.
>
> By experimentation, I have discovered that passing -1 as the default
> instead of None *appears* to work, but I'm not sure if I can rely on it or
> if that is an accidental implementation detail. According to the
> documentation at
> http://docs.python.org/lib/string-methods.html#string-methods
>
> split([sep [,maxsplit]])
> Return a list of the words in the string, using sep as the delimiter
> string. If maxsplit is given, at most maxsplit splits are done. (thus,
> the list will have at most maxsplit+1 elements). If maxsplit is not
> specified, then there is no limit on the number of splits (all
> possible splits are made).
>
>
> If I take that literally, then the correct way to wrap split is something
> like this:
>
> def mysplit(S, sep=None, maxsplit=None):
> pre_processing()
> if maxsplit is None:
> # don't specify maxsplit
> result = S.split(sep)
> else:
> result = S.split(sep, maxsplit)
> post_processing()
> return result
>
> Is it safe for me to pass -1 as the default to maxsplit, meaning
> "unlimited splits"? Should the docs be fixed to mention that?
> 
> Thanks,
> 
> 
> 
> -- 
> Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty with maxsplit default value for str.split

2006-09-24 Thread Fredrik Lundh
Steven D'Aprano wrote:

> I'm having problems passing a default value to the maxsplit argument of
> str.split. I'm trying to write a function which acts as a wrapper to
> split, something like this:
> 
> def mysplit(S, sep=None, maxsplit=None):
> pre_processing()
> result = S.split(sep, maxsplit)
> post_processing()
> return result
> 
> But the split method doesn't accept a value of None for maxsplit, and I
> don't know what default value I should be using.

 def mysplit(S, *args):
pre_processing()
result = S.split(*args)
post_processing()
return result

> Is it safe for me to pass -1 as the default to maxsplit, meaning
> "unlimited splits"?

not really.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty with maxsplit default value for str.split

2006-09-25 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> Is it safe for me to pass -1 as the default to maxsplit, meaning
> "unlimited splits"? Should the docs be fixed to mention that?

Frederik gave a simple and practical solution to your immediate
problem, but yes, I think the docs should be fixed after checking the
code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty with maxsplit default value for str.split

2006-09-25 Thread Steven D'Aprano
On Sun, 24 Sep 2006 10:34:31 +0200, Fredrik Lundh wrote:

>> But the split method doesn't accept a value of None for maxsplit, and I
>> don't know what default value I should be using.
> 
>  def mysplit(S, *args):
>   pre_processing()
>   result = S.split(*args)
>   post_processing()
>   return result

Thanks Fredrik, that's *exactly* the sort of insight I was lacking. And
now that you've shown me, I can't believe how obvious it is.


-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list


Using default a empty dictionary as a default value

2005-03-22 Thread C Gillespie
Dear All,
I ran my code through pylint to clean it up and one of the (many) errors it
through up was
Dangerous default value {} as argument
Bascially, I have:

class NewClass:
def __init__(self,  myDict={}):
for key, value in myDict:
print key, value

Obviously, this is not the way it should be done. Should I have a default
value of None for myDict and test for it? Or is there some other way?

Thanks

Colin



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using default a empty dictionary as a default value

2005-03-22 Thread Diez B. Roggisch
C Gillespie wrote:

> Dear All,
> I ran my code through pylint to clean it up and one of the (many) errors
> it through up was
> Dangerous default value {} as argument
> Bascially, I have:
> 
> class NewClass:
> def __init__(self,  myDict={}):
> for key, value in myDict:
> print key, value
> 
> Obviously, this is not the way it should be done. Should I have a default
> value of None for myDict and test for it? Or is there some other way?

Yes. That's the way to go.
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using default a empty dictionary as a default value

2005-03-22 Thread SER.RI-TIC-Alexis Roda
C Gillespie wrote:
Dear All,
I ran my code through pylint to clean it up and one of the (many) errors it
through up was
Dangerous default value {} as argument
Bascially, I have:
class NewClass:
def __init__(self,  myDict={}):
for key, value in myDict:
print key, value
Obviously, this is not the way it should be done. Should I have a default
value of None for myDict and test for it? Or is there some other way?
Take a look at:
http://www.python.org/doc/2.4/tut/node6.html#SECTION00671
look for "Important warning"
HTH
--
   
  (@ @)
oOO(_)OOo--
<>   Ojo por ojo y el mundo acabara ciego
/\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain)
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using default a empty dictionary as a default value

2005-03-22 Thread Peter Hansen
C Gillespie wrote:
Dear All,
I ran my code through pylint to clean it up and one of the (many) errors it
through up was
Dangerous default value {} as argument
Bascially, I have:
class NewClass:
def __init__(self,  myDict={}):
for key, value in myDict:
print key, value
Obviously, this is not the way it should be done. Should I have a default
value of None for myDict and test for it? Or is there some other way?
If you *know* you will not be modifying the contents
of myDict, and you *know* you will not be modifying
the function in the future to do so, then it's
completely safe as written...
--
http://mail.python.org/mailman/listinfo/python-list


User input with a default value that can be modified

2007-05-28 Thread Etienne Hilson
Hello the list :-)

I do a little program that permit the user to manage list of sentences.
This program runs into a linux shell.
The user can add, modify and delete the sentences.

What I want to do is :

When the user want to modify one sentence, I would like to do this :

Modify your sentence : The_sentence_appear_here_followed_by_a_cursor

And the user can go back with the cursor, like in the bash shell,
delete, modify, and when pressing enter, the new value (or the same if
not modified) is put in my variable.

Of course, the first think I did as a newbie was :

new_sentence = raw_input("Modify your sentence : "old_sentence)

But OF COURSE, stupid am I, the user cannot put the cursor back into
the old sentence !

I think about playing with some sophisticated keyboard exercise where
I could program a new input command with a value already appearing as
answer, but I am pretty sure that it exists already.

What do you think about it ?

Actually, it is quite difficult to find anything on it, because the
keywords are not very obvious (input, default answer, ...)

Thank you for your help.

Etienne
-- 
(\__/)
(='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
(")_(")  votre signature pour l'aider à dominer le monde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

-- 
http://mail.python.org/mailman/listinfo/python-list