Re: Favorite non-python language trick?

2005-07-07 Thread Edvard Majakari
Simon Brunning [EMAIL PROTECTED] writes:

 http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb

Neat.

I guess about 75% about programming-related things classified as neat-o or
convenient! are already implemented by some Pythonista(s). Spoils all the
fun for reinventing the wheel, doesn't it. :)

-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),\n;
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-07 Thread Shai
Mike Meyer wrote:
 Shai [EMAIL PROTECTED] writes:

  They're called Special vars, and you need to define them (unlike
  local LISP variables, which behave essentially like Python vars), but
  then you use them just like other vars (that is, you usually bind them
  with LET). This is the first I hear about them being ill-considered in
  LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
  book which recommends them. I don't know about Scheme, but I think it
  does have them.

 I'm pretty sure scheme doesn't have dynamically bound variables. I
 just went through r5rs to check, and couldn't find them.


Yes, you're right. One learns.

  dynamic x=10
  def bar():
print x
 

 This looks different from what I understood before. You're now
 declaring the variable dynamic in the global scope, rather than in the
 function that makes it dynamic. This is a *much* more palatable
 situation.


This is indeed different from what I said first. It copies the Common
LISP construct without regard to consistency with the Python global
construct.

 Globals are lexically scoped. As such, you can find the defintion of
 the variable by examining the module that includes the function. Yes,
 other modules can reach into your module and change them - but you can
 find those, because they reference your module by name.

 A dynamic variable declared so in a function has no such clue
 associated with it. If the variable is declared dynamic in the module
 of the enclosed function, that provides a contextual clue.

In my original proposal, dynamic variables are seen as globals from the
function in their module which reads them; no more, no less. The
important point I want from dynamic scope is the time-locality of
asignments, that
is, the fact that they are undone when the (lexical) scope of the new
binding ends. This allows the use of globals, with a lot less fear of
unintended interactions between users of the module (well, this is only
accurate until multithreading enters the picture, but that can be
handled
too).

[rest snipped]

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


Re: Favorite non-python language trick?

2005-07-07 Thread Robert Kern
Edvard Majakari wrote:
 Simon Brunning [EMAIL PROTECTED] writes:
 
http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb
 
 Neat.
 
 I guess about 75% about programming-related things classified as neat-o or
 convenient! are already implemented by some Pythonista(s). Spoils all the
 fun for reinventing the wheel, doesn't it. :)

Doesn't seem to stop most Pythonistas from trying, though.  :-)

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Favorite non-python language trick?

2005-07-06 Thread Edvard Majakari

(sorry, my NUA had lost the original article)

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

Ability to tag some methods 'deprecated' as in Java (from 1.5
onwards?). However, Python interpreter doesn't have to do it: pydoc and
similar tools could detect, say, '@deprecated' in method comment string and
warn user about it.

Currently I just document deprecated methods, and if I feel like it, I also
add

def some_method_which_is_badly_named_or_just_plain_wrong(..)
docstring

This method is now deprecated. Use frob() instead.


sys.stderr.write('warning: method 
some_method_which_is_badly_named_or_just_plain_wrong is now deprecated')


-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!
You shouldn't verb verbs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-06 Thread Thomas Heller
Edvard Majakari [EMAIL PROTECTED] writes:

 (sorry, my NUA had lost the original article)

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

 Ability to tag some methods 'deprecated' as in Java (from 1.5
 onwards?). However, Python interpreter doesn't have to do it: pydoc and
 similar tools could detect, say, '@deprecated' in method comment string and
 warn user about it.

I don't see what's wrong with this code, and if one wanted, one could
also implement a decorator which calls warnings.warn when the function
is called:

def c_buffer(init, size=None):
deprecated, use create_string_buffer instead
import warnings
warnings.warn(c_buffer is deprecated, use create_string_buffer instead,
  DeprecationWarning, stacklevel=2)
return create_string_buffer(init, size)

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


Re: Favorite non-python language trick?

2005-07-06 Thread Edvard Majakari
Thomas Heller [EMAIL PROTECTED] writes:

 I don't see what's wrong with this code, and if one wanted, one could
 also implement a decorator which calls warnings.warn when the function
 is called:

 def c_buffer(init, size=None):
 deprecated, use create_string_buffer instead
 import warnings
 warnings.warn(c_buffer is deprecated, use create_string_buffer instead,
   DeprecationWarning, stacklevel=2)
 return create_string_buffer(init, size)

Well, nothing's wrong there, and the same could be done with Java
before. However, having a consistent deprecated string everywhere allows
easier eg. automatic finding of such methods from documentation. 

Decorators also help here, but that requires version 2.3 or newer (which
usually isn't a problem, but can be)

Hey! I hadn't realized category parameter nor stacklevel in warnings module
(just used a few times, never read the doc because I didn't need to). Neat,
thanks.

-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),\n;
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-06 Thread Simon Brunning
On 7/6/05, Edvard Majakari [EMAIL PROTECTED] wrote:
 Ability to tag some methods 'deprecated' as in Java (from 1.5
 onwards?). However, Python interpreter doesn't have to do it: pydoc and
 similar tools could detect, say, '@deprecated' in method comment string and
 warn user about it.

http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-06 Thread Shai
I only saw this today... sorry about the late response. Anyway,
replying to your two messages at once:

Mike Meyer wrote:

 Last time I checked, dynamic binding variables were frowned on in LISP
 systems as well. Scheme doesn't have them.  Common LISP requires
 special forms to use them.

They're called Special vars, and you need to define them (unlike
local LISP variables, which behave essentially like Python vars), but
then you use them just like other vars (that is, you usually bind them
with LET). This is the first I hear about them being ill-considered in
LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
book which recommends them. I don't know about Scheme, but I think it
does have them.

The one special thing you see in every use of these vars in LISP is a
naming convention; as LISP symbols can contain most characters, they
are usually named with asterisks on both ends to distinguish them.
Thus, in the example above, the dynamic var would be named *x*.

 The problem with the given use case is that it lets every routine in
 the call chain substitute it's own variable for the library parameter
 you want to use, with no local indication that this is going
 on. This makes bugs in dynamically scoped variables a PITA to find.

In LISP, the naming convention indeed takes care of that; and indeed, I
consider taking the LISP way would be better. The definition of x as
dynamic would then be not in bar nor its callers, but in the definition
of x, as in

dynamic x=10
def bar():
  print x

I specified the syntax as I did, specifically to make it match the
current definition of globals, which enjoys the same problems you
noted with my dynamics.


  x=10
  def foo():
# No need to define x as it is only read -- same as globals
print x
 
  def bar():
dynamic x
x = 11
foo()
 
  def baz():
bar() # prints 11
foo() # prints 10; the binding in bar is undone when bar exits

 Here's the problem with that. Consider this script:

 import foo
 x = 10
 def bar():
 print x

 foo.foogle(bar)

 If foo.foogle includes dynamic x and then invokes bar, bar could
 print anything. This makes the behavior of bar unpredictable by
 examining the sourc, with no hint that that is going on.

While I didn't write it explicitly, if both LISP and Python globals are
to be followed, the dynamic x should somehow be defined in the scope of
its module. On second thought, this means dynamic _must_ be added in
the variable definition, for foo.foogle will simply access it as
othermodule.x, which doesn't differentiate globals from dynamics.

Either way, Python as it is now allows foo.foogle to change x even
without dynamic variables; it is accessible as barmodule.x. bar()
should expect to have other functions mess with its globals, and
dynamics are no different.

  Given that it's a feature I don't want programmers using, I'd only be
  willing to see it added to the language if you can show that it has no
  overhead so long as you don't use it. I'm not sure that can be done.

That sounds like a fine requirement. Now, with my corrected
proposition, it would be implementable at the module-object level, so
that only module which use the feature, and modules which use them,
would be affected.

 Here's a proposal for dynamically bound variables that you should be
 able to implement without affecting the runtime behavior of code that
 doesn't use it.

 Instead of dynamic meaning all references to the named variable(s)
 will be dynamic until this function exits, have it mean the named
 variable(s) will be dynamic in this function. Whether it should only
 check local variables in the calling routines, check local + global,
 or check for all free variables, is an open question.

 I.e. - your example would be written:

 x = 10
 def foo():
 dynamic x
 print x

 def bar():
 x = 11
 foo()

 def baz():
 bar()   # prints 11
 foo()   # Possibly an error?


This introduces the same problem you noted with my original proposal,
but in reverse: Now, in bar(), you define and use a local variable, and
suddenly some library function changes its behavior misteriously.

 For my example above, bar would *always* print 10. Nothing that
 foo.foogle did would change that. However, you could write:

 import foo
 def bar():
 dynamic x
 print x

 foo.foogle(bar)

 In this case, bar will print whatever foo.foogle sets x to - and it's
 noted in the source to bar. This means that functions that don't
 declare a dynamic variable can be compiled to the same code they are
 compiled to now.


This is, I believe, disproved by my comment above.

Thanks for your time and effort,

Shai.

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


Re: Favorite non-python language trick?

2005-07-06 Thread Mike Meyer
Shai [EMAIL PROTECTED] writes:

 They're called Special vars, and you need to define them (unlike
 local LISP variables, which behave essentially like Python vars), but
 then you use them just like other vars (that is, you usually bind them
 with LET). This is the first I hear about them being ill-considered in
 LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
 book which recommends them. I don't know about Scheme, but I think it
 does have them.

I'm pretty sure scheme doesn't have dynamically bound variables. I
just went through r5rs to check, and couldn't find them.

 dynamic x=10
 def bar():
   print x

 I specified the syntax as I did, specifically to make it match the
 current definition of globals, which enjoys the same problems you
 noted with my dynamics.

This looks different from what I understood before. You're now
declaring the variable dynamic in the global scope, rather than in the
function that makes it dynamic. This is a *much* more palatable
situation.

Globals are lexically scoped. As such, you can find the defintion of
the variable by examining the module that includes the function. Yes,
other modules can reach into your module and change them - but you can
find those, because they reference your module by name.

A dynamic variable declared so in a function has no such clue
associated with it. If the variable is declared dynamic in the module
of the enclosed function, that provides a contextual clue.

Of course, you can do pretty much anything you want if you're willing
to grovel over the guts of the environment enough, but some things
shouldn't be easy.

 While I didn't write it explicitly, if both LISP and Python globals are
 to be followed, the dynamic x should somehow be defined in the scope of
 its module. On second thought, this means dynamic _must_ be added in
 the variable definition, for foo.foogle will simply access it as
 othermodule.x, which doesn't differentiate globals from dynamics.

 Either way, Python as it is now allows foo.foogle to change x even
 without dynamic variables; it is accessible as barmodule.x. bar()
 should expect to have other functions mess with its globals, and
 dynamics are no different.

The question is, how hard is it to find the other people who are
messing with bar()'s globals? Normal usage with the current situation
makes it fairly starightforward. How does adding dynamicly bound
variables change this?

Of course, if you add the requirement that the variable be tagged in
the scope of the module, you're making things a lot better. That way,
readers of the module know that they need to look back along the call
chain for functions that use such variables. That makes them much
saner to find.

 Instead of dynamic meaning all references to the named variable(s)
 will be dynamic until this function exits, have it mean the named
 variable(s) will be dynamic in this function. Whether it should only
 check local variables in the calling routines, check local + global,
 or check for all free variables, is an open question.

 I.e. - your example would be written:

 x = 10
 def foo():
 dynamic x
 print x

 def bar():
 x = 11
 foo()

 def baz():
 bar()   # prints 11
 foo()   # Possibly an error?


 This introduces the same problem you noted with my original proposal,
 but in reverse: Now, in bar(), you define and use a local variable, and
 suddenly some library function changes its behavior misteriously.

True. That pretty much kills my proposal.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-03 Thread Steven D'Aprano
On Sun, 03 Jul 2005 00:39:19 -0400, Christopher Subich wrote:

 Devan L wrote:
 sum(sequence[0] + [1/element for element in sequence[1:]])
 
 I think that should work.
 
 That won't work, because it misses the x*y part of the expression 
 (x[n]*x[n+1] + 1/x[n+1], for people who haven't immediately read the 
 grandparent).
 
 Personally, I think demanding that it be writable as a sum (or product, 
 or any, or all) is a false standard -- nobody's claimed that these would 
 replace all cases of reduce, just the most common ones.


Er, excuse me, but that is EXACTLY what Devan claimed. 

Quote: With the exception of reduce(lambda x,y:x*y, sequence), reduce can be
replaced with sum, and Guido wants to add a product function.

-- 
Steven.

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


Re: Favorite non-python language trick?

2005-07-03 Thread Peter Otten
Steven D'Aprano wrote:

 How do you replace:
 
 reduce(lambda x,y: x*y-1/y, sequence)
 
 with sum?
 
missing = object()

def my_reduce(f, items, first=missing):
class adder:
def __init__(self, value):
self.value = value
def __add__(self, other):
return adder(f(self.value, other))

if first is missing:
items = iter(items)
try:
first = items.next()
except StopIteration:
raise TypeError
return sum(items, adder(first)).value

if __name__ == __main__:
sequence = map(float, range(10))
r = reduce(lambda x, y: x*y-1/y, sequence)
s = my_reduce(lambda x, y: x*y-1/y, sequence)
assert r == s

:-)

Peter

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


Re: Favorite non-python language trick?

2005-07-03 Thread Christopher Subich
Steven D'Aprano wrote:
 On Sun, 03 Jul 2005 00:39:19 -0400, Christopher Subich wrote:
Personally, I think demanding that it be writable as a sum (or product, 
or any, or all) is a false standard -- nobody's claimed that these would 
replace all cases of reduce, just the most common ones.
 
 Er, excuse me, but that is EXACTLY what Devan claimed. 
 
 Quote: With the exception of reduce(lambda x,y:x*y, sequence), reduce can be
 replaced with sum, and Guido wants to add a product function.

Okay, then... not many people have claimed that sum is a universal 
replacement for reduce, only the most common cases.  It's further 
argued that the uncommon cases are more flexible and (again, mostly) 
anywhere from only slightly less readable to significantly more readable 
in for-loop form.

The only corner case that isn't, so far as I know, is when the reduce() 
has no default initial value and the sequence/generator might possibly 
have 0 elements.  But that's a TypeError anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-03 Thread Rocco Moretti
Jp Calderone wrote:
 On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti 
 [EMAIL PROTECTED] wrote:
 

 I'm not aware of a language that allows it, but recently I've found
 myself wanting the ability to transparently replace objects. 
 
 
 Smalltalk supports this with the become message.  I have also done an 
 implementation of this for Python.

As a pure Python module, or do you have to recompile the interpreter?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-03 Thread Jp Calderone
On Sun, 03 Jul 2005 15:40:38 -0500, Rocco Moretti [EMAIL PROTECTED] wrote:
Jp Calderone wrote:
 On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti
 [EMAIL PROTECTED] wrote:


 I'm not aware of a language that allows it, but recently I've found
 myself wanting the ability to transparently replace objects.


 Smalltalk supports this with the become message.  I have also done an
 implementation of this for Python.

As a pure Python module, or do you have to recompile the interpreter?

Somewhere in between, I guess.  The module is all Python, but relies pretty 
heavily on one particular stdlib extension module.

The code is rather short, and online here:

  http://divmod.org/users/exarkun/become.py

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


Re: Favorite non-python language trick?

2005-07-03 Thread Devan L
Okay, maybe that was too restrictive, reduce can *usually* be replaced
with sum. Sorry about that.

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


Re: Favorite non-python language trick?

2005-07-02 Thread Bernhard Herzog
Scott David Daniels [EMAIL PROTECTED] writes:

 Rocco Moretti wrote:
 Joseph Garvin wrote:

 I'm not aware of a language that allows it, but recently I've found
 myself wanting the ability to transparently replace objects
 I mainly look for it in the object replaces self form, but I guess
 you could also have it for arbitrary objects, e.g. to wrap a logging
 object around a function, even if you don't have access to all
 references of that function.
 Why isn't it in Python? It's completely counter to the conventional
 object semantics.

 Actually this is the old (and terrifying) Smalltalk message 'becomes:'.
 There is a concrete reason it is not in python: objects are represented
 as pointers to their data structures, do not have identical sizes, and
 therefore cannot be copied into each others data space. 

That limitation applies only some of the time, e.g. when you inherit
from built-in types.  But for ordinary classes it can be done:

 class A(object):
... def __init__(self, x):
... self.x = x
... 
 class B(object):
... def __init__(self, y):
... self.y = y
... 
 a = A(1)
 b = B(2)
 vars(a)
{'x': 1}
 vars(b)
{'y': 2}
 a.__class__, b.__class__ = b.__class__, a.__class__
 a.__dict__, b.__dict__ = b.__dict__, a.__dict__
 vars(a)
{'y': 2}
 isinstance(a, B)
True


   Bernhard

-- 
Intevation GmbH http://intevation.de/
Skencil   http://skencil.org/
Thuban  http://thuban.intevation.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-02 Thread Steven D'Aprano
On Fri, 01 Jul 2005 12:24:44 -0700, Devan L wrote:

 With the exception of reduce(lambda x,y:x*y, sequence), reduce can be
 replaced with sum, and Guido wants to add a product function.

How do you replace:

reduce(lambda x,y: x*y-1/y, sequence) 

with sum?


Inquiring minds want to know.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-07-02 Thread Devan L
sum(sequence[0] + [1/element for element in sequence[1:]])

I think that should work.

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


Re: Favorite non-python language trick?

2005-07-02 Thread Christopher Subich
Devan L wrote:
 sum(sequence[0] + [1/element for element in sequence[1:]])
 
 I think that should work.

That won't work, because it misses the x*y part of the expression 
(x[n]*x[n+1] + 1/x[n+1], for people who haven't immediately read the 
grandparent).

Personally, I think demanding that it be writable as a sum (or product, 
or any, or all) is a false standard -- nobody's claimed that these would 
replace all cases of reduce, just the most common ones.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-02 Thread James
Steven D'Aprano wrote:
 On Fri, 24 Jun 2005 14:29:37 -0700, James wrote:

  Interesting thread ...
 
  1.) Language support for ranges as in Ada/Pascal/Ruby
  1..10 rather than range(1, 10)

 What advantages do Pascal-like for loops give over Python for loops?

 The only two I can think of are trivial:

 (1) the Pascal-like for loop is six characters shorter to type:

 for i = 1 to 10:# 16 chars
 for i in range(1, 10):  # 22 chars

 (2) for very large ranges, you don't have to hold the entire list of
 integers in memory. But you can use xrange() instead of range(), which
 also doesn't hold the entire list in memory.

First, I was never concerned about what I can do with the new keyword
that I could not do without since most languages are turing complete.
The question is that of elegance and it is subjective. I do know that
if Python kept adding features that everyone liked, it will end up like
Perl (although D seems to be doing a great job incorporating everyone's
favorite features while still retaining language consistancy. Then
again, it is very new.). But this thread is about favorite features
from other languages.

Secondly, the point was about ranges. Their use in loops (as in Ada and
Ruby) is just one instance. For me, they are more readable in the same
way I like -- for comments as in Eiffel and Ada rather than // and #
which do the same.


  2.) Contracts

 Explain please.

Design By Contract (as in Eiffel and D)

  3.) With

 Explain please.

As in Delphi
http://www.delphibasics.co.uk/RTL.asp?Name=With

There have been some PEPs regarding this.

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


Re: Favorite non-python language trick?

2005-07-01 Thread Pekka Karjalainen
In article [EMAIL PROTECTED], Joseph Garvin wrote:
I'm curious -- what is everyone's favorite trick from a non-python 
language? And -- why isn't it in Python?


  Being able to use my native language without a hitch when naming my
variables c. Java allows that because it supports almost any Unicode
character in its identifiers. With Python I occasionally have to stop and
think: I can't name it that. What's better?

  Not everyone always writes their programs in English. Once you get used
to Java's naming possibilities, it's plain annoying to go back, even if
it's just a couple of letters that're lacking in my case.

-- 
Pekka Karjalainen - Oulu, Finland

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


Re: Favorite non-python language trick?

2005-07-01 Thread Devan L
With the exception of reduce(lambda x,y:x*y, sequence), reduce can be
replaced with sum, and Guido wants to add a product function.

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


Re: Favorite non-python language trick?

2005-07-01 Thread TZOTZIOY
On Fri, 24 Jun 2005 21:17:09 GMT, rumours say that Ron Adam
[EMAIL PROTECTED] might have written:

I think some sort of inline or deferred local statement would be useful 
also.  It would serve as a limited lambda (after it's removed), eval 
alternative, and as a inlined function in some situations as well I think.

Something like:

 name = defer expression

then used as:

 result = name()

The expression name() will never have arguments as it's meant to 
reference it's variables as locals and probably will be replaced 
directly with names's byte code contents at compile time.

Defer could be shortened to def I suppose, but I think defer would be 
clearer.  Anyway, it's only a wish list item for now.

This is similar:

http://groups-beta.google.com/group/comp.lang.python/msg/6fc884147852d23d
-- 
TZOTZIOY, I speak England very best.
Dear Paul,
please stop spamming us.
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-01 Thread Rocco Moretti
Joseph Garvin wrote:

 I'm curious -- what is everyone's favorite trick from a non-python 
 language? And -- why isn't it in Python?

I'm not aware of a language that allows it, but recently I've found 
myself wanting the ability to transparently replace objects. For 
example, if you have a transparent wrapper class around a certain 
object, and then determine that you no longer need to wrap the object, 
you can say the magic incantation, and the wrapper instance is replaced 
by what it is wrapping everywhere in the program. Or you have a complex 
math object, and you realize you can reduce it to a simple integer, you 
can substitue the integer for the math object, everywhere.

I mainly look for it in the object replaces self form, but I guess you 
could also have it for arbitrary objects, e.g. to wrap a logging object 
around a function, even if you don't have access to all references of 
that function.

Why isn't it in Python? It's completely counter to the conventional 
object semantics.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-01 Thread Shai
Joseph Garvin wrote:

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?


1. Lisp's dynamically scoped variables (Perl has them, and calls them
local, but as far as I've seen their use their is discouraged). These
are global variables which are given time-local bindings. That is,
structuring the syntax after what's used for globals,

x=10
def foo():
  # No need to define x as it is only read -- same as globals
  print x

def bar():
  dynamic x
  x = 11
  foo()

def baz():
  bar() # prints 11
  foo() # prints 10; the binding in bar is undone when bar exits

This feature makes using globals sensible, providing a way to avoid
many important uses (and some say, misuses) of objects if you are so
inclined. It allows you to do some things better than objects do,
because it does to library parameters, what exceptions do to return
codes: instead of passing them in all the way from outside until a
piece of code which actually uses them, they are only mentioned where
you set them and where you really need to access them.

It would not be too hard to implement a version of this (inefficiently)
in the existing language, if frame objects could carry a modifiable
dictionary.

I suppose it is not in Python because (most) Pythoners are not looking
(hard enough) for alternatives to OOP.

2. Prolog's ability to add operators to the language. Though this
facility is quite clanky in Prolog (because there is no elegant way to
specify precedence), the idea is appealing to me. It would allow a
better implementation of my (awkward, granted) recipe for adding logic
programming constructs to Python. It is not in the language because it
might fragmentize it, and because it is very hard to make
recursive-descent parsers like CPython's programmable this way.

3. Lisp's Macros, of course, which have been mentioned already in this
thread. Even Boo-like macros, which are nowhere as strong as Lisp's,
would be very useful. Not in the language, besides its being hard in
any non-lisp-like language, for the reasons mentioned for adding
operators.

On the other hand, there's no end to the features I wish I could copy
from Python to other languages...

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


Re: Favorite non-python language trick?

2005-07-01 Thread Jp Calderone
On Fri, 01 Jul 2005 15:02:10 -0500, Rocco Moretti [EMAIL PROTECTED] wrote:
Joseph Garvin wrote:

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

I'm not aware of a language that allows it, but recently I've found
myself wanting the ability to transparently replace objects. For
example, if you have a transparent wrapper class around a certain
object, and then determine that you no longer need to wrap the object,
you can say the magic incantation, and the wrapper instance is replaced
by what it is wrapping everywhere in the program. Or you have a complex
math object, and you realize you can reduce it to a simple integer, you
can substitue the integer for the math object, everywhere.

I mainly look for it in the object replaces self form, but I guess you
could also have it for arbitrary objects, e.g. to wrap a logging object
around a function, even if you don't have access to all references of
that function.

Why isn't it in Python? It's completely counter to the conventional
object semantics.

Smalltalk supports this with the become message.  I have also done an 
implementation of this for Python.

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


Re: Favorite non-python language trick?

2005-07-01 Thread Scott David Daniels
Rocco Moretti wrote:
 Joseph Garvin wrote:

 I'm not aware of a language that allows it, but recently I've found 
 myself wanting the ability to transparently replace objects
 I mainly look for it in the object replaces self form, but I guess you 
 could also have it for arbitrary objects, e.g. to wrap a logging object 
 around a function, even if you don't have access to all references of 
 that function.
 
 Why isn't it in Python? It's completely counter to the conventional 
 object semantics.

Actually this is the old (and terrifying) Smalltalk message 'becomes:'.
There is a concrete reason it is not in python: objects are represented
as pointers to their data structures, do not have identical sizes, and
therefore cannot be copied into each others data space.  Smalltalk
implementations often have a level of indirection that allows it to
simply tweak an indirection table to implement this method.

The reason I find it terrifying is that I can be passed an object,
place it in a dictionary (for example) based on its value, and then
it can magically be changed into something else which does not fit
in that spot in the dictionary.

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


Re: Favorite non-python language trick?

2005-07-01 Thread Mike Meyer
Shai [EMAIL PROTECTED] writes:

 Joseph Garvin wrote:

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

 1. Lisp's dynamically scoped variables (Perl has them, and calls them
 local, but as far as I've seen their use their is discouraged). These
 are global variables which are given time-local bindings. That is,
 structuring the syntax after what's used for globals,

Perl started life with nothing but dynamically scoped variables. They
added lexical scoping after they realized what a crock dynamic scoping
was.

 x=10
 def foo():
   # No need to define x as it is only read -- same as globals
   print x

 def bar():
   dynamic x
   x = 11
   foo()

 def baz():
   bar() # prints 11
   foo() # prints 10; the binding in bar is undone when bar exits

 This feature makes using globals sensible, providing a way to avoid
 many important uses (and some say, misuses) of objects if you are so
 inclined. It allows you to do some things better than objects do,
 because it does to library parameters, what exceptions do to return
 codes: instead of passing them in all the way from outside until a
 piece of code which actually uses them, they are only mentioned where
 you set them and where you really need to access them.

 It would not be too hard to implement a version of this (inefficiently)
 in the existing language, if frame objects could carry a modifiable
 dictionary.

 I suppose it is not in Python because (most) Pythoners are not looking
 (hard enough) for alternatives to OOP.

Last time I checked, dynamic binding variables were frowned on in LISP
systems as well. Scheme doesn't have them.  Common LISP requires
special forms to use them.

The problem with the given use case is that it lets every routine in
the call chain substitute it's own variable for the library parameter
you want to use, with no local indication that this is going
on. This makes bugs in dynamically scoped variables a PITA to find.

Given that it's a feature I don't want programmers using, I'd only be
willing to see it added to the language if you can show that it has no
overhead so long as you don't use it. I'm not sure that can be done.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-01 Thread Chris Rebert (cybercobra)
My personal favorite would be ruby's iterators and blocks.
Instead of writing a bunch of repetitive list comprehensions or
defining a bunch of utility functions, you just use the iterators
supported by container objects.
For instance,

[f(x) for x in y]

could be written in Ruby as

y.collect |x| do
  #body of f
end

You don't have to use a lambda or define f() externally.
Best of all, Ruby's containers come with many iterators for common
cases builtin.

Joseph Garvin wrote:
 As someone who learned C first, when I came to Python everytime I read
 about a new feature it was like, Whoa! I can do that?! Slicing, dir(),
 getattr/setattr, the % operator, all of this was very different from C.

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

 Here's my current candidate:

 So the other day I was looking at the language Lua. In Lua, you make a
 line a comment with two dashes:

 -- hey, this is a comment.

 And you can do block comments with --[[ and ---]].

 --[[
 hey
 this
 is
 a
 big
 comment
 --]]

 This syntax lets you do a nifty trick, where you can add or subtract a
 third dash to change whether or not code runs:

 --This code won't run because it's in a comment block
 --[[
 print(10)
 --]]

 --This code will, because the first two dashes make the rest a comment,
 breaking the block
 ---[[
 print(10)
 --]]

 So you can change whether or not code is commented out just by adding a
 dash. This is much nicer than in C or Python having to get rid of  or
 /* and */. Of course, the IDE can compensate. But it's still neat :)

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


Re: Favorite non-python language trick?

2005-07-01 Thread Mike Meyer
[Lots of quoted text left in...]

I started thinking about this, and realized that there was a way to do
what you wanted, with no execution time overhead, and without
providing ways to radically change the program behavior behind the
scenes.

Mike Meyer [EMAIL PROTECTED] writes:
 Shai [EMAIL PROTECTED] writes:

 Joseph Garvin wrote:

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

 1. Lisp's dynamically scoped variables (Perl has them, and calls them
 local, but as far as I've seen their use their is discouraged). These
 are global variables which are given time-local bindings. That is,
 structuring the syntax after what's used for globals,

 Perl started life with nothing but dynamically scoped variables. They
 added lexical scoping after they realized what a crock dynamic scoping
 was.

That's a bit harsher than I intended. I mean that having nothing but
dynamically scoped variables - like early Perl and LISP - is a
crock. I'll add that dynamic scoping as the default is a crock. But
you aren't asking for those.

 x=10
 def foo():
   # No need to define x as it is only read -- same as globals
   print x

 def bar():
   dynamic x
   x = 11
   foo()

 def baz():
   bar() # prints 11
   foo() # prints 10; the binding in bar is undone when bar exits

Here's the problem with that. Consider this script:

import foo
x = 10
def bar():
print x

foo.foogle(bar)

If foo.foogle includes dynamic x and then invokes bar, bar could
print anything. This makes the behavior of bar unpredictable by
examining the sourc, with no hint that that is going on.

 Given that it's a feature I don't want programmers using, I'd only be
 willing to see it added to the language if you can show that it has no
 overhead so long as you don't use it. I'm not sure that can be done.

Here's a proposal for dynamically bound variables that you should be
able to implement without affecting the runtime behavior of code that
doesn't use it.

Instead of dynamic meaning all references to the named variable(s)
will be dynamic until this function exits, have it mean the named
variable(s) will be dynamic in this function. Whether it should only
check local variables in the calling routines, check local + global,
or check for all free variables, is an open question.

I.e. - your example would be written:

x = 10
def foo():
dynamic x
print x

def bar():
x = 11
foo()

def baz():
bar()   # prints 11
foo()   # Possibly an error?

For my example above, bar would *always* print 10. Nothing that
foo.foogle did would change that. However, you could write:

import foo
def bar():
dynamic x
print x

foo.foogle(bar)

In this case, bar will print whatever foo.foogle sets x to - and it's
noted in the source to bar. This means that functions that don't
declare a dynamic variable can be compiled to the same code they are
compiled to now.

Would this version provide the functionality you wanted?

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-01 Thread BJörn Lindqvist
I like C++ templates so that you can ensure that a list only contain
items of one type. I also like the JMP instruction in x86 assembler,
you could do some nasty tricks with that.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-01 Thread Terry Reedy

Devan L [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 With the exception of reduce(lambda x,y:x*y, sequence), reduce can be
 replaced with sum, and Guido wants to add a product function.

The update function is not at all limited to sums and products, but can be 
any callable with the appropriate signature.  The new any() and all() 
functions are examples that use other updates.

Terry J. Reedy



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


Re: Favorite non-python language trick?

2005-06-30 Thread Paddy
Sadly, its not a solution that I'm after, but a particular toolkit that
can be used for solving that type of problem.

- Pad.

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


Re: Favorite non-python language trick?

2005-06-30 Thread Brian Elmegaard
Joseph Garvin [EMAIL PROTECTED] writes:

 I'm curious -- what is everyone's favorite trick from a non-python
 language? 

Metapost solution of linear equations:
x1+9=x2-8=2;

 And -- why isn't it in Python?

I'd like to know too.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-30 Thread Terry Hancock
On Wednesday 29 June 2005 10:51 pm, Paddy wrote:
 Joseph Garvin wrote:
   'm curious -- what is everyone's favorite trick from a non-python
   language? And -- why isn't it in Python?
 
 I use constraints programming at work, Check out System Verilog  or
 OZ/Mozart.
 
 It would be great if this style of programming could be added to
 Python.

Check out:
http://www.logilab.org/projects/python-logic/

In short, it has been already.

This is something pretty new to me, so I can't comment on how well
it would meet your expectations, but I see now that the site does mention
OZ/Mozart as comparables.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Favorite non-python language trick?

2005-06-30 Thread NickC
Steven D'Aprano wrote:
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;

 instead of:

 colour.red := 0; colour.blue := 255; colour.green := 0;

c = colour
c.red = 0; c.blue = 255; c.green = 0
del c # Not strictly needed, but limits the scope of c

When everything's a reference, the Pascal 'with' syntax doesn't gain
you anything over a single-letter variable name. As I recall, it's
handy in Pascal because record assignment has value semantics rather
than reference semantics.

Cheers,
Nick.

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


Re: Favorite non-python language trick?

2005-06-30 Thread Benji York
Terry Hancock wrote:
 http://www.logilab.org/projects/python-logic/

 This is something pretty new to me, so I can't comment on how well
 it would meet your expectations, but I see now that the site does mention
 OZ/Mozart as comparables.

I've used both, the logilab stuff is cool, but no where near the
maturity (or speed) of OZ/Mozart.  OTOH, I can actually get things
done with the logilab code.  But that might say more about me than
Mozart. :)
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-30 Thread [EMAIL PROTECTED]
If I had to choose one feature, I would like to see better support for
nested lexical scopes.  However, I imagine this is no easy trick to
add to the language.

 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

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


Re: Favorite non-python language trick?

2005-06-30 Thread Terry Reedy

Paddy [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Sadly, its not a solution that I'm after, but a particular toolkit that
 can be used for solving that type of problem.

Presuming this is an anwer to my comment about generators... I was pointing 
you more to the method used than the particular solutions.  Whether your 
constraint problems are similar enough, I have no idea.

Terry J. Reedy



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


Re: Favorite non-python language trick?

2005-06-30 Thread Terry Hancock
On Thursday 30 June 2005 10:21 am, [EMAIL PROTECTED] wrote:
 If I had to choose one feature, I would like to see better support for
 nested lexical scopes.  However, I imagine this is no easy trick to
 add to the language.

Doesn't that already happen in versions 2.2+?

What exactly do you mean by better support for nested lexical
scopes?  Can you give an example of something that doesn't work,
but should?

I'm just curious.  The whole question of lexical scoping seemed
a bit esoteric to me at the time --- I think I must instinctively
avoid situations where it causes trouble. The most important
exception would have to be the behavior of lambda and locally-defined
functions --- I still expect them to know the variables in the defining
function's namespace.  But I think that lexical scoping fixed this
so that they do, IIRC (I don't use them often, so I'm not so sure).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Favorite non-python language trick?

2005-06-30 Thread ncf
Hmm...I think it's time I do better justice to what I previously wrote.


http://www.artima.com/weblogs/viewpost.jsp?thread=98196

The above article was linked by Python's PEP...

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


Re: Favorite non-python language trick?

2005-06-30 Thread ncf
Sorry, I realized that shortly after my post =X

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


Re: Favorite non-python language trick?

2005-06-29 Thread Mandus
Sun, 26 Jun 2005 08:35:58 +0200 skrev Peter Otten:
 Steven D'Aprano wrote:

 On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote:
 
 Mandus wrote:
 
 By using the builtin reduce, I
 move the for-loop into the c-code which performs better.
 
 No. There is no hope of ever writing fast code when you do not actually
 measure its performance.
 
 Good grief! You've been spying on Mandus! How else could you possibly know
 that he doesn't measure performance? Are you running a key-logger on his
 machine? *wink*

 His mentioning reduce() as a performance panacea was a strong indication
 even without looking over his shoulders. He filled in some conditions in a
 later post, but [U]sing reduce ... performs better [than a for-loop] is
 just wrong.

Ok - so sometimes reduce() for convenience (nha, that's just me...),
sometimes for performance. In some cases clever use of map/reduce/etc.
have given a good speedup - say  4 times that of for-loops. But going to
C can give 10 to 100 times speed up over that again... So it depends how
important the performance is. Going to C/Fortran is always a bit more
hassel, while reduce is something you can stick in your interactive
session to finish the work rather before than after lunch :)

[snip]

 Isn't it reasonable to just say, I use join because it is faster than
 adding strings without being abused for invalid optimization?

 OK, I am making a guess: .join(strings) is more often faster than
 naive string addition than reduce() wins over a for-loop.

you're probably right.

 I don't think my pointed comment qualifies as abuse, by the way.

neither think I.


-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-29 Thread Paddy
Joseph Garvin wrote:
  'm curious -- what is everyone's favorite trick from a non-python
  language? And -- why isn't it in Python?

I use constraints programming at work, Check out System Verilog  or
OZ/Mozart.

It would be great if this style of programming could be added to
Python.

It is a declarative programming style
(http://en.wikipedia.org/wiki/Declarative_programming), in which you
can state what discrete values constrained values can take , say in a
list. Give a set of functions that must be true for the variables then
sit back and generate one or many sets of variable values that fit the
constraints.

The OZ homepage has an example for solving the eight queens problem:

http://www.mozart-oz.org/documentation/fdt/node25.html#section.scripts.queens

My use would be for testing. In the electronic design automation
fields, there are several proprietary languages with this feature, here
is an example written in Cadence's Specman 'e' language:
  http://www.asic-world.com/specman/specman_one_day2.html


Cheers, Paddy.

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


Re: Favorite non-python language trick?

2005-06-29 Thread Terry Reedy

Paddy [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 The OZ homepage has an example for solving the eight queens problem:

Buried in the generator test module (something like 
lib/test/test_generators.py) are solutions for both 8Queens and Knight's 
Tour.  You might find these of interest.

Terry J. Reedy



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


Re: Favorite non-python language trick?

2005-06-28 Thread Mike Meyer
Tom Anderson [EMAIL PROTECTED] writes:
 On Fri, 24 Jun 2005, Roy Smith wrote:
 Tom Anderson  [EMAIL PROTECTED] wrote:
 The one thing i really do miss is method overloading by parameter
 type. I used this all the time in java
 You do things like that in type-bondage languages
 I love that expression. I think it started out as 'bondage and
 discipline languages', which is even better. I'm going to start
 referring to python as a 'sluttily typed' language.

Since the user is the one bound with BD languages, they are clearly
tops. Which makes Python a bottom.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-28 Thread Ivan Van Laningham
Hi All--

Mike Meyer wrote:
 
 Since the user is the one bound with BD languages, they are clearly
 tops. Which makes Python a bottom.
 

Well, we certainly hope Python has a safe word.

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-27 Thread Steven D'Aprano
On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote:

 You need to differentiate
a = b = 1
 from
a = b == 1
 
 Okay, I see what you mean.  I can't ever recall having needed the
 second form, though.
 
 Of course, you could still do assignment like this:
 
 a, b = (1,)*2
 
 But I guess that's not exactly elegant. ;-)

In general that is not the same thing as a = b = obj.

py a, b = ([], [])
py a.append(1)
py b
[]
py a = b = []
py a.append(1)
py b
[1]


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-27 Thread Robert Kern
Steven D'Aprano wrote:
 On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote:
 
You need to differentiate
   a = b = 1
from
   a = b == 1

Okay, I see what you mean.  I can't ever recall having needed the
second form, though.

Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)
 
 In general that is not the same thing as a = b = obj.
 
 py a, b = ([], [])
 py a.append(1)
 py b
 []
 py a = b = []
 py a.append(1)
 py b
 [1]

What you wrote isn't, but what Terry wrote is.

In [1]: a, b = ([],)*2

In [2]: a.append(1)

In [3]: b
Out[3]: [1]

In [4]: a is b
Out[4]: True

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Favorite non-python language trick?

2005-06-27 Thread Tim Peters
[Terry Hancock]
 Probably the most pointless Python wart, I would think. The =/==
 distinction makes sense in C, but since Python doesn't allow assignments
 in expressions, I don't think there is any situation in which the distinction
 is needed.  Python could easily figure out whether you meant assignment
 or equality from the context, just like the programmer does.

That's what Python originally did, before release 0.9.6 (search
Misc/HISTORY for eqfix.py).  Even this is ambigous then:

a = b

Especially at an interactive prompt, it's wholly ambiguous then
whether you want to change a's binding, or want to know whether a and
b compare equal.

Just yesterday, I wrote this in a script:

lastinline = ci == ncs - 1

This:

lastinline = ci = ncs - 1

means something very different (or means something identical,
depending on exactly how it is Python could easily figure out what I
intended wink).

Of course strange rules could have resolved this, like, say, = means
assignment, unless that would give a syntax error, and then = means
equality.  Then

lastinline = ci = ncs - 1

would have been chained assignment, and something like

lastinline = (ci = ncs - 1)

would have been needed to get the intent of the current

lastinline = ci == ncs - 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-27 Thread Steve Jorgensen
On 24 Jun 2005 19:09:05 +0400, Sergei Organov [EMAIL PROTECTED] wrote:

Steven D'Aprano [EMAIL PROTECTED] writes:

 On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote:
 
  I'm curious -- what is everyone's favorite trick from a non-python 
  language? And -- why isn't it in Python?
 
 Long ago, I used to dabble in Forth. You could say, the entire Forth
 language was a trick :-) It was interesting to be able to define your own
 compiler commands, loop constructs and so forth.
 
 One of the things I liked in Pascal was the with keyword. You could
 write something like this:
 
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;
 
 instead of:
 
 colour.red := 0; colour.blue := 255; colour.green := 0;
 
 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.

... that quickly becomes quite messy:

 - When abused -

with A do begin
  .
  with B do begin
.
with C do begin
  x := y;
end;
  end;
end;

Like many features that can be helpful when used well, and harmful when used
poorly, it's not a simple question whether it should be in any given language.
It also makes sense to consider whether other features already in the language
can fill the same need (though I don't know Python well enough to address that
yet).  Even though I like With in VB and use it often, I always consider its
use a warning that perhaps that code should be factored into the class
somehow.

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


Re: Favorite non-python language trick?

2005-06-27 Thread GodFoca
 if a.value == True:
 return a

 if not database.connect == error:
 database.query(q)

Yeah, yeah, I know that :-)
What I mean is that most of the time I find the code more readable (I
know that more readable code ain't better code, but it helps when you
work with other people...).

 unless seems to become while not, as opposed to if not. Should be
 more consistent.

My mistake :-S
The comment in the code was erroneous, I shouldn't write messages to
the list while asleep ^_^

'unless' works as 'if not', not as 'while not'. Sorry for that :-)

Anyway, it does improve readability. I know that it doesn't necessarily
makes code better, but it's a nice trick that I like :-)

Other nice thing about ruby is declaring regexps as /regexp/ rather
than having to re.compile(regexp), and having a built-in operator to
match against them (of course, as everything in ruby, overloadable in
each class :-))

-NIcolas

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


Re: Favorite non-python language trick?

2005-06-26 Thread Peter Otten
Steven D'Aprano wrote:

 On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote:
 
 Mandus wrote:
 
 By using the builtin reduce, I
 move the for-loop into the c-code which performs better.
 
 No. There is no hope of ever writing fast code when you do not actually
 measure its performance.
 
 Good grief! You've been spying on Mandus! How else could you possibly know
 that he doesn't measure performance? Are you running a key-logger on his
 machine? *wink*

His mentioning reduce() as a performance panacea was a strong indication
even without looking over his shoulders. He filled in some conditions in a
later post, but [U]sing reduce ... performs better [than a for-loop] is
just wrong.

 For the record, perhaps now is a good time to mention that even Guido
 recommended the use of map, filter and reduce in some circumstances:

Personally I wouldn't rely on authority when I can measure without much
hassle. And the lesson I take from Guido's essay is rather how he got to
his conclusions than what his actual findings were. After all, Python may
have advanced a bit since he wrote the text.

 Do we really need to profile our code every single time to know this?

No. Only if we care about the performance of a particular piece. And if we
do we are sometimes in for a surprise.

 Isn't it reasonable to just say, I use join because it is faster than
 adding strings without being abused for invalid optimization?

OK, I am making a guess: .join(strings) is more often faster than
naive string addition than reduce() wins over a for-loop.

I don't think my pointed comment qualifies as abuse, by the way.

Peter

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


Re: Favorite non-python language trick?

2005-06-26 Thread Konstantin Veretennicov
On 25 Jun 2005 12:17:20 -0700, George Sakkis [EMAIL PROTECTED] wrote:
 If they go to itertools, they can simply be:
 
 def map(f, *iterables):
 return list(imap(f,*iterables))
 
 def filter(f, seq):
 return list(ifilter(f,seq))

 from itertools import ifilter
 def filter(f, seq):
... return list(ifilter(f,seq))
 filter(str.isalpha, 'not quite!')
['n', 'o', 't', 'q', 'u', 'i', 't', 'e']
 __builtins__.filter(str.isalpha, 'not quite!')
'notquite'

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


Re: Favorite non-python language trick?

2005-06-26 Thread Terry Hancock
On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
 Hallöchen!
 However, then you must forbid a=b=1 for assigning to two variables
 at the same time.

Why?  It's already handled as an exception in the syntax.

In C, what you say makes sense, because b=1 is an expression as
well as an assignment. But I don't think Python reads it that way -- it 
just has code to recognize multiple assignment as a statement. I think
I remember reading that in the Language Reference or something.

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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

Re: Favorite non-python language trick?

2005-06-26 Thread Robert Kern
Terry Hancock wrote:
 On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
 
Hallöchen!
However, then you must forbid a=b=1 for assigning to two variables
at the same time.
 
 Why?  It's already handled as an exception in the syntax.
 
 In C, what you say makes sense, because b=1 is an expression as
 well as an assignment. But I don't think Python reads it that way -- it 
 just has code to recognize multiple assignment as a statement. I think
 I remember reading that in the Language Reference or something.

You need to differentiate

   a = b = 1

from

   a = b == 1

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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

Re: Favorite non-python language trick?

2005-06-26 Thread Roy Smith
Steven D'Aprano [EMAIL PROTECTED] wrote:
 Using := and = for assignment and equality is precisely as stupid as using
 = and == for assignment and equality.

On the other hand, == is easier to type than := (two taps on the same key 
vs two different keys, and at least on a US/English keyboard, no shift key 
required).  Not only that, but := is more likely to be turned into some 
bizarre smiley face by brain-dead IM clients :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-26 Thread George Sakkis
Konstantin Veretennicov [EMAIL PROTECTED] wrote:

  On 25 Jun 2005 12:17:20 -0700, George Sakkis [EMAIL PROTECTED] wrote:
  If they go to itertools, they can simply be:
 
  def map(f, *iterables):
  return list(imap(f,*iterables))
 
  def filter(f, seq):
  return list(ifilter(f,seq))

  from itertools import ifilter
  def filter(f, seq):
 ... return list(ifilter(f,seq))
  filter(str.isalpha, 'not quite!')
 ['n', 'o', 't', 'q', 'u', 'i', 't', 'e']
  __builtins__.filter(str.isalpha, 'not quite!')
 'notquite'

Oops ! I've used filter only with lists and didn't know that it
preserves the type for strings and tuples. Here's a (hopefully) correct
version:

def filter(f,seq):
it = ifilter(f,seq)
if isinstance(seq,basestring):
return ''.join(it)
elif isinstance(seq,tuple):
return tuple(it)
else:
return list(it)


By the way, the documentation of filter is unclear on what is the
return type if seq is a subclass of list, tuple, str, or unicode; is it
type(seq) or the base builtin type ? Let's see:

def subclassFactory(cls):
return type(Dummy_ + cls.__name__, (cls,),
{'__new__' : lambda self, seq: cls.__new__(self, seq)})

baseToSub = dict([(base,subclassFactory(base))
 for base in list,tuple,str,unicode])

f = lambda x: x.lower()
for Base,Sub in baseToSub.iteritems():
assert type(__builtins__.filter(f, Sub('lowerUPPERCap'))) is Base

for Base,Sub in baseToSub.iteritems():
for cls in Base,Sub:
args = (f, cls('lowerUPPERCap'))
assert filter(*args) == __builtins__.filter(*args)


George

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


Re: Favorite non-python language trick?

2005-06-26 Thread GodFoca
 I'm curious -- what is everyone's favorite trick from a non-python
 language? And -- why isn't it in Python?

Hmm... I used to be quite the fan of Python, yet not long ago I met
Ruby and fell in love almost instantly. Some of the features I like the
most:

- statement modifiers:

 return a if a.value == true
 database.query(q) unless database.connect == error
(etc)

- unless as if not, since it gives nicer code to read

 unless false then print 1 # this prints 1 forever

- iterators, such as times (already mentioned)

- 'case'

 case var
when 3 then do_sth
when 4 then do_sth_else
# etc...
 end

- everything returns a value, so you can do:

 foo = case foo2
when 1 then yadda_yadda
when 2 then blah_blah
# etc
 end

And when foo2 == 2 then blah_blah gets executed and returned as the
'case' return value, thus assigning foo the value that results from
evaluating blah_blah

And some more, but those are the ones I like the best and python
doesn't have :-)

- greetings -
Nicolas

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


Re: Favorite non-python language trick?

2005-06-26 Thread Devan L
 return a if a.value == true
 database.query(q) unless database.connect == error
(etc)

if a.value == True:
return a

if not database.connect == error:
database.query(q)

Trading two words for one word doesn't necessarily make the code
better.

 unless false then print 1 # this prints 1 forever
while not False:
print 1

unless seems to become while not, as opposed to if not. Should be
more consistent.

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


Re: Favorite non-python language trick?

2005-06-26 Thread Bengt Richter
On Sun, 26 Jun 2005 14:30:15 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:

On Sat, 25 Jun 2005 23:08:10 +, Bengt Richter wrote:

[...]
 
 The single line replacing
  
  with colour do begin
  red := 0; blue := 255; green := 0;
  end;
  
 follows:
   vars(color).update(red=0, blue=255, green=0)


The point is that a hypothetical with block would have to allow
arbitrary access to dotted names: getting, setting, deletion, and method
calling, not just one very limited form of keyword assignment.
Point taken.

I understand how to manipulate __dict__ as an more complicated (dare I say
obfuscated?) way of assigning to object attributes.

Yes, it's a bit obfuscated.

[snip]

 We can clear those attributes from the instance dict:
 vars(colour).clear()
 vars(colour)
 {}

Which has the unfortunate side effect of also destroying any other
instance attributes.
You wouldn't do something unfortunate, would you? ;-)
I just wanted to clear them all at that point in the interaction.


you might do this:

with myobject:
# read a class attribute
print .__class__.myattribute
# set an instance attribute
.widget.datapoints[.collector] = .dispatcher(.widget.current_value)

 
 def mywith(o=myobject):
  # read a class attribute
  print o.__class__.myattribute
  # set an instance attribute
  o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value)
 mywith()

[snip]

 Is a one-character prefix to the dot objectionable?

That's a good workaround, subject to namespace pollution issues, and one
that I'm aware of. Although do you really want to be creating a unique
function definition every time you want to use the with idiom?
The only thing, ISTM, that would not also be unique in the with construct
is the function name, and you snipped the anonymnous def version that would
eliminate that. The main question in my mind would be binding of non-leading-dot
names. Would they work as in the suite of an if (i.e., binding in the same 
scope)
or as in a function with a new local scope that disappears on exit?

A function solves the alias name pollution problem, but prevents rebinding
anything external except explicitly declared globals, and closure cell vars
can't be rebound currently.

I'm not about to stop using Python because of the lack of Pascal-like
with blocks. It is a nice feature to have, but I'm aware that Guido
prefers explicit to implicit and with is extremely implicit. 

I wonder what happens when you have multiple withs, e.g.,

   with obj_a:
   .x = 1
   with obj_b:
   .x = 2
   .y = 3

(I guess you would have to have a stack with only the latest with effective).
whereas a simple aliasing syntax like

(a=obj_a, b=obj_b):
a.x = 1
b.x = 2
b.y = 3
  
is unambigous and concise and the scope of the namescan be limited
to prevent name pollution at compile time.

OTOH, what should
(a=obj_a):
a = 123 # XXX ??
mean? Should it mean obj_a=123 and rebind in that scope,
like a macro substitution of names at compile time?
I guess the corresponding with thing would be
with obj_a:
. = 123




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


Re: Rebindings [was Re: Favorite non-python language trick?]

2005-06-26 Thread Bengt Richter
On Sun, 26 Jun 2005 14:36:42 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:

On Sat, 25 Jun 2005 23:08:10 +, Bengt Richter wrote:

Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?

 I agree, but I think := would be nice in python for RE-binding an existing
 binding, wherever it is seen from the local context. Thus you could
 write
 
 def foo(): x:=123
oops, for below example, needs global declaration
   def foo():
   global x
   x:=123  #note that x:=123 searches outward through nested scopes,
   #not including globals unless explicitly declared, whereas
   # x=456 would always {re}bind the global x, as usual with a global x 
declared.
 
 and
x = 456
def bar():
x = 789
foo()  # finds and rebinds local x
print x
bar() # - 123
print x # - 456
foo()  # finds and rebinds the global x
oops, not so, unless foo has correction above
print x # - 123
 
 but
del x
foo()  #- NameError exception, can't find any x to rebind
 
 hm, wandered a bit OT there, ;-/

Given how much the use of global variables are discouraged, is it a
good idea to allow even more inter-namespace interactions?

I forgot some of my previous thoughts on this. It's not as wild as it appears 
;-)

I forgot to mention that of course a symbol found in __builtins__ by way
of the usual default lookup should not be rebound. And only globals explicitly
declared should be rebound (error in code above, since foo doesn't have global 
x).
So that limits it to the local scope and nested scopes and declared globals not
preempted by nearer nested scope variable names.

This is motivated by currently not being able to rebind a closure variable in
a nested scope, and the requirement of pre-existence within a limited range of
namespaces that can (I think ;-) be statically analyzed for is meant to prevent
new accidental collision problems.

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


Re: Favorite non-python language trick?

2005-06-26 Thread Terry Hancock
On Sunday 26 June 2005 06:11 am, Robert Kern wrote:
 Terry Hancock wrote:
  On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:
 However, then you must forbid a=b=1 for assigning to two variables
 at the same time.
 
 You need to differentiate
a = b = 1
 from
a = b == 1

Okay, I see what you mean.  I can't ever recall having needed the
second form, though.

Of course, you could still do assignment like this:

a, b = (1,)*2

But I guess that's not exactly elegant. ;-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Favorite non-python language trick?

2005-06-26 Thread Robert Kern
Terry Hancock wrote:
 On Sunday 26 June 2005 06:11 am, Robert Kern wrote:
 
Terry Hancock wrote:

On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote:

However, then you must forbid a=b=1 for assigning to two variables
at the same time.

You need to differentiate
   a = b = 1
from
   a = b == 1
 
 Okay, I see what you mean.  I can't ever recall having needed the
 second form, though.

I use it all the time with Numeric's rich comparisons.

   mask = some_arr == 999

 Of course, you could still do assignment like this:
 
 a, b = (1,)*2
 
 But I guess that's not exactly elegant. ;-)

Ya think?  :-)

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Favorite non-python language trick?

2005-06-25 Thread William Heymann
On Friday 24 June 2005 02:53 pm, D H wrote:

 Again, you are splitting hairs.  His point still stands that it is not
 possible to do method overloading in python (unless you use decorator
 hacks).  It may be possible to add this feature when type declarations
 and type checking are added to a future version of python.

Decorators are actually a syntax hack remember. Everything you can do in a 
decorator you could do with python before since they work via nested scopes. 
It is easy to write wrapper methods and I use them for many purposes but not 
for type checking. 

Wrapper methods are very useful to take out common checking code. The checking 
of conditions does not really belong in the caller (the caller could forget), 
it does not really belong in the called function since that is not that 
functions purpose but putting it in a wrapper and having it wrap the called 
function sure gives a nice seperation and makes life simpler.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Mandus
Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson:
 On Fri, 24 Jun 2005, Joseph Garvin wrote:

 Claudio Grondi wrote:

 So far we've got lisp macros and a thousand response's to the lua trick. 
 Anyone else have any actual non-python language tricks they like?

 Higher-order functions like map, filter and reduce. As of Python 3000, 
 they're non-python tricks. Sigh - i guess it's time for me to get to know 
 list comprehensions a bit better.


u-huu... I wasn't aware of that. It is really a consensus on this; that
removing map, filter, reduce is a good thing? It will render a whole lot
of my software unusable :(

Sure, I guess I can port most of it to list comprehensions, but
reduce/map are so much nicer.


-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Robert Kern
Mandus wrote:
 Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson:

Higher-order functions like map, filter and reduce. As of Python 3000, 
they're non-python tricks. Sigh - i guess it's time for me to get to know 
list comprehensions a bit better.
 
 u-huu... I wasn't aware of that. It is really a consensus on this; that
 removing map, filter, reduce is a good thing? It will render a whole lot
 of my software unusable :(

Python 3000 (or Python 3.0) is the designated we're going to break 
backwards compatibility release. Your code won't necessarily work even 
if map, filter, and reduce are kept.

Guido's current plans, such as they are, with links to his reasoning can 
be found here:

http://www.python.org/peps/pep-3000.html
http://wiki.python.org/moin/Python3.0

Of course, there's no timetable for when this change will take place. 
map, filter, and reduce are safe for quite some time.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Favorite non-python language trick?

2005-06-25 Thread Roy Smith
Steve [EMAIL PROTECTED] wrote:
 One thing that I miss every once in a while is pre-processing.

There are so many things wrong with preprocessing, at least if you're 
thinking of the way C/C++ implements it (cpp).  Cpp a number of things.

1) It does file inclusion.  Pythons import serves that purpose and does a 
better job of it.

2) It defines constants.  A simple assignment in Python does that just fine 
(and in C++, enums and const variables do it).

3) It does conditional compilation.  Just use if in Python.  You can even 
enclose function definitions inside an if body.

4) It lets you do macro expansion.  Just write a function in Python.

The big problem with cpp is that it essentially lets you define a whole new 
language.  The code that is compiled/executed isn't anything like the code 
that you see on the screen.  This can lead to debugging nightmares.

BTW, if you *really* want to, you can use cpp with Python.  For example, I 
just wrote the following little program.  It's in a language I'll call 
Prethon, for lack of a better name.  It comes in two files:

---
Roy-Smiths-Computer:play$ cat pp.h
#define foo(bar) mySillyFunction(bar, 0)

def mySillyFunction(x, y):
x / y
---

and

---
Roy-Smiths-Computer:play$ cat pp.pre
#include pp.h

foo(37)
---

I can use cpp to turn this into a Python program by doing cpp pp.pre  
pp.py.  When I run that, I get a run-time exception and a stack trace:

Roy-Smiths-Computer:play$ python pp.py
Traceback (most recent call last):
  File pp.py, line 13, in ?
mySillyFunction(37, 0)
  File pp.py, line 10, in mySillyFunction
x / y
ZeroDivisionError: integer division or modulo by zero

This is really confusing.  I'm looking at my source code and don't see any 
calls to mySillyFunction().  In the trivial example I've given, it's 
obvious that it's a #define in pp.h, but in a real-life example, there can 
be hundreds or thousands of included files in a project, scattered about 
all sorts of different directories you may not even know exist.  Trying to 
figure out what's going on becomes a nightmare.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Konstantin Veretennicov
On 6/25/05, Mandus [EMAIL PROTECTED] wrote:
 It is really a consensus on this; that
 removing map, filter, reduce is a good thing? It will render a whole lot
 of my software unusable :(

I think you'll be able to use from __past__ import map, filter,
reduce or something like that :) They don't have to be built-in.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Lee Harr
 Higher-order functions like map, filter and reduce. As of Python 3000, 
 they're non-python tricks. Sigh - i guess it's time for me to get to know 
 list comprehensions a bit better.



Couldnt there just be a functional module ?...

from functional import map, filter, reduce
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Fri, 24 Jun 2005 14:29:37 -0700, James wrote:

 Interesting thread ...
 
 1.) Language support for ranges as in Ada/Pascal/Ruby
 1..10 rather than range(1, 10)

What advantages do Pascal-like for loops give over Python for loops?

The only two I can think of are trivial:

(1) the Pascal-like for loop is six characters shorter to type:

for i = 1 to 10:# 16 chars
for i in range(1, 10):  # 22 chars

(2) for very large ranges, you don't have to hold the entire list of
integers in memory. But you can use xrange() instead of range(), which
also doesn't hold the entire list in memory.


 2.) Contracts

Explain please.
 
 3.) With

Explain please.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote:

 On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote:
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;

 instead of:

 colour.red := 0; colour.blue := 255; colour.green := 0;

 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.
 
 class color:# americanized
   red = 0
   blue = 255
   green = 0

The problem is, you have made colour (returning to English spelling
instead of foreign) into a class. If you need two colour variables, you
have to duplicate the code for the class (perhaps only changing the
numeric constants. You can't even make instances from the class, because
they all share the same RGB values, which is pretty useless if they are
meant to represent different colours.

 
 Less typing than pascal. 

You have missed the point. I'm not comparing Python vs Pascal for
creating records representing RBG values. I'm talking about a Pascal
feature that reduced typing by allowing you to use an implicit record.
Here is one possible way you might use such a feature as a Python idiom,
letting with specify an implicit object. Instead of doing this:

# read a class attribute
print myobject.__class__.myattribute  
# set an instance attribute
myobject.widget.datapoints[myobject.collector] \
= myobject.dispatcher(myobject.widget.current_value)

you might do this:

with myobject:
# read a class attribute
print .__class__.myattribute
# set an instance attribute
.widget.datapoints[.collector] = .dispatcher(.widget.current_value)

 Also avoids those stupid little colons.

Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?


-- 
Steven.


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


Re: Favorite non-python language trick?

2005-06-25 Thread Konstantin Veretennicov
On 6/25/05, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Fri, 24 Jun 2005 14:29:37 -0700, James wrote:
  2.) Contracts
 
 Explain please.

James probably meant Eiffel's Design by Contract. My favourite Python
implementation is Terence Way's http://www.wayforward.net/pycontract/ 
;-)

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


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote:

 On 6/25/05, Mandus [EMAIL PROTECTED] wrote:
 It is really a consensus on this; that
 removing map, filter, reduce is a good thing? It will render a whole lot
 of my software unusable :(
 
 I think you'll be able to use from __past__ import map, filter,
 reduce or something like that :) They don't have to be built-in.

More likely they will be moved to something like itertools than __past__.

Or just define them yourself:

def map(f, seq):
return [f(x) for x in seq]

def filter(p, seq):
return [x for x in seq if p(x)]

def reduce(f, seq, zero):
r = zero
for x in seq: r = f(r, x)
return r

-- 
Steve.


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


Re: Favorite non-python language trick?

2005-06-25 Thread Konstantin Veretennicov
On 6/25/05, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote:
 
  On 6/25/05, Mandus [EMAIL PROTECTED] wrote:
  It is really a consensus on this; that
  removing map, filter, reduce is a good thing? It will render a whole lot
  of my software unusable :(
 
  I think you'll be able to use from __past__ import map, filter,
  reduce or something like that :) They don't have to be built-in.
 
 More likely they will be moved to something like itertools than __past__.
 
 Or just define them yourself:
 
 def map(f, seq):
 return [f(x) for x in seq]
 
 def filter(p, seq):
 return [x for x in seq if p(x)]
 
 def reduce(f, seq, zero):
 r = zero
 for x in seq: r = f(r, x)
 return r

FWIW, these don't exactly reproduce behaviour of current built-ins.
Filter, for instance, doesn't always return lists and map accepts more
than one seq... Just my $.02.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Tom Anderson
On Fri, 24 Jun 2005, Roy Smith wrote:

 Tom Anderson  [EMAIL PROTECTED] wrote:

 The one thing i really do miss is method overloading by parameter type. 
 I used this all the time in java

 You do things like that in type-bondage languages

I love that expression. I think it started out as 'bondage and discipline 
languages', which is even better. I'm going to start referring to python 
as a 'sluttily typed' language.

 like Java and C++ because you have to.  Can you give an example of where 
 you miss it in Python?

No. I don't generally go around keeping a list of places where i miss 
particular features or find particular warts irritating. Still, my 
medium-term memory is not completely shot, so i assume i haven't missed it 
much in the last couple of days!

 If you want to do something different based on the type of an argument, 
 it's easy enough to do:

 def foo (bar):
if type(bar) == whatever:
   do stuff
else:
   do other stuff

 replace type() with isistance() if you prefer.

Yeah, i'm well aware that this is possible - what it's not is a clean 
solution. If i was into writing boilerplate, i'd be using C. Also, this 
gets really nasty if you want to overload on multiple variables.

Also, it actually falls down really badly in combination with duck typing 
- you can't use isinstance to ask if an object looks like a file, for 
example, only if it really is a file. Sure, you can do a bunch of hasattrs 
to see if it's got the methods it should have, but that doesn't tell you 
for certain it's a file, and it's a pain in the arse to write. In a typed 
language, you'd just ask if it implemented the Channel (for example) 
interface.

 No, it's not really possible in a typeless language,

 Python is not typeless.  It's just that the types are bound to the 
 objects, not to the containers that hold the objects.

No. Types are properties of variables; the property that objects have is 
called class. Python has classes but not types. I realise that many, even 
most, people, especially those using typeless languages like python or 
smalltalk, use the two terms interchangeably, but there's a real and 
meaningful distinction between them. I may be the last person alive who 
thinks it's an important distinction, but by god i will die thinking it. 
So let's recognise that we have slightly different terminologies and not 
argue about it!

tom

-- 
Why do we do it? - Exactly!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Tom Anderson
On Sat, 25 Jun 2005, Konstantin Veretennicov wrote:

 On 6/25/05, Mandus [EMAIL PROTECTED] wrote:

 It is really a consensus on this; that removing map, filter, reduce is 
 a good thing? It will render a whole lot of my software unusable :(

 I think you'll be able to use from __past__ import map, filter,
 reduce or something like that :)

from __grumpy_old_bastard_who_cant_keep_up__ import map

:)

tom

-- 
Why do we do it? - Exactly!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread George Sakkis
Konstantin Veretennicov [EMAIL PROTECTED] wrote:

 On 6/25/05, Steven D'Aprano [EMAIL PROTECTED] wrote:
  On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote:
 
   On 6/25/05, Mandus [EMAIL PROTECTED] wrote:
   It is really a consensus on this; that
   removing map, filter, reduce is a good thing? It will render a whole lot
   of my software unusable :(
  
   I think you'll be able to use from __past__ import map, filter,
   reduce or something like that :) They don't have to be built-in.
 
  More likely they will be moved to something like itertools than __past__.
 
  Or just define them yourself:
 
  def map(f, seq):
  return [f(x) for x in seq]
 
  def filter(p, seq):
  return [x for x in seq if p(x)]
 
  def reduce(f, seq, zero):
  r = zero
  for x in seq: r = f(r, x)
  return r

 FWIW, these don't exactly reproduce behaviour of current built-ins.
 Filter, for instance, doesn't always return lists and map accepts more
 than one seq... Just my $.02.

 - kv

If they go to itertools, they can simply be:

def map(f, *iterables):
return list(imap(f,*iterables))

def filter(f, seq): 
return list(ifilter(f,seq))

George

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


Re: Favorite non-python language trick?

2005-06-25 Thread Mandus
Sun, 26 Jun 2005 04:36:51 +1000 skrev Steven D'Aprano:
 On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote:

 On 6/25/05, Mandus [EMAIL PROTECTED] wrote:
 It is really a consensus on this; that
 removing map, filter, reduce is a good thing? It will render a whole lot
 of my software unusable :(
 
 I think you'll be able to use from __past__ import map, filter,
 reduce or something like that :) They don't have to be built-in.

 More likely they will be moved to something like itertools than __past__.

 Or just define them yourself:

 def map(f, seq):
 return [f(x) for x in seq]

 def filter(p, seq):
 return [x for x in seq if p(x)]

 def reduce(f, seq, zero):
 r = zero
 for x in seq: r = f(r, x)
 return r

sure - that will be possible. But the main point (for me) is to avoid
the horrible slow for-loop in python (reduce...). By using the builtin reduce, I
move the for-loop into the c-code which performs better. 

map and filter with list-comprehensions is probably ok - I use
list-comprehensions a lot, but somehow like the syntax of map/filter
better.

When it comes to lambdas, I am not so sure. I use them all the time, and
I will certainly miss them, and I have used lambdas in ways which at
least take som tinkering to translate to normal def's (or rather
closures). But I am not sure yet whether I have cases which are
impossible to translate (hey, nothing is impossible, some things just
take a bit more time).

Oh, and by the way, I use python to solve PDEs :)

But as someone else said, this will take some time. And I can always put
the c-function back in my self when that time comes.

Another important point, which it seems Guido does not fancy very much,
is that Python can be an ok functional style language for those who like
it. I very much enjoy the concept of using different programming styles
within the same language. It is mostly a convenience - I admit that -
but it makes me more productive. I'll be very sorry if we take that away
from python.

Maybe I am to late to change Guido on this - but if we are many, maybe
we can!

-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Mandus
Sat, 25 Jun 2005 16:06:57 GMT skrev Lee Harr:
 Higher-order functions like map, filter and reduce. As of Python 3000, 
 they're non-python tricks. Sigh - i guess it's time for me to get to know 
 list comprehensions a bit better.



 Couldnt there just be a functional module ?...

 from functional import map, filter, reduce

but lambda is grammar, so probably not so easy to import?


-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Devan L
Why overload when you can use class methods?

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


Re: Favorite non-python language trick?

2005-06-25 Thread Peter Otten
Mandus wrote:

 By using the builtin reduce, I
 move the for-loop into the c-code which performs better.

No. There is no hope of ever writing fast code when you do not actually
measure its performance.

Peter

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


Re: Favorite non-python language trick?

2005-06-25 Thread Nicolas Fleury
Steven D'Aprano wrote:
 One of the things I liked in Pascal was the with keyword. You could
 write something like this:
 
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;
 
 instead of:
 
 colour.red := 0; colour.blue := 255; colour.green := 0;
 
 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.
 

With PEP343 (I guess in Python 2.5), you will be able to do something like:
with renamed(colour) as c:
 c.red = 0; c.blue = 255; c.green = 0

I think however it is bad.  Better solutions to me would be:

colour.setRgb(0, 255, 0)

or

c = myVeryLongNameColour
c.red = 0; c.blue = 255; c.green = 0

Regards,
Nicolas

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


Re: Favorite non-python language trick?

2005-06-25 Thread Mandus
Sat, 25 Jun 2005 21:30:26 +0200 skrev Peter Otten:
 Mandus wrote:

 By using the builtin reduce, I
 move the for-loop into the c-code which performs better.

 No. There is no hope of ever writing fast code when you do not actually
 measure its performance.

I do.

-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Mandus
25 Jun 2005 13:15:16 -0700 skrev Devan L:
 But by using the builtin reduce, you need to specify a function, which
 probably slows it down more than any speed-up from the loop in C.

Sounds reasonable, but not always the case, especially when dealing with
numpy arrays. At least that what some of my test shows. But then I
should probably write c-functions that deals with the numeric arrays
anyway. 

Besides, functions like 'operator.add' is also in c, maybe that helps.

But I admit it's not a perfect example.

-- 
Mandus - the only mandus around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-25 Thread Robert Kern
Devan L wrote:
 But by using the builtin reduce, you need to specify a function, which
 probably slows it down more than any speed-up from the loop in C.

Not if the function is from an extension module. For some applications, 
this can be quite common.

Of course, in a Python 3000 world, nothing stops anyone from using their 
own extension module implementing map, filter, and reduce if they really 
want to. TSBOOOWTDI in the language/stdlib, but it shouldn't stop anyone 
from using other ways to do it that aren't in the stdlib if the 
tradeoffs are right for them.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Favorite non-python language trick?

2005-06-25 Thread Bengt Richter
On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:

On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote:

 On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote:
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;

 instead of:

 colour.red := 0; colour.blue := 255; colour.green := 0;

 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.
How do you like the following?
  color = type('',(),{})() # an instance that will accept attributes
  vars(color)
 {}

The single line replacing
 
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;
 
follows:
  vars(color).update(red=0, blue=255, green=0)

which sets all the attributes:
  vars(color)
 {'blue': 255, 'green': 0, 'red': 0}
  color.blue
 255
  color.red
 0
  color.green
 0

Of course, I defined a class on the fly above, so I could have given it defaults
as class variables (using English spelling ;-) :

  colour = type('Colour',(),dict(red=0,blue=255,green=0))() # an instance 
  with defaults
  vars(colour)
 {}
Which don't show up in the instance dict, but do show up as attributes:
  colour.red
 0
  colour.green
 0
  colour.blue
 255

Then we can update the instance dict that holds its attributes:
 vars(colour).update(red=111,green=222,blue=333)

And they show up, shadowing the class vars
 vars(colour)
{'blue': 333, 'green': 222, 'red': 111}

You can do one attribute this way:
 vars(colour).update(red='RED')
 vars(colour)
{'blue': 333, 'green': 222, 'red': 'RED'}

though this is obviously more concise:
 colour.green = 'GREEN'
 vars(colour)
{'blue': 333, 'green': 'GREEN', 'red': 'RED'}


The class vars are still there, even though we don't have a local name binding 
for the class:

  map(vars(type(colour)).__getitem__, 'red green blue'.split())
 [0, 0, 255]

The instance is separate:
  vars(colour)
 {'blue': 333, 'green': 'GREEN', 'red': 'RED'}

We can clear those attributes from the instance dict:
 vars(colour).clear()
 vars(colour)
{}

And then they don't shadow the class vars, so getting attributes make the class 
vars show again:
 [getattr(colour, c) for c in 'red green blue'.split()]
[0, 0, 255]

Or:
  map(colour.__getattribute__, 'red green blue'.split())
 [0, 0, 255]

Actually, you could make that a few characters shorter using a temporary short 
name to make
a kind of with inside a list comprehension:
  [[c.red, c.green, c.blue] for c in [colour]][0]
 [0, 0, 255]

Though list comprehensions leak bindings:
  c
 __main__.Colour object at 0x02F8FFCC

Which generator expressions don't:
  del c
  list(([c.red, c.green, c.blue] for c in [colour]))[0]
 [0, 0, 255]
  c
 Traceback (most recent call last):
   File stdin, line 1, in ?
 NameError: name 'c' is not defined


Or we can get the pairs and build a dict:
 [(c,getattr(colour, c)) for c in 'red green blue'.split()]
[('red', 0), ('green', 0), ('blue', 255)]
 dict([(c,getattr(colour, c)) for c in 'red green blue'.split()])
{'blue': 255, 'green': 0, 'red': 0}

Of course, rgb is usually ordered, so why not

  colour = type('Colour',(),dict(rgb=(0,255,0)))() # an instance with 
  default rgb
  vars(colour)
 {}
  colour.rgb
 (0, 255, 0)
  colour.rgb = 111,222,333
  vars(colour)
 {'rgb': (111, 222, 333)}
  colour.rgb
 (111, 222, 333)
  type(colour).rgb
 (0, 255, 0)


 
 class color:# americanized
   red = 0
   blue = 255
   green = 0

The problem is, you have made colour (returning to English spelling
instead of foreign) into a class. If you need two colour variables, you
have to duplicate the code for the class (perhaps only changing the
numeric constants. You can't even make instances from the class, because
they all share the same RGB values, which is pretty useless if they are
meant to represent different colours.

 
 Less typing than pascal. 

You have missed the point. I'm not comparing Python vs Pascal for
creating records representing RBG values. I'm talking about a Pascal
feature that reduced typing by allowing you to use an implicit record.
Here is one possible way you might use such a feature as a Python idiom,
letting with specify an implicit object. Instead of doing this:

# read a class attribute
print myobject.__class__.myattribute  
# set an instance attribute
myobject.widget.datapoints[myobject.collector] \
= myobject.dispatcher(myobject.widget.current_value)

you might do this:

with myobject:
# read a class attribute
print .__class__.myattribute
# set an instance attribute
.widget.datapoints[.collector] = .dispatcher(.widget.current_value)


def mywith(o=myobject):
 # read a class attribute
 print o.__class__.myattribute
 # set an instance attribute
 o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value)
mywith()

Or if we had a lambda-replacing anonymous def permitting full suites:
(def(o=myobject):
 # read a class attribute
 print o.__class__.myattribute
 # set an instance attribute
 

Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 19:23:18 +, Mandus wrote:

 Sat, 25 Jun 2005 16:06:57 GMT skrev Lee Harr:
 Higher-order functions like map, filter and reduce. As of Python 3000, 
 they're non-python tricks. Sigh - i guess it's time for me to get to know 
 list comprehensions a bit better.



 Couldnt there just be a functional module ?...

 from functional import map, filter, reduce
 
 but lambda is grammar, so probably not so easy to import?


from __future__ import something can change the compile-time behaviour
of Python, so it is possible.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Terry Reedy

Mandus [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson:
 On Fri, 24 Jun 2005, Joseph Garvin wrote:
 Higher-order functions like map, filter and reduce. As of Python 3000,
 they're non-python tricks. Sigh - i guess it's time for me to get to 
 know
 list comprehensions a bit better.


 u-huu... I wasn't aware of that. It is really a consensus on this; that
 removing map, filter, reduce is a good thing? It will render a whole lot
 of my software unusable :(

In his State of Python 2005 address, Guido estimated 1/2 +1, 1/4 +/-0, 
1/4 -1 on this.  So majority of those with opinion, not 'consensus'.  Then 
there is his vote...

Terry J. Reedy



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


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 15:44:14 -0400, Nicolas Fleury wrote:

 Steven D'Aprano wrote:
 One of the things I liked in Pascal was the with keyword. You could
 write something like this:
 
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;
 
 instead of:
 
 colour.red := 0; colour.blue := 255; colour.green := 0;
 
 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.
 
 
 With PEP343 (I guess in Python 2.5), you will be able to do something like:
 with renamed(colour) as c:
  c.red = 0; c.blue = 255; c.green = 0
 
 I think however it is bad.  Better solutions to me would be:
 
 colour.setRgb(0, 255, 0)

But that is no help, because the setRgb method will be implemented as

def setRgb(r, g, b):
self.red = r; self.green = g; self.blue = b

which is exactly the usage case for a with statement:

def setRgb(r, g, b):
with self:
.red = r; .green = g; .blue = b

 or
 
 c = myVeryLongNameColour
 c.red = 0; c.blue = 255; c.green = 0

Namespace pollution. It might not matter if c is a temporary variable
inside a function or method, but it does matter if your top-level code is
full of such constructs. Or for that matter, your interactive Python
session.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread James Stroud


On Saturday 25 June 2005 11:08 am, Steven D'Aprano wrote:
 The problem is, you have made colour (returning to English spelling
 instead of foreign) into a class. If you need two colour variables, you
 have to duplicate the code for the class (perhaps only changing the
 numeric constants. You can't even make instances from the class, because
 they all share the same RGB values, which is pretty useless if they are
 meant to represent different colours.

py class color:
...   pass
...
py def with(classname, **kwargs):
...   classname.__dict__.update(kwargs)
...
py with(color, red=0,
... blue=255,
... green=255)
py
py color.blue
255

Is this what you want to do?

  Also avoids those stupid little colons.

 Using := and = for assignment and equality is precisely as stupid as using
 = and == for assignment and equality. Perhaps less stupid: why do we use
 == for equals, but not ++ for plus and -- for minus?

The colons are to make it look more official or something. They are useless 
and hence stupid. The two equals signs for comparison could be argued to be 
redundant, but the colons are absolutely unecessary. I thought they were 
pointless 18 years ago when I learned pascal in highschool and after 20 
years, I still think they are still pointless.

-- 
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: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote:

 Mandus wrote:
 
 By using the builtin reduce, I
 move the for-loop into the c-code which performs better.
 
 No. There is no hope of ever writing fast code when you do not actually
 measure its performance.


Good grief! You've been spying on Mandus! How else could you possibly know
that he doesn't measure performance? Are you running a key-logger on his
machine? *wink*

For the record, perhaps now is a good time to mention that even Guido
recommended the use of map, filter and reduce in some circumstances:

Try to use map(), filter() or reduce() to replace an explicit for loop,
but only if you can use a built-in function: map with a built-in function
beats for loop, but a for loop with in-line code beats map with a lambda
function!

http://www.python.org/doc/essays/list2str.html

He specifically mentions that the reason map will often beat a for loop is
that it moves the work out of Python into the underlying C code.

That is also one of the reasons that ''.join(L) is faster than

s = ''
for item in L:
s = s + item

Do we really need to profile our code every single time to know this?
Isn't it reasonable to just say, I use join because it is faster than
adding strings without being abused for invalid optimization?



-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 13:31:19 -0700, Robert Kern wrote:

 Of course, in a Python 3000 world, nothing stops anyone from using their 
 own extension module implementing map, filter, and reduce if they really 
 want to. TSBOOOWTDI in the language/stdlib, but it shouldn't stop anyone 
 from using other ways to do it that aren't in the stdlib if the 
 tradeoffs are right for them.

Now that's a good point. Since Guido has said that one of the major
motivations for removing the functional programming tools like map, filter
and reduce is that There Should Be Only One Obvious Way To Do It, and
Guido also seems to really like list comprehensions, is it fair to
assume that for-loops will be removed from Python 3000 too?

Or are they safe until Python 4000?

*wink*

Of course, I also know that Guido has said a foolish consistency
is the hobgoblin of little minds, and I would never accuse him of being a
little mind. But one of the things I like about Python is that it has
found a nice balance between There Is Always Another Way, and The Language
Is A Straight Jacket.

It is blindingly easy to refactor map and filter as in-line list comps,
and Guido's comments suggest to me that they are safe until list comps are
significantly faster. But reduce needs to be re-factored as a for loop,
with all the disadvantages that implies. I think that if people like
Mandus have good real-world usage cases for reduce, it can be saved, at
least as part of itertools.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread James Stroud
On Saturday 25 June 2005 06:44 pm, James Stroud wrote:
 I thought they were
 pointless 18 years ago when I learned pascal in highschool and after 20
 years, I still think they are still pointless.

I think that fails ==.

-- 
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: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 18:44:12 -0700, James Stroud wrote:

 On Saturday 25 June 2005 11:08 am, Steven D'Aprano wrote:
 The problem is, you have made colour (returning to English spelling
 instead of foreign) into a class. If you need two colour variables, you
 have to duplicate the code for the class (perhaps only changing the
 numeric constants. You can't even make instances from the class, because
 they all share the same RGB values, which is pretty useless if they are
 meant to represent different colours.
 
 py class color:
 ...   pass
 ...
 py def with(classname, **kwargs):
 ...   classname.__dict__.update(kwargs)
 ...
 py with(color, red=0,
 ... blue=255,
 ... green=255)
 py
 py color.blue
 255
 
 Is this what you want to do?

No it isn't. That doesn't help at all if you want to do something
other than assigning to instance attributes.

For starters, it doesn't help me do this:

with colour:
print Blue =, .blue
print Green =, .green
print Red =, .red

or anything more complex:

with my_directory_object:
L = .raw_paths
L.append(~/custom/)
# move the last directory looked to the front
# and the current directory to the end
.normalise(L, first=.last_dir, last=.)
.paths = L
try:
.currentpos += 1
except AttributeError:
.currentpos = 0

The point is that a hypothetical with block would have to allow
arbitrary access to dotted names: getting, setting, deletion, and method
calling, not just one very limited form of keyword assignment.



  Also avoids those stupid little colons.

 Using := and = for assignment and equality is precisely as stupid as using
 = and == for assignment and equality. Perhaps less stupid: why do we use
 == for equals, but not ++ for plus and -- for minus?
 
 The colons are to make it look more official or something. 

That is the most ridiculous thing I have ever heard about a programming
language.

Has it escaped your notice that every language has to distinguish in
some way between x equals 1 in the sense of assignment and x equals 1
in the sense of comparisons? x = 1 is ambiguous.

A language might use constructs like:

SET x = 1 and x = 1 

for assignment and comparison, or do what Python does:

x = 1 and x == 1

or do what Pascal does:

x := 1 and x = 1

Even if the compiler can always unfailing tell them apart from context,
for the sake of the human programmers who have to read and write the code,
it is important to have two different operators.


 They are useless and hence stupid. 

Useless huh? Just try leaving them out and see how useless they are.

 The two equals signs for comparison could be argued to be 
 redundant, 

No they aren't redundant, because assignment and equality testing are very
different. And in Python, you can even use them in the same place, so you
can't expect the compiler to tell them apart from context.

py x = 2  # did I mean assignment or comparison?

 but the colons are absolutely unecessary. I thought they were 
 pointless 18 years ago when I learned pascal in highschool and after 20 
 years, I still think they are still pointless.

You didn't learn Pascal very well then if you can't see the difference
between assignment and equality testing.


-- 
Steven.

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


Re: Favorite non-python language trick?

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 23:08:10 +, Bengt Richter wrote:

 On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano [EMAIL PROTECTED] wrote:
 
On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote:

 On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote:
 with colour do begin
 red := 0; blue := 255; green := 0;
 end;

 instead of:

 colour.red := 0; colour.blue := 255; colour.green := 0;

 Okay, so maybe it is more of a feature than a trick, but I miss it and it
 would be nice to have in Python.

 How do you like the following?
   color = type('',(),{})() # an instance that will accept attributes
   vars(color)
  {}
 
 The single line replacing
  
  with colour do begin
  red := 0; blue := 255; green := 0;
  end;
  
 follows:
   vars(color).update(red=0, blue=255, green=0)


The point is that a hypothetical with block would have to allow
arbitrary access to dotted names: getting, setting, deletion, and method
calling, not just one very limited form of keyword assignment.

I understand how to manipulate __dict__ as an more complicated (dare I say
obfuscated?) way of assigning to object attributes.


[snip]

 We can clear those attributes from the instance dict:
 vars(colour).clear()
 vars(colour)
 {}

Which has the unfortunate side effect of also destroying any other
instance attributes.


you might do this:

with myobject:
# read a class attribute
print .__class__.myattribute
# set an instance attribute
.widget.datapoints[.collector] = .dispatcher(.widget.current_value)

 
 def mywith(o=myobject):
  # read a class attribute
  print o.__class__.myattribute
  # set an instance attribute
  o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value)
 mywith()

[snip]

 Is a one-character prefix to the dot objectionable?

That's a good workaround, subject to namespace pollution issues, and one
that I'm aware of. Although do you really want to be creating a unique
function definition every time you want to use the with idiom?

I'm not about to stop using Python because of the lack of Pascal-like
with blocks. It is a nice feature to have, but I'm aware that Guido
prefers explicit to implicit and with is extremely implicit. 



-- 
Steven.

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


Rebindings [was Re: Favorite non-python language trick?]

2005-06-25 Thread Steven D'Aprano
On Sat, 25 Jun 2005 23:08:10 +, Bengt Richter wrote:

Using := and = for assignment and equality is precisely as stupid as using
= and == for assignment and equality. Perhaps less stupid: why do we use
== for equals, but not ++ for plus and -- for minus?

 I agree, but I think := would be nice in python for RE-binding an existing
 binding, wherever it is seen from the local context. Thus you could
 write
 
 def foo(): x:=123
 
 and
x = 456
def bar():
x = 789
foo()  # finds and rebinds local x
print x
bar() # - 123
print x # - 456
foo()  # finds and rebinds the global x
print x # - 123
 
 but
del x
foo()  #- NameError exception, can't find any x to rebind
 
 hm, wandered a bit OT there, ;-/

Given how much the use of global variables are discouraged, is it a
good idea to allow even more inter-namespace interactions?


-- 
Steven.

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


Favorite non-python language trick?

2005-06-24 Thread Joseph Garvin
As someone who learned C first, when I came to Python everytime I read 
about a new feature it was like, Whoa! I can do that?! Slicing, dir(), 
getattr/setattr, the % operator, all of this was very different from C.

I'm curious -- what is everyone's favorite trick from a non-python 
language? And -- why isn't it in Python?

Here's my current candidate:

So the other day I was looking at the language Lua. In Lua, you make a 
line a comment with two dashes:

-- hey, this is a comment.

And you can do block comments with --[[ and ---]].

--[[
hey
this
is
a
big
comment
--]]

This syntax lets you do a nifty trick, where you can add or subtract a 
third dash to change whether or not code runs:

--This code won't run because it's in a comment block
--[[
print(10)
--]]

--This code will, because the first two dashes make the rest a comment, 
breaking the block
---[[
print(10)
--]]

So you can change whether or not code is commented out just by adding a 
dash. This is much nicer than in C or Python having to get rid of  or 
/* and */. Of course, the IDE can compensate. But it's still neat :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-06-24 Thread Enrico
Joseph Garvin [EMAIL PROTECTED] ha scritto nel messaggio
news:[EMAIL PROTECTED]
 --This code won't run because it's in a comment block
 --[[
 print(10)
 --]]

 --This code will, because the first two dashes make the rest a comment,
 breaking the block
 ---[[
 print(10)
 --]]

 So you can change whether or not code is commented out just by adding a
 dash. This is much nicer than in C or Python having to get rid of  or
 /* and */. Of course, the IDE can compensate. But it's still neat :)

python:


print 10


and

#
print 10
#

C++:

/*
print(10);
*/

and

///*
print(10);
//*/

?

Bye,
Enrico


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


Re: Favorite non-python language trick?

2005-06-24 Thread Uwe Mayer
Friday 24 June 2005 09:18 am Enrico wrote:

[...]
 --This code will, because the first two dashes make the rest a comment,
 breaking the block
 ---[[
 print(10)
 --]]
[...]

 python:
 
 
 print 10
 
 
 and
 
 #
 print 10
 #
 
 C++:
 
 /*
 print(10);
 */
 
 and
 
 ///*
 print(10);
 //*/
 
 ?

I think the *trick* here was that if you had larger blocks you'd only have
to change one side of the comment, i.e. the opening line, to de-comment the
block without searching the end of it and commenting that out aswell.

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


  1   2   >