Re: [Python-Dev] (try-except) conditional expression similar to (if-else) conditional (PEP 308)

2009-08-14 Thread Alexander Kozlovsky
Jeff McAninch wrote:
> I very often want something like a try-except conditional expression similar
> to the if-else conditional. 

I think it may be done currently with the help of next function:

def guard(func, *args):
try:
return func()
except Exception, e:
for exc_type, exc_func in args:
if isinstance(e, exc_type):
return exc_func()
raise

Example usage:

a, b, c = 10, 20, 0

result = a + b/c  # raise ZeroDivisionError

result = a + guard(lambda: b/c, (TypeError, lambda: 10),
(ZeroDivisionError, lambda: b/2))

May be not very concise, but it works...


-- 
Best regards,
 Alexander  mailto:alexander.kozlov...@gmail.com

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] str.dedent

2005-11-13 Thread Alexander Kozlovsky
Raymond Hettinger wrote:
> That is somewhat misleading.  We already have that ability.  What is
> being proposed is moving existing code to a different namespace.  So the
> motivation is really something like:
> 
>I want to write 
>s = s.dedent() 
>because it is too painful to write
>s = textwrap.dedent(s)

>From technical point of view, there is nothing wrong with placing
this functionality in textwrap. But from usability point of view
using textwrap.dedent is like importing some stuff for doing string
concatenation or integer addition.

In textwrap module this function placed in section "Loosely (!)
related functionality". When Python beginner try to find "Pythonic"
way for dealing with dedenting (And she know, in Python "there
should be one -- and preferably only one -- obvious way to do it"),
it is very unlikely that she think "Which module may contain
standard string dedenting? Yes, of course textwrap! I'm sure
I'll find necessary function there!"

> String methods should be limited to generic string manipulations.
> String applications should be in other namespaces.  That is why we don't
> have str.md5(), str.crc32(), str.ziplib(), etc.

I think, dedenting must be classified as "generic string manipulations".

The need in string dedenting results from meaningful indentation
and widespread use of text editors with folding support. Multiline strings
without leading whitespaces breaks correct folding in some editors.


Best regards,
 Alexandermailto:[EMAIL PROTECTED]

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


[Python-Dev] Draft proposal: Implicit self in Python 3.0

2006-01-05 Thread Alexander Kozlovsky
Hello!

I have some proposal for Python 3.0 (interesting one, from my point
of view). I'm sorry for my English, it is not very good.


Abstract


There are three different peculiarity in Python 2.x
in respect of 'self' method argument:

1. Each method must have explicit 'self' argument in its argument list
2. This argument must be used explicitly for instance's attribute value
   assignment
3. The count of explicit arguments in method definition differs from
   count of explicit parameters when method is called

Example 1 (Python 2.x):
---

class Foo:
def __init__(self, x):   # 1: Explicit 'self' argument
self.x = x   # 2: 'self' must be used explicitly
def bar(self, a, b): # 3: There are three arguments...
print self.x + a + b

Foo(10).bar(20, 30)  # ...but only two explicit parameters
 #is presented

This document proposes to change this, as the next example shows:

Example 2 (Python 3.0):
---

class Foo:
def __init__(x): # 1: Implicit self
.x = x   # 2: Brief form of: self.x = x
def bar(a, b):   # 3: Two arguments...
print .x + a + b

Foo(10).bar(20, 30)  # ...and exactly two parameters

According  Python Zen, "Explicit is better then implicit", but
"practicality beats purity" and "Readability counts" ;-)

This draft document describes high-level semantic of proposed changes
and doesn't discuss details of C implementation.


Rationale
=

When programmer tries to pick up some new programming language from
different possibilities (e.g. Smalltalk, Python, Perl, ...), he often
bases his choice on secondary and non-essential details. Almost any
language has peculiarities, which can distract potential users
from language evaluation. Examples of such warts may be [EMAIL PROTECTED]&% 
perlish
syntax in Ruby, abundance of parenthesis in Lisp and Schema, and
explicit 'self' argument in Python.

Of course, from technical point of view, such peculiarities are
completely non-issue. Parenthesis is not problem in Lisp if you use
a good text editor, perlisms in Ruby can be avoided, etc. But from
sociological and usability points of view, such warts can cause
remarkable hurt, because they affect first impression about language.

In many superficial language comparisons Python's OO approach dismissed
as after-thought because of the explicit 'self'. Example:

   But the most important aspect, why I am using Ruby instead of
   Python or Perl are the object-orientated features of Ruby, and
   that Ruby was designed object-oriented right from beginning,
   unlike Python and Perl where object-orientation was added on
   later. You can recognize this in e.g. in Python very good,
   because the first parameter (often named self) of every method of
   a class is the object on which the method is called

   (http://www.ntecs.de/old-hp/s-direktnet/rb/ruby.pdf)

   
Of course, this words about Python are not true. Python was
object-oriented from the beginning, and explicit 'self' is intentional
design decision, which is elegant in some aspects. But from
pragmatical point of view, implicit 'self' in Python 3.0 may
lower entry barrier for many people and assist Python's wide adoption.

The proposed change is not backward-compatible with Python 2.x

Detailed proposals
==

1. 'self' becomes a keyword, and may be used inside function
   definition to denote a special implicit function argument

2. New syntax shortcut is introduced: '.attr' inside a function
   is exact equivalent to 'self.attr'. Full syntax can be used
   as well
   
3. 'class' keyword can be used in two different syntactical
   construction:
   a) If 'class' keyword immediately followed by identifier,
  then it is usual class definition.
   b) In all other cases (inside a function) 'class' keyword
  denotes value of implicit function argument

   >>> # in Python 3.0:
   >>> def sample(a, b):
   ... class C: pass # ordinary class definition
   ... print class.__name__  # 'class' is implicit argument
   ...

4. Each function (not only class methods) accepts two implicit
   arguments, 'class' and 'self'. With ordinary function call,
   this arguments has 'None' value

   >>> def f(a, b):
   ... return [class, self, a, b]
   ...
   >>> f(1, 2)
   [None, None, 1, 2]

   Implicit 'class' and 'self' attributes don't participates in
   partial function application

5. Each function have two constant attributes, __class__ and __self__,
   both of them have value 'None'

   >>> f.__class__, f.__self__
   (None, None)

6. New builtin function bind(func, self_, [class_]) is introduced.
   The result is a new function with the same name,
   __self__ and __class__ attributes of which are equal to
   self_ and class_, correspondly. If bind function is called
   without class_ argument, then __clas

Re: [Python-Dev] Draft proposal: Implicit self in Python 3.0

2006-01-05 Thread Alexander Kozlovsky
I wrote:
> 5. Each function have two constant attributes, __class__ and __self__,
>both of them have value 'None'

Of course, this attributes have names 'im_class' and 'im_self',
as before, but can be used with any function.

I have not sleep enough last night :)



Best regards,
Alexandermailto:[EMAIL PROTECTED]

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Draft proposal: Implicit self in Python 3.0

2006-01-06 Thread Alexander Kozlovsky
Hello!

Ian Bicking wrote:
> (As an aside directed at the original PEP, I think discussion of leaving
> self out of expressions, e.g., ".x" for "self.x", should be separate 
> from the rest of this PEP).

Yes, I'm fully agree.


Nick Coghlan wrote:
> The main concern I have is with the answer to the question "How many
> positional arguments does the function have if I retrieve it from the class, 
> rather than from an instance?" (this is the common concern for almost all 
> proposals to remove the explicit self and class_ slots).

In this case, the function always (!!!) has fixed number of
positional arguments equal to number of positional parameters
inside the function definition:

  >>> def func(a, b):
  ... print class, self, a, b
  ...
  >>> class Foo:
  ... bar = func
  ...
  >>> instance = Foo()
  >>> func(1, 2)  # there are 2 arguments
  None None 1 2   #   <- class and self both equal to None
  >>> Foo.bar(1, 2)   # 2 arguments again!!
   None 1 2#   <- self is equal to None
  >>> instance.bar(1, 2)  # 2 arguments always!!!
1 2

  
Nick Coghlan wrote:
> To sum the proposal up in my own words:
>Eliminate the need for explicit class and self slots in class
> and instance methods by implicitly providing those slots on all
> functions.

Yes, I think, it is what I mean.

With my proposal, 'self' is no longer the first explicit or implicit
positional argument (!), instead, it is 'pseudo-argument', the value
of which is equal to function's 'im_self' attribute. Any function
contains two special read-only attributes: 'im_class' and 'im_self',
and values of this attributes are accessible inside function body
as values of 'class' and 'self' pseudo-arguments.

Any function has this attributes, for ordinary function their values
are set to 'None'. Example:

  >>> # Python 3.0
  >>> def f(): return class, self
  >>> f()
  (None, None)

There is new built-in function:

bind(old_function, self_, class_=None) -> new_function
  
The result is the new function with the same code object which the
old function had, but with different im_class and im_self attributes
values.

- If both self_ and class_ arguments are None, then 'im_class' and
  'im_self' attributes of new function is set to equal to None.

- If self_ is not None, then class_ must be None or self_.__class__.
  'im_self' attribute of new function is set to self_, and im_class
  attribute is set to self_.__class__

- If self_ is None but class_ is not None, then 'im_self' attribute
  is set to None, and 'im_class' attribute is set to class_

Consider this expression (extraction of a method from a class):

   x = Foo.bar

This expression is equivalent of:

   x = bind(Foo.__dict__["bar"], None, Foo)

After this, x.im_class is Foo and x.im_self is None
The type.__getattribute__ contains implementation of this
   
Consider next expression (extraction of a method from an instance):

   y = instance.bar

This expression is equivalent of:

   y = bind(instance.__class__.__dict__["bar"], instance)

After this, y.im_class is instance.__class__ and y.im_self is instance.
The object.__getattribute__ is responsible for this

Ian Bicking wrote:
> Well... it becomes more complex for decorators, I guess:
> 
>def printargs(func):
>def replacement(*args, **kw):
>print args, kw
>return func(*args, **kw)
>return replacement
>class Foo:
>@printargs
>def null(a): pass
> 
> What is printargs going to print?  Will it even work?  I'd guess you'd 
> have to do:
> 
>def printargs(func):
>def replacement(*args, **kw):
>print args, kw
>return bind(func, self)(*args, **kw)
>return replacement

I think, it should be:

def printargs(func):
def replacement(*args, **kw):
print args, kw
return bind(func, self, class)(*args, **kw)
return replacement

Yep, the code in decorators will be more complicated than it is today.
I did not get it before...

> I guess it depends on what bind(func, self) does outside of
> a method invocation.  I think self should be undefined in that case.

'self' will be None in that case. Any function has 'self' pseudo-argument,
but in a plain function (not a method) 'self' and 'class' both equal
to None.



-- 
Best regards,
 Alexandermailto:[EMAIL PROTECTED]

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com