Re: So what exactly is a complex number?

2007-09-07 Thread El Pitonero
On Sep 5, 7:27 am, El Pitonero [EMAIL PROTECTED] wrote:

 I am a bit surprised that today, September 2007, in a thread about
 complex numbers, no one has mentioned about geometric algebra.

Here is a good reference for whoever is interested. It's quite
accessible to general audience.

http://www.xtec.es/~rgonzal1/treatise.pdf

If a person spends some time to look at the geometric algebra, it will
become clear that complex numbers are not that special, after all.
Hopefully the relationship between the 2-d vector plane and the
complex plane will also become more clear, as complex numbers can be
understood as rotation-dilation operators over vectors. One also
learns that complex numbers are based on a metric assumption of square
of vectors (norm) being positive (a.k.a Euclidean space). There is
nothing sacred about positively-defined metric, and in fact if one
uses mixed signature metric (pseudo-Euclidean space), one comes up
with hyperbolic numbers instead of complex numbers.

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


Re: So what exactly is a complex number?

2007-09-05 Thread El Pitonero
On Sep 1, 3:54 am, Grzegorz S odkowicz [EMAIL PROTECTED] wrote:

 You're mixing definition with application. You didn't say a word about
 what complex numbers are, not a word about the imaginary unit, where
 does it come from, why is it 'imaginary' etc.  
 ...
 I'd also like to see a three-dimensional vector
 represented by a complex number.

Well, maybe you'd like to learn something about Geometric Algebra. :)

I am a bit surprised that today, September 2007, in a thread about
complex numbers, no one has mentioned about geometric algebra. There
is an older way of looking at complex numbers: the imaginary unit as
square root of -1. And then there is a new way of looking at complex
numbers: as the multi-vector space associated to the two-dimensional
vector space. So, yes, complex numbers are a bit like vectors, but
more precisely, they are multi-vectors, where the first component
(the real part) is a scalar, and the second part (the imaginary
part) is an area.

This may all be just paraphrasing. But it gets more interesting when
you go to higher dimensions. You'd like to know whether there are
extension of complex numbers when you go to three dimensional space,
and the answer is definitely YES! But the new multivectors live in 8
dimensional space. Geometric product not only make this possible, but
this product is invertible. Moreover, complicated equations in
electromagnatism in physics (Maxwell's equations) can be written in a
single line when you use geometric algebra. When you see some of the
features of geometric algebra, you will realize that complex number
are but a small part of it. (There is a paper with the title
Imaginary numbers are not real..., I guess the title says it all.)

Anyway, there are always many ways of looking at the same thing.
Geometric algebra is one. Who knows what tomorrow brings? But as of
today, I'd say that it's better to teach school children about
geometric algebra, instead of the present way of introducing imaginary
unit. Just my opinion.

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


Re: Subprocess with a Python Session?

2006-12-07 Thread El Pitonero
Paul Boddie wrote:
 Shane Hathaway wrote:
 
  Make sure the pipes are unbuffered.  Launch the process with python -u
  and flush() the streams after writing.  (That's the issue I've
  encountered when doing this before.)

 The -u option is critical, yes. I wrote some code recently which
 communicated with a subprocess where the input/output exchanges aren't
 known in advance, and my technique involved using socket.poll and one
 character reads from the subprocess. I note that Pexpect is also
 conservative about communicating with subprocesses (see the $ regex
 pattern is useless section on the Pexpect site [1]).

 Generally, any work with asynchronous communications, or even
 socket/pipe programming in a wider sense, seems to involve ending up
 with working code that looks a lot like the code you started out with,
 but only after a period of intense frustration and with a few minor
 adjustments being made to separate the two.

Is there something equivalent to the -u option for a shell like
bash? In general (whether the subprocess is bash or python), how can
one make sure that once something is written into the subprocess'
stdin, the output from its stdout is fully completed and the subprocess
is ready to receive another command? Is there some kind of signal or
return status code one can capture?

-- P.

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


Re: updating local()

2005-10-06 Thread El Pitonero
Flavio wrote:
 I wish all my problems involved just a couple of variables, but
 unfortunately the real interesting problems tend to be complex...

 def fun(**kw):
 a = 100
 for k,v in kw.items():
 exec('%s = %s'%(k,v))
 print locals()


  fun(**{'a':1,'b':2})
 {'a': 1, 'k': 'b', 'b': 2, 'kw': {'a': 1, 'b': 2}, 'v': 2}

 any better Ideas?

Actually, your solution is not bad. Some potential problems are: (1)
unintentional name collisions with other variables, including
globals/builtins, (2) it's easy to unpack variables into locals(), but
not easy to pack them back, since locals() are often contaminated with
extra auxiliary variables.

Your problem happens often in the field of math formulas/equations.

I remember similar problem happens in C++, too. When one has a function
with a long list of parameters, in C++ one may find oneself updating
the funtion header/prototype all the time, which is very tiresome and
error-prone.

When you have complicated list of arguments to pass, it's better to put
them into a structure/object. This way, the function header/prototype
will remain the same, and you only need to change the declaration of
the object.

The parameter object(s) could be called:

- request and response, if input and output are separated
- param
- workspace, session, etc.

so, your function call would look like

class Param: pass
...
def f(p):
result = p.x + p.y
return result
...
p=Param()
p.x = 3
p.y = 4
result = f(p)

Now, you may not like the extra dots in the line:

result = p.x + p.y

My experience is: it's not that bad to have names with extra dots. I
know it's annoying, but not a total disaster. Plus, once you start to
use OOP, it makes your code more organized. It has its benefits. For
instance, very often your models/formulas have several versions. Using
OOP's class hierarchy inheritance mechanism allows you to try out
different versions or different ideas much more easily, and you can
roll back the changes more easily, too (instead of commenting out code
lines all over places.) If you do decide to go the route of OOP, the
lines:

p.x = 3
p.y = 4
p.z = 5

can be replaced by something like:

calculation_engine.set(x=3, y=4)
calculation_engine.set(z=5)

--

The longer answer is: if you need complex formula evaluations, Python
is probably not the language to use. For speed and memory usage issues,
C++ is probably what you need. You can hookup your C++ program to
Python in various ways, but packing/unpacking variables seems
unavoidable. And even in C++ (where object attributes don't have the
dots inside the object's own methods), I still often end up using a lot
of dotted names for attributes from other objects.

If the problem is complex, then it's complex. I know you have your
equations, but you have to decide for yourself: is it better to do all
the packing/unpacking, or is it better to change your equations to use
the dotted names? There is no right or wrong answer, it all depends on
your particular situation.

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


Re: Will python never intend to support private, protected and public?

2005-10-04 Thread El Pitonero
Paul Rubin wrote:

 Let's see, say I'm a bank manager, and I want to close my cash vault
 at 5pm today and set its time lock so it can't be opened until 9am
 tomorrow, including by me.  Is that handcuffs?  It's normal
 procedure at any bank, for good reason. It's not necessarily some
 distrustful policy that the bank CEO set to keep me from robbing the
 bank.  I might have set the policy myself.  Java lets me do something
 similar with instance variables.  Why is it somehow an advantage for
 Python to withhold such a capability?

If so, you would probably be the type of person that also likes static
typing, type safety and variable declaration, right? You like your
language with extra baggages to improve some safety concerns, which
most Python programmers don't seem to need.

   def countdown():
 n = 3
 while n  0:
yield n
   g = countdown()
   print g.next()  # 3
   print g.next()  # 2

 where's the Python feature that lets me modify g's internal value of n
 at this point?

You missed the point. I have, for fun, built a GUI application in
Python, while the program is running. I just kept on adding more and
more code to it. This, while the Python program is running. I was able
to change the GUI's look-and-feel, add more buttons, menus, all while
the programming is running. I was able to change the class definition,
preserve the previous object state variables. For that, you already
have event-based program and can use module reload and some metaclass
tricks to automatically relink your objects to new classes. Sure,
Python is not as friendly as Lisp/Scheme for interactive programming,
but you can still do a lot.

 [Other stuff incomprehensible and snipped].

Sigh, I gave you the keywords: containment and aggregation.

There are two ways of enhancing functionality from an existing
object/class. One way is by inheritance, that's aggregation. Another
way is by containment, that means that instead of inheriting, you add
the additional features as an object contained in the new object.

Vault encapsulation is one way to do OOP. But by no means it is the
only way. The whole access level thing (the private keyword) is not
an essential part of OOP. The concept of a private namespace is not
necessary for OOP. Just because you learned OOP from one particular
school of thought, does not mean that that's the only way. Let us call
your OOP school A.

Another way of OOP is to accept by default that everything in the class
hierarchy is inheritable. And Python is by no means the only language
that does that. Now, obviously in this type of OOP you can run into
name collision. But if you actually follow this other school of
thought, you would organize your variables differently. Let us call
this type of OOP school B.

Let me be more clear: when you have variables that are so, so, so
private that no one else should touch, from school B's point of view,
those variables do not belong to the object. They belong to another
object.

Let us say there is a financial instrument that pays some fixed coupon
interest:

class Bond:
volatility = None
interest = None
def __init__(self):
self.volatility = 0.3 # volatility from credit risk
self.interest = 0.4

Now, you have another instrument that pays variable interest:

class VariableInterestBond(Bond):
volatility = None # this one collides with the base class
def __init__(self):
 Bond.__init__(self)
 self.volatility = 0.2 # volatility for variable interest
def calculate(self):
 interest = self.get_variable_interest()
 ...
def get_variable_interest(self):
 return self.interest * (1 + random.random()*self.volatility)
...

In this example, the subclass's volatility meant something else but
collides with the base class's volatility. It should have been a
private variable, but now it accidentally overwrote an existing
variable.

We are trying to combine two features in the hierarchy tree:


Bond
|
|
+- Variable Interest
|
|
Variable-Interest Bond

There are two ways to add the variable interest feature to the bond
object. One way is by aggregation (inheritance), which is shown above.
Another way is by containment.

If the subsclass's volatility should be private and encapsulated from
the main class hierarchy (i.e. Bond-like objects), then from school B's
point of view, it does not belong to the bond object. It would be
better to encapsulate it into another object.

class VariableInterest:
volatility = None
def __init__(self, interest):
self.interest = interest
self.volatility = 0.2
def get_variable_interest(self):
 return self.interest * (1 + random.random()*self.volatility)

class VariableInterestBond(Bond):
variable_interest_calculator = None
def __init__(self):
 Bond.__init__(self)
 self.variable_interest_calculator =
VariableInterest(self.interest)
def calculate(self):
 interest =

Re: Will python never intend to support private, protected and public?

2005-10-02 Thread El Pitonero
Bengt Richter wrote:

 I decided to read this thread today, and I still don't know exactly
 what your requirements are for private whatevers.

No name collision in subclassing. Notice that even if you use

self._x = 3

in a parent class, it can be overriden in a sub-sub-class accidentally.

 Or maybe, what are your real requirements?
 ;-)

No need for this type of joke.

For people coming from Java/C++ camp, (especially Java camp,) they
think they've got something good with the private class variable, and
they think the lack of an exact equivalent in Python means Python is
lesser in this regard.

The thing is, there are two sides to every coin. Features surely can be
viewed as goodies, or they can be viewed as handcuffs.

Python's lack of Java-style private surely has its drawback: name
collisions can happen. But, that's just one side. Name collisions are
allowed in many dynamic languages, where you can override the default
system behavior (in some languages, you can override/intercept the
assignment operator =, or even the if statement and the while
loop.) Sure, in these very dynamic languages you can ACCIDENTALLY
override the default system behavior. How many Python programmers have
once upon a time done stupid things like:

list = 3

, without realizing that list() is a Python function? This type of
accidental overriding DOES happen. Similarly, in large and complicated
Python projects, name collision (even for self._x type of private
members) CAN happen, and I am sure it has happened for some people.

Now the question is: for average people and average project, how often
does this type of error happen? If people really cool down their heads
and don't talk emotionally, and base on their real experience
throughout the years, the truth is that this type of error just doesn't
happen that often. And even if it does happen, the error is usually
fatal enough to be detected.

OK, I have said that not having Java-style private has one downside
in Python. But what's the upside?

Not having private in Python closes one door, but opens another door.

The upside is exactly the same as the fact that you can override the
list() function in Python. Python is dynamic language. Like others
have pointed out, you can not even be sure about the variable content
of a class/object during runtime. In Java, you cannot override your
private members during runtime. In Python, if you have a private
variable:

self._x = 3

and you, for curiosity reasons and DURING runtime (after the program is
already up and running) want to know the exact moment the self._x
variable is accessed (say, print out the local time), or print out the
calling stack frames, you can do it. And I mean the program is running.

In Java, you would have to stop the program, re-write/re-implement
changes, re-compile, re-start the program, etc. etc.

The thing is, Python allows you to do runtime dynamic programming much
more easily than Java/C++. This type of dynamic and metaprogramming are
kind of unthinkable in the C++/Java world. Sure, these are advanced
programming features that not everybody uses, but Python leaves the
door open for those who want to take advantage of these powerful
features.

The fact that you can override Python's list() function can be either
viewed as pro or con. The fact that you can override member variables
can also be viewed as pro or con.

Would any Python programmer trade the benefits of a highly dynamic
language with an unessential feature like Java-style private data
members? My guess is not.

---

What do I say Java-style private is unessential?

If your Python class/object needs a real Java-style private working
namespace, you have to ask yourself: do the private variables REALLY
belong to the class?

In my opinion, the answer is: NO. Whenever you have Java-style private
variables (i.e, non-temporary variables that need to persist from one
method call to the next time the class node is accessed), those
variables/features may be better described as another object, separate
from your main class hierarchy. Why not move them into a foreign worker
class/object instead, and let that foreign worker object hold those
private names, and separate them from the main class hierarchy? (In
Microsoft's jargon: why not use containment instead of
aggregation?)

That is, the moment you need Java-style private variables, I think you
might as well create another class to hold those names and
functionalities, since they do not belong to the core functionality of
the main class hierarchy. Whatever inside the core functionality of the
main class, should perhaps be inheritable, sharable and modifiable.

If you use containment instead of aggregation, the chance for name
collision reduces dramatically. And in my opinion, it's the Pythonic
way of dealing with the private problem: move things that don't
belong to this object to some other object, and be happy again.

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-30 Thread El Pitonero
googleboy wrote:

 I am reading in a csv file that documents a bunch of different info
on
 about 200 books, such as title, author, publisher, isbn, date and
 several other bits of info too.
 ...
 I really want to be able to sort the list of books based on other
 criterium, and even multiple criteria (such as by author, and then by
 date.)

import string

input = open(r'c:\books.csv', 'r')
records = input.readlines()
input.close()

# assuming first line contains headers
headers = records.pop(0)
records = [x.strip().split(',') for x in records]

# header order
p_headers ='(title, author, publisher, isbn, date, other)'
p_sorts = '(author, title, date, publisher, other, isbn)'

temp_records = []
for r in records:
exec '%(p_headers)s = r' % vars()
exec 't = %(p_sorts)s' % vars()
temp_records.append(t)

temp_records.sort()

sorted_records = []
for t in temp_records:
exec '%(p_sorts)s = t' % vars()
exec 'r = %(p_headers)s' % vars()
sorted_records.append(r)

lines = [headers] + [','.join(x)+'\n' for x in sorted_records]
output = open(r'c:\output.csv', 'w')
output.writelines(lines) 
output.close()

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


Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread El Pitonero
Bengt Richter wrote:
 I still don't know what you are asking for, but here is a toy,
 ...
 But why not spend some time with the tutorials, so have a few more
cards in your deck
 before you try to play for real? ;-)

Communication problem.

All he wanted is automatic evaluation a la spreadsheet application.
Just like in Microsoft Excel. That's all.

There are many ways for implementing the requested feature. Here are
two:

(1) Push model: use event listeners. Register dependent quantities as
event listeners of independent quantities. When an independent quantity
is modified, fire off the event and update the dependent quantities.
Excel uses the push model.

(2) Pull model: lazy evaluation. Have some flag on whether an
independent quantity has been changed. When evaluating a dependent
quantity, survey its independent quantities recursively, and update the
cached copies whereever necessary.

Of course, combination of the two approaches is possible.

For Python, metaclasses and/or decorators and/or properties may help.

But functional languages are a more natural territory.

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


Re: Puzzling OO design problem

2005-04-09 Thread El Pitonero
It may be useful to separate the code into version-independent part and
version-dependent part. Also, one can try to implement the higher-level
logic directly in the class definition of A, B, etc., and then use the
version objects only as patches for the details. That is, one can use
place-holder calls. The place-holder calls do nothing if a feature is
not really implemented (either in a parent class, or in an older
version).

class World(object):

def __init__(w, version):

class A(object):
def ff(): pass # place holder for version-dependent code
def f(self): # version-independent code
return self.ff()

class B(A):
def gg(): pass
def g(self):
return self.gg()

for cls in (A, B):
setattr(w, cls.__name__, w.versionize(cls, version))

def versionize(w, cls, version):
import inspect
methods = inspect.getmembers(version, inspect.ismethod)
methods = [m[1] for m in methods if m[0].split('_')[0] ==
cls.__name__]
for m in methods:
m_name = '_'.join(m.__name__.split('_')[1:])
import new
im = new.instancemethod(m.im_func, None, cls)
setattr(cls, m_name, im)
return cls

class Version1(object):
def A_ff(self):
return 'A.ff: version 1'
def B_gg(self):
return 'B.gg: version 1'

class Version2(Version1):
def A_ff(self):
return 'A.ff: version 2'
def B_ff(self):
return 'B.ff: version 2'

w1, w2 = World(Version1), World(Version2)
a1, b1 = w1.A(), w1.B()
a2, b2 = w2.A(), w2.B()

print a1.f() # prints 'A.ff: version 1'
print b1.f() # prints 'A.ff: version 1'
print b1.g() # prints 'B.gg: version 1'
print ''
print a2.f() # prints 'A.ff: version 2'
print b2.f() # prints 'B.ff: version 2'
print b2.g() # prints 'B.gg: version 1'

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


Re: Decorator Base Class: Needs improvement.

2005-04-06 Thread El Pitonero
Bengt Richter wrote:
 On 5 Apr 2005 19:28:55 -0700, El Pitonero [EMAIL PROTECTED]
wrote:

 Scott David Daniels wrote:
  Ron_Adam wrote:
   ...
 
   def tweakdoc(name):
   def decorator(function):
 function.__doc__ = 'Tweak(%s) %r' % (name, function.__doc__)
 return function
   return decorator
 
  What is confusing us about what you write is that you are
referring
 to
  tweakdoc as a decorator, when it is a function returning a
decorator.
 
 Decorator factory would be a shorter name for a function
returning a
 decorator.
 
 True, but tweakdoc doesn't have to be a function, so IMO we need a
better
 name for the @-line, unless you want to use many various specific
names
 like factory. E.g.,

There are two things:

(1) The tweadoc object in the example, which no doubt can be called a
decorator factory.

(2) The @-line, which you called a decorator expression and that's
fine with me. My preference would be something like the decorator
header. A more clear statement would be something like: a decorator
header expression or the expression in the decorator header, though
your proposed decorator expression would be clear enough, too.

I was addressing (1). You jumped in with (2), which I was aware of and
was not dissenting.

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


Re: Docorator Disected

2005-04-03 Thread El Pitonero
Martin v. Löwis wrote:
 Ron_Adam wrote:
 
  No, I did not know that you could pass multiple sets of arguments
to
  nested defined functions in that manner.

 Please read the statements carefully, and try to understand the
mental
 model behind them. He did not say that you can pass around multiple
 sets of arguments. He said that functions (not function calls, but
 the functions themselves) are objects just like numbers. There is
 a way of truly understanding this notion, and I would encourage
 you to try doing so.

I have the same feeling as Martin and Bengt. That is, Ron you are still
not getting the correct picture. The fact that you have three-level
nested definition of functions is almost incidental: that's not the
important part (despite the nested scope variables.) The important part
is that you have to understand functions are objects.

Perhaps this will make you think a bit more:

x=1

if x==1:
def f(): return 'Hello'
else:
def f(): return 'Bye'

for x in range(3):
def f(x=x):
return x

Do you realize that I have introduced 5 function objects in the above
code? Do you realize that function objects could be created *anywhere*
you can write a Python statement? Whether it's inside another function,
or inside a if...else... statement, or inside a loop, doesn't matter.
Whereever you can write a Python statement, you can create a function
there. I don't know what your previous programming language is, but you
have to stop treating functions as declarations. The def is an
executable statement.

Another example:

def f():
   return f

g = f()()()()()()()()()()()

is perfectly valid.

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


Re: Docorator Disected

2005-04-02 Thread El Pitonero
Ron_Adam wrote:

 # (0) Read defined functions into memory

 def decorator(d_arg): # (7) Get 'Goodbye' off stack

 def get_function(function): # (8) Get func object off stack

 def wrapper(f_arg):# (9) Get 'Hello' off stack

 new_arg = f_arg+'-'+d_arg
 result = function(new_arg)  # (10) Put new_arg on stack
 # (11) Call func object

 return result  # (14) Return result to wrapper

 return wrapper# (15) Return result to get_function

 return get_function# (16) Return result to caller of func



 @decorator('Goodbye')   # (5) Put 'Goodbye' on stack
 # (6) Do decorator

 def func(s):# (12) Get new_arg off stack

 return s# (13) Return s to result

 # (1) Done Reading definitions


 print func('Hello') # (2) Put 'Hello' on stack
 # (3) Put func object on stack
 # (4) Do @decorator
 # (17) print 'Hello-Goodbye'

 # Hello-Goodbye

Is it possible that you mistakenly believe your @decorator() is being
executed at the line func('Hello')?

Please add a print statement to your code:

def decorator(d_arg):
 def get_function(function):
 print 'decorator invoked'
 def wrapper(f_arg):
 new_arg = f_arg+'-'+d_arg
 result = function(new_arg)
 return result
 return wrapper
 return get_function

When you run the program, you will see that the comment decorator
invoked is printed out at the moment when you finish defining:

@decorator('Goodbye')
def func(s):
return s

That is, decorator is invoked before you run the line func('Hello').

Decorator feature is a metaprogramming feature. Not a programming
feature. By metaprogramming I mean you are taking a function/code
object, and try to do something with it (e.g., wrap it around.) By the
time you finish defining the function func(s), the decorator
get_function() was already invoked and will never be invoked again.

It's better to view functions as individual objects. And try to think
who holds reference to these objects. If no one holds reference to an
object, it will be garbage collected and will be gone. After you define
the function func() and before you execute func('Hello'), this is
the situation:

decorator() --- held by the module
get_function() --- temporary object, garbage collected
wrapper() --- held by the module, under the name func
func() --- held by wrapper(), under the name function

'Goodbye' --- string object, held by the wrapper function object,
under the name d_arg

Objects can be rebound to different names. In your code you have
rebound the original wrapper() and func() function objects to different
names.

I think the confusing part is that, for function name binding, Python
does not use the = operator, but instead relies on the def keyword.
Maybe this is something to be considered for Python 3K. Anonymous
function or codeblock objects are good to have, when you are doing
metaprogramming.

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


Re: Decorator Dissection

2005-04-02 Thread El Pitonero
Ron_Adam wrote:
 On 2 Apr 2005 08:39:35 -0800, Kay Schluehr [EMAIL PROTECTED]
 wrote:

 There is actually nothing mysterious about decorators.

 I've heard this quite a few times now, but *is* quite mysterious if
 you are not already familiar with how they work.  Or instead of
 mysterious, you could say complex, as they can be used in quite
 complex ways.

If the syntax were like:

decorator = function(d_arg) {
return function(f) {
return function(f_arg) {
new_arg = f_arg+'-'+d_arg;
return f(new_arg);
}
}
}

func = decorator('Goodbye') function(s) {
return s;
}

Would you think it would be more easily understandable? Here,
function() is a metafunction (or function factory) whose role is to
manufacture a function given a parameter spec and a code body. And in
the expression

func = decorator('Goodbye')(function(s){return s;})

one pair of outter parenthesis have been omitted. Sure, it's not as
readable as Python's def, but with today's syntax highlighters, the
special word function can be highlighted easily.

If the decorator does not have parameters, one has:

func = decorator function(s) {

}

or in the general case:

func = deco1 deco2 deco3 function(s) {

}

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


Re: Docorator Disected

2005-04-02 Thread El Pitonero
Ron_Adam wrote:

 So I didn't know I could do this:

 def foo(a1):
 def fee(a2):
 return a1+a2
 return fee

 fum = foo(2)(6)   -- !!!

Ah, so you did not know functions are objects just like numbers,
strings or dictionaries. I think you may have been influenced by other
languages where there is a concept of static declaration of functions.

The last line can be better visualized as:

fum = (foo(2)) (6)

where foo(2) is a callable.

---

Since a function is an object, they can be assigned (rebound) to other
names, pass as parameters to other functions, returned as a value
inside another function, etc. E.g.:

def g(x):
return x+3

h = g # -- have you done this before? assignment of function

print h(1) # prints 4

def f(p):
return p # -- function as return value

p = f(h) # -- passing a function object

print p(5) # prints 8

Python's use of def keyword instead of the = assignment operator
makes it less clear that functions are indeed objects. As I said
before, this is something to think about for Python 3K (the future
version of Python.)



Function modifiers exist in other languages. Java particularly is
loaded with them.

public static synchronized double random() {
...
}

So your new syntax:

@decorator(a1)(foo)
def foo(): 
   pass 

is a bit out of the line with other languages.

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


Re: static variables in functions (was: Version Number Comparison Function)

2005-03-29 Thread El Pitonero
Christos TZOTZIOY Georgiou wrote:

 One of the previous related threads is this (long URL):

http://groups-beta.google.com/group/comp.lang.python/messages/f7dea61a92f5e792,5ce65b041ee6e45a,dbf695317a6faa26,19284769722775d2,7599103bb19c7332,abc53bd83cf8f636,4e87b44745a69832,330c5eb638963459,e4c8d45fe5147867,5a184dac6131a61e?thread_id=84da7d3109e1ee14mode=threadnoheader=1#doc_7599103bb19c7332

Another previous message on this issue:

http://groups-beta.google.com/group/comp.lang.lisp/msg/1615d8b83cca5b20

Python's syntax surely is not clean enough for concise metaprogramming.
At any rate, I'd agree with Fernando's assessment:

Fernando wrote:
 The real problem with Python is ... Python is
 going the C++ way: piling feature upon feature, adding bells
 and whistles while ignoring or damaging its core design.

If the core design were better, many new features in Python could
have been rendered unnecessary.

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


Re: Python for a 10-14 years old?

2005-03-24 Thread El Pitonero
Lucas Raab wrote:
 [EMAIL PROTECTED] wrote:
  I am blessed with a *very* gifted nine-years old daughter...
  Now, I would like to teach her programming basics using Python

 Let her mess around with it on her own. I'm 15 and have been using
 Python for 2-3 years and had nothing to really go on. Give her Dive
Into
 Python or How to Think Like a Computer Scientist and let her ask
 questions if she needs help.

In the chess world, people have long learnt to take young prodigies
seriously. Most of the grandmasters start to play chess at age 4 or
earlier. Bobby Fisher became the US chess champion at age 14, and a
grandmaster at 15. And that's considered old by modern standard: Sergei
Karjakin became grandmaster at age 12.

http://www.chessbase.com/newsdetail.asp?newsid=310
http://members.lycos.co.uk/csarchive/gilbert.htm

Sure, programming's skill set is a bit broader than chess playing or
ice-skating, but young hackers have plenty of contacts and resources
through internet, and many of them live (will be living) in Brazil,
Russia, India and China (the so-called BRIC countries.) So, a thorny
question for matured programmers is: what's your value in face of this
competition? :)

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread El Pitonero
On Sat, 19 Mar 2005 01:24:57 GMT, Raymond Hettinger
[EMAIL PROTECTED] wrote:
I would like to get everyone's thoughts on two new dictionary methods:

def count(self, value, qty=1):
try:
self[key] += qty
except KeyError:
self[key] = qty

def appendlist(self, key, *values):
try:
self[key].extend(values)
except KeyError:
self[key] = list(values)

Bengt Richter wrote:
   class xdict(dict):
  ... def valadd(self, key, incr=1):
  ... try: self[key] = self[key] + type(self[key])(incr)
  ... except KeyError: self[key] = incr

What about:

import copy
class safedict(dict):
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return copy.copy(self.default)

x = safedict(0)
x[3] += 1
y = safedict([])
y[5] += range(3)
print x, y
print x[123], y[234]

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread El Pitonero
Dan Sommers wrote:
 On Sat, 19 Mar 2005 01:24:57 GMT,
 Raymond Hettinger [EMAIL PROTECTED] wrote:

  The proposed names could possibly be improved (perhaps tally() is
more
  active and clear than count()).

 Curious that in this lengthy discussion, a method name of
accumulate
 never came up.  I'm not sure how to separate the two cases
(accumulating
 scalars vs. accumulating a list), though.

Is it even necessary to use a method name?

import copy
class safedict(dict):
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return copy.copy(self.default)


x = safedict(0)
x[3] += 1
y = safedict([]) 
y[5] += range(3) 
print x, y 
print x[123], y[234]

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread El Pitonero
Raymond Hettinger wrote:
 Separating the two cases is essential.  Also, the wording should
contain strong
 cues that remind you of addition and of building a list.

 For the first, how about addup():

 d = {}
 for word in text.split():
  d.addup(word)

import copy
class safedict(dict):
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = copy.copy(self.default)
return dict.__getitem__(self, key)

text = 'a b c b a'
words = text.split()
counts = safedict(0)
positions = safedict([])
for i, word  in enumerate(words):
counts[word] += 1
positions[word].append(i)

print counts, positions

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread El Pitonero
Raymond Hettinger wrote:

 As written out above, the += syntax works fine but does not work with
append().
 ...
 BTW, there is no need to make the same post three times.

The append() syntax works, if you use the other definition of safedict
(*). There are more than one way of defining safedict, see the subtle
differences between the two versions of safedict, and you'll be glad
more than one version has been posted. At any rate, what has been
presented is a general idea, nitpicking details is kind of out of
place. Programmers know how to modify a general receipe to suit their
actual needs, right?

(*) In some cases, people do not want to create a dictionary entry when
an inquiry is done on a missing item. In some case, they do. A general
receipe cannot cater to the needs of everybody.

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread El Pitonero
George Sakkis wrote:
 Aahz [EMAIL PROTECTED] wrote:
  In article [EMAIL PROTECTED],
  Raymond Hettinger [EMAIL PROTECTED] wrote:
  
  The proposed names could possibly be improved (perhaps tally() is
more active
  and clear than count()).
 
  +1 tally()

 -1 for count(): Implies an accessor, not a mutator.
 -1 for tally(): Unfriendly to non-native english speakers.
 +0.5 for add, increment. If incrementing a negative is unacceptable,
how about
 update/updateby/updateBy ?
 +1 for accumulate. I don't think that separating the two cases --
adding to a scalar or appending to
 a list -- is that essential; a self-respecting program should make
this obvious by the name of the
 parameter anyway (dictionary.accumulate('hello', words) vs
a.accumulate('hello', b)).

What about no name at all for the scalar case:

a['hello'] += 1
a['bye'] -= 2

and append() (or augmented assignment) for the list case:

a['hello'].append(word)
a['bye'] += [word]

?

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


Re: importing two modules with the same name

2005-03-19 Thread El Pitonero
Francisco Borges wrote:
 There are 2 foo named modules, 'std foo' and 'my foo'. I want to be
 able to import 'my foo' and then from within my foo, import 'std
 foo'. Anyone can help??

In other words, you would like to make a patch on third-party code.
There are many ways to do it. Here is just one possible approach.

#- A.py: third-party module
x = 3
def f():
return 'A.f(): x=%d' % x
#- B.py: your modifications to the module
def f():
return 'B.f(): x=%d' % x
#- Main.py: your program
import imp
# load the third party module into sys.modules
imp.load_source('A', '', open('C:\\A.py'))
# load and execute your changes
imp.load_source('A', '', open('C:\\B.py'))
# import now from memory (sys.modules)
import A
print A.f()

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


Re: importing two modules with the same name

2005-03-19 Thread El Pitonero
Tim Jarman wrote:
 But if your foo is under your control, why not do everyone a favour
and call
 it something else?

His case is a canonical example of a patch. Often you'd like to choose
the patch approach because:

(1) the third-party may eventually incorporate the changes themselves,
hence you may want to minimize changes to the name of the module in
your code, so one day in the future you may simply remove the patch, or

(2) you are testing out several ideas, at any point you may want to
change to a different patch, or simply roll back to the original
module, or

(3) your product is shipped to different clients, each one of them
requires a different twist of the shared module, or

(4) your program and your data files are versioned, and your program
structure needs cumulative patches in order to be able to work with all
previous data file versions.

These types of needs are rather common.

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


Re: Python becoming less Lisp-like

2005-03-15 Thread El Pitonero
Fernando wrote:
 The real problem with Python is ... Python is
 going the C++ way: piling feature upon feature, adding bells
 and whistles while ignoring or damaging its core design.

I totally agree.

Look at a recent thread Compile time evaluation (aka eliminating
default argument hacks)

http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/d0cd861daf3cff6d/6a8abafed95a9053#6a8abafed95a9053

where people coming from C++ or other typical programming languages
would do:

x = 1
def _build_used():
  y = x + 1
  return x, y
def f(_used = _build_used()):
  x, y = _used
  print x, y

instead of:

x=1
def f():
   y=x+1
   global f
   def f(x=x, y=y):
 print x, y
   f()

It is easy to see that people have been molded into thinking one way
(declaration of functions, legacy from staticly typed languages),
instead of viewing code also as object that you can tweak.

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