Re: why memoizing is faster

2011-03-26 Thread Lie
On Mar 26, 5:10 pm, Terry Reedy  wrote:
> On 3/26/2011 12:17 AM, Stefan Behnel wrote:
>
> > Not "restarted" in the sense that it gets cleaned up, though. The above
> > simply passes an explicit value for it that will be used for the single
> > call.
>
> Which satisfies the time test need, but...
>
>  > Future calls won't be affected.
>
> Good point. If one does fib(1) and wants to dump the cache without
> dumping all references to the function object, one can currently do
>    fib_iter.__kwdefaults__['_cache'] = [0,1]
> to truly reset the cache, at least with CPython.

Alternatively:

new_cache = [0, 1]
fib_iter(100, new_cache)
fib_iter(200, new_cache)
-- 
http://mail.python.org/mailman/listinfo/python-list


About Rational Number (PEP 239/PEP 240)

2007-12-15 Thread Lie
I'm very surprised actually, to see that Python rejected the use of
fractional/rational numbers. However, when I read the PEP, I know
exactly why the proposal was rejected: People compared fractions with
integers, while it should be more fairly compared to floats.

Arguments against:
- When I use the result of / as a sequence index, it's usually an
error which should not be hidden by making the program working for
some data, since it will break for other data.
> In Python 3 (and 2 w/ __future__), the / operator would always
return floats, and floats is invalid as sequence index, even if the
value of the float is whole. Since fractions is created with the /
operator on two integers, the behavior of fractions should mimics
float. So putting fractional type as sequence index should always be
considered as error (exception), a behavior consistent with floats.
Thus, the arguments specified above has turned invalid, at least in
Python 3.
- (this assumes the same type for them:) Int is a good type in itself,
not to be mixed with rationals.  The fact that something is an integer
should be expressible as a statement about its type. Many operations
require ints and don't accept rationals. It's natural to think about
them as about different types.
> I agree, ints shouldn't be mixed with rationals. But floats
could. This argument is the main reason why I said most people
compared rational with integers. Many operations that requires ints
and don't accept rationals also don't accept floats.

Other arguments:
- Slow: Doing addition and subtraction in fractions sure is expensive,
but doing division (the heaviest arithmetic operation) is extremely
fast in fractional numbers compared to in floating numbers. It is
clear that doing two integer multiplication and switching numerator-
denominator is much faster than doing a single float division.
- Memory Intensive: To represent 1/3 to infinite accuracy requires two-
integer-space (theoretically, 2 bytes). There are some numbers that
are hard to represent in fractions, yes, but in general those numbers
could be represented using two-long-space (variable-width longs). And
whenever accuracy isn't that important, it could be possible to create
a method that would lossily approximate the current fraction to an
acceptable length. Anyway, most computers nowadays is packed with
gigantic memory, why bother with such a small issue.
- Rationals must present themselves as decimal floats or it'll be
confusing: There will be no confusion in a good written code.
Progammers that writes good code would always use the 'behind-the-
scene' number, they wouldn't convert a previously 'string'ed number
back into calculation. And a convention can be created to represent a
fraction in a single line output (like * for multiplication, / for
division, they don't exist in paper maths) that would completely
eliminate any confusion of the user (well informed about the
convention, most people that never used computer before often tried to
use x and : to represent mult and div), even when the fractional
number is outputted to the foreground UI.

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


Re: About Rational Number (PEP 239/PEP 240)

2007-12-15 Thread Lie

The easiest implementation of using fractional datatype is probably to
add a new operator. Some scientific calculators provide a special
operator to signify a fraction (somewhat on the shape of a small L in
mine) and I strongly believe that their internal calculation probably
used fractions even when regular division is used, only when the
calculator have difficulties using fraction (like calculating sin/cos/
tan function) or the screen is not wide enough to represent the
fraction would it use regular division.

Python implemented complex numbers, why not fractions?

Random ramble past here:
Actually, my vision would be not only fractions, but also rooted
number (square root, cube root, etc), it could be possible to
implement a type where a number consist of a rooted number times a
multiplier plus a variable [a + b * root(c, d)]. But I guess this
would be extremely complex and it requires nesting, probably very slow
if implementation isn't good. The advantage of using such is much
faster operations, as long as str() is not called. This actually
reflects my way of doing paper math, I save the lossy operations
(float division, root, trigonometric function) until the very end of
calculation (I'm not fundamentalist though, so compromise sometimes is
done here and there).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Rational Number (PEP 239/PEP 240)

2007-12-15 Thread Lie
On Dec 16, 4:55 am, "Fredrik Johansson" <[EMAIL PROTECTED]>
wrote:
> On Dec 15, 2007 10:05 PM, Lie <[EMAIL PROTECTED]> wrote:
>
> > Random ramble past here:
> > Actually, my vision would be not only fractions, but also rooted
> > number (square root, cube root, etc), it could be possible to
> > implement a type where a number consist of a rooted number times a
> > multiplier plus a variable [a + b * root(c, d)]. But I guess this
> > would be extremely complex and it requires nesting, probably very slow
> > if implementation isn't good. The advantage of using such is much
> > faster operations, as long as str() is not called. This actually
> > reflects my way of doing paper math, I save the lossy operations
> > (float division, root, trigonometric function) until the very end of
> > calculation (I'm not fundamentalist though, so compromise sometimes is
> > done here and there).
>
> You're looking for a computer algebra system. Try 
> sympy:http://code.google.com/p/sympy/
>
> Fredrik

Yeah, that's why I consider them too complex for being included as a
core of a general programming language like Python. Nevertheless,
fraction datatype _IS_ elementary enough to be included as core
language feature.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Lie
> Rationals are not that simple.

So do complex number, in fact most people are much more familiar with
rationals/fractions than with complex number. And notice that I don't
use the word simple, I use the word elementary. Elementary doesn't
always means simple (although it usually is), but rather it emphasizes
on it being essential and being a basic building block for other
things.

And if you think about it, floating numbers aren't that simple either.
It only seems simple because it's implemented natively in the
hardware, but I'm sure the engineers creating them have a heated
discussion when they first try to implement it. Remember the
discussion about Decimals? How many rounding methods are there?

> * Unless you are working under very controlled conditions, rationals
> very quickly grow enormous numerators and denominators, hence
> require arbitrary precision integers (which, I concede, are part of
> Python).

One part of the problem is solved (arbitrary length integers) another
problem is the growth of rationals. That could have easy workaround,
like a scientific calculator, by using a special operator to construct
a fractions, people would only _consciously_ use fractions, avoiding
unexpected return of fraction AND controlled environment for using
fraction. It's also possible to have lossy_simplify(n[, acc]) method
for calculations that need rationals but don't need such accuracy (in
that case, perhaps float could be a better substitute).

> * In order to have a canonical representation of integers, they need
> to be kept in normalised form.

There are methods to simplify fractions and there are addition,
subtraction, division, multiplication, etc can be made to
automatically returns the most simple form.
[btw, off topic, in music, isn't 1/4 and 2/8 different? I'm not very
keen of music though, so correct me if I'm wrong.]

> * Having yet another numerical type would make it difficult what
> type to expect from a calculation.
There is a simple rule of thumb:
If a (built-in) method receives floats returns floats, else returns
fractions << Please don't take me too literally here, apply some
compromises.
The rationale is simple: Float's can't be turned easily into fraction,
while the otherwise involves only a simple true division.

> Which only seems to me to prove that having integer division return
> a floating value is a mistake
Oh no, it's not a mistake. Only IEEE's floating point standard isn't
sufficient to cope with exact arithmetic. Another reason to use
fractions.

> So while rationals might be useful to have available for
> some things, you should have to explicitly ask for them.
> Returning rationals from '/' applied to integers would
> be a bad idea, for example.

> From my reading of the PEP, it doesn't suggest such automatic
> coercions (neither rejects them explicitly though). Given the huge
> discussions about integer vs true division, it would be very
> controversial to suggest implicit rational division.

Which I agree, implicit rational division would be evil. People should
explicitly use fractions, using a special division operators, just
like calculators (although mine seems to always use fractions 'behind-
the-scenes' whenever possible, but on presenting them to the user it
does the rule of thumbs I mentioned).

> Regardless, a builtin (or at least standard library) rational type
> would be nice to have. Of course folks that *really need* rationals
> are already using some 3rd party library, but for the rest of us it
> would be an improvement in several cases where currently floats are
> used, just like the motivation for Decimals. Only difference seems to
> be that there aren't so many or compelling use cases for rationals as
> for decimals (mainly money counting).

People have, for ages used floating numbers in calculation on
occasions where it shouldn't be used, and that's a really bad practice
and even prominent (paper) mathematician are accustomed to such
practice. Floating numbers involves rounding and continued use of them
would make the value wanders off far away.
-- 
http://mail.python.org/mailman/listinfo/python-list


Odd behavior in Python/Tkinter?

2007-12-21 Thread Lie
Inspect the following code:

--- start of code ---
import Tkinter as Tk
from Tkconstants import *

root = Tk.Tk()

e1 = Tk.Entry(root, text = 'Hello World')
e2 = Tk.Entry(root, text = 'Hello World')

e1.grid(row = 1, column = 1)
e2.grid(row = 2, column = 1)

e1.insert(END, 'Hello Python')

root.mainloop()

--- end of code ---

What do you expect the result should be?
a. Two textboxes: One contains 'Hello Python', the other 'Hello World'
b. Two textboxes: Both containing 'Hello World'
c. Two textboxes: Both containing 'Hello Python'
d. Two textboxes: Both empty
e. Don't know

Check your guess with your Python 2.5.1 (AFAIK, the latest version at
the moment of writing)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to handle multi-line quotes

2007-12-21 Thread Lie
On Dec 22, 2:15 am, [EMAIL PROTECTED] wrote:
> Thinking about unclosed multi-line quotes.
>
> When you open a multi-line quote (type '"""') what does your editor
> do? Does it color the remainder of your text as a quote, or does it
> color the line with the open quote as a quote and leave the rest of
> your code alone?
>
> What do you want it to do?
>
> This is a tokenizer question in disguise, of course. The simple way to
> handle it, which is what my editor sees, is for the tokenizer to
> return the remainder of the text as one great UNCLOSED_MULTILINE_QUOTE
> token. The alternative is to assume that the line with the unclosed
> quote is in error and to continue to tokenize the rest. An editor
> might blink or otherwise draw attention to the unmatched quote.

Are you asking about IDLE? If it is, IDLE considers the remainder of
the code as part of multiline-quote and thus colors them green (in
default color scheme). This behavior is consistent with any other code
editors way of handling multiline comments (Frontpage, Dreamweaver,
etc). IMHO, it is a fine behavior, such a huge color change would be
immediately noticed by any non-color-blind people and they'll
immediately close the multiline (perhaps in panic) before filling the
multiline.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception message output problem

2007-12-21 Thread Lie
On Dec 22, 2:57 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> I am baffled about why my exception messages are not displaying
> properly.
>
> I have a class that represents physical scalars with units. If I type
>
> >>> 3 * s + 4 * m
>
> I should get something like this:
>
> scalar.InconsistentUnits: 3 s, 4 m
>
> to show that seconds cannot be added to meters.  Instead, the message
> is broken up into individual characters, like this:
>
> scalar.InconsistentUnits: ('3', ' ', 's', ',', ' ', '4', ' ', 'm')
>
> This worked correctly for months, so I don't understand what went
> wrong. I am using version 2.5.1 on a Dell workstation with Red Hat
> Enterprise WS Linux.
>
> As far as I can tell, I am doing everything "by the book." Here is my
> exception class:
>
>     class InconsistentUnits(Exception):
>         def __init__(self, args=""): self.args = args
>
> and here is my instantiation of it:
>
>         raise scalar.InconsistentUnits, str(self) + ", " + str(other)
>
> I've tried various little changes, but nothing seems to make any
> difference. Has anyone else noticed this sort of behavior? Thanks.
>
> By the way, my scalar class is available for free 
> fromhttp://RussP.us/scalar.htm
> . A complete user guide is available. Check it out. I think you'll
> like it.

The problem is in the InconsistentUnits Exception. It seems that the
act of:
self.args = 'Some String'
would break the string into chars, possibly because self.args think
'Some String' is a tuple of some sort.

Change the exception into this:
class InconsistentUnits(Exception):
def __init__(self, args=""): self.args = (args,)
# Python have an odd (read: broken) singleton implementation
# single member tuple must have a comma behind it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behavior in Python/Tkinter?

2007-12-21 Thread Lie
On Dec 22, 4:05 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > Inspect the following code:
>
> > --- start of code ---
> > import Tkinter as Tk
> > from Tkconstants import *
>
> > root = Tk.Tk()
>
> > e1 = Tk.Entry(root, text = 'Hello World')
> > e2 = Tk.Entry(root, text = 'Hello World')
>
> the "text" (or "textvariable") option to the Entry widget is the name of
> the Tcl variable that should hold the result.
>
> to get something that's a bit more usable from Python, use a StringVar
> instance instead.  alternatively, use the "get" method to fetch text
> from the widget, and the "insert" method to add text to it.
>
> also see:
>
>      http://effbot.org/tag/Tkinter.entry
>
> 

I realized that 'text' isn't a normally valid arguments for Entry (and
I'm also aware about the insert, get, etc), but what makes me creep is
the fact that the Entry's value would mirror each other if they're set
to the same 'text' value (Actually, I'm interested on how they
implement the Tkinter's/Tcl/Tk Entry box that this kind of behavior
could ever possibly exist [I started Pythoning just two weeks ago, so
my knowledge on its internals is quite limited]).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behavior in Python/Tkinter?

2007-12-22 Thread Lie
On Dec 22, 1:42 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> >>> Inspect the following code:
>
> >>> --- start of code ---
> >>> import Tkinter as Tk
> >>> from Tkconstants import *
> >>> root = Tk.Tk()
> >>> e1 = Tk.Entry(root, text = 'Hello World')
> >>> e2 = Tk.Entry(root, text = 'Hello World')
>
> >> the "text" (or "textvariable") option to the Entry widget is the name of
> >> the Tcl variable that should hold the result.
>
> >> to get something that's a bit more usable from Python, use a StringVar
> >> instance instead.  alternatively, use the "get" method to fetch text
> >> from the widget, and the "insert" method to add text to it.
> > I realized that 'text' isn't a normally valid arguments for Entry (and
> > I'm also aware about the insert, get, etc), but what makes me creep is
> > the fact that the Entry's value would mirror each other if they're set
> > to the same 'text' value
>
> note that you've set the "textvariable" option, not the "text" option.
> Tk allows you to abbreviate option names.
>
> and since you've set the "textvariable" option for both widgets to the
> same variable, you've asked them both to display the same variable.
> Tkinter just does what you've asked it to.
>
> this is no different from using a Tkinter variable to display the same
> value in a number of radiobutton widgets.
>
> 

But an expression (e.g. string) is NOT a variable. It's fine if the
value mirrored when I set the textvariable conf to the same variable,
but in this case I'm setting them to the same expression (e.g. string).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception message output problem

2007-12-22 Thread Lie
On Dec 22, 6:18 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Lie a écrit :
> (snip)
>
> > # Python have an odd (read: broken) singleton implementation
> > # single member tuple must have a comma behind it
>
> You may call it weird or even a wart if you want, but given that what
> makes the tuple is the comma - not the parens[1] -, it is _not_ broken.
>
> [1] with the exception of the empty tuple.


I also realized that you don't need to use parens to make tuple, it's
rather my habit to always use parens in making a tuple (because "print
'%s + %s + %s' % (a, b, c)" _must_ have a parens (otherwise Python
thinks b and c is arguments for the print not for the string
formatting) and because Python always return a tuple w/ parens)

PS: My wording on broken doesn't actually means broken so it won't
work, but rather broken syntactically, making the syntax inconsistent,
funny, illogical, etc. One could argue though that the trailing comma
is a formalized workaround.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception message output problem

2007-12-22 Thread Lie
PPS: Actually, what makes a tuple is both the parens and the comma,
with comma as the minimum signifier, inspect this: "str(a) +
str((a,b,c))", you have to use the double parens, one to make the
tuple and the other as part of the str. This harmless little case
gives error if done without the double parens, but what would happen
if we exchange the str into a function that accepts one argument and
several optional arguments (or better yet, one argument and an
optional * argument)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behavior in Python/Tkinter?

2007-12-22 Thread Lie
> But an expression (e.g. string) is NOT a variable. It's fine if the
> value mirrored when I set the textvariable conf to the same variable,
> but in this case I'm setting them to the same expression (e.g. string).

On the other hand, the oddness multiplied since the value replication
doesn't happen if I set the textvariable to a variable. So, why is it?
A checkbox/optionbox value replication works if they're set to a
variable (I don't know if they're set to an expression) but Entry's
value replication works only if they're set to expression not variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd behavior in Python/Tkinter?

2007-12-22 Thread Lie
On Dec 22, 7:35 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > But an expression (e.g. string) is NOT a variable.
>
> in this case, it is.  I don't know if it's worth spending more time on
> this, since you're not listening, but let's make one more attempt.

Sure I'm listening (well, actually I'm reading), but please spare me
since I can't understand what you meant in the previous posts (I'm
just starting Python, and yesterday was my first introduction to
Tkinter/Tk/Tcl). Everyone has their own newbie moments...

> for the Entry widget, the "textvariable" argument, if given, identifies
> an *internal* Tkinter variable (managed by the embedded Tcl inter-
> preter, not Python).  changes to this variable will be reflected in the
> widget, and changes to the widget will be reflected in the variable.

That clears things up. I never realized that we can even specify the
name for the Tcl's variable, setting its values is a behavior, but
setting its name is... some kind of incomplete encapsulation (well its
understandable, complete encapsulation is never a Pythonic thing and
proper ways to keep the encapsulation is available [through
StringVar]).

> the *usual* way to create such a variable is to use StringVar, and leave
> it to Tkinter to come up with an internal variable name, but you can
> refer to any Tcl variable; if it doesn't exist, it's created.
>
> in your example, you told both widgets to use the same internal
> variable.  you can do the same thing with a StringVar:
>
>      var = Tk.StringVar()
>
>      e1 = Tk.Entry(root, textvariable = var)
>      e2 = Tk.Entry(root, textvariable = var)
>
> doing this has the advantage that you can access the internal variable
> via the StringVar object (held in the Python variable named "var"), but
> at the Tkinter level, it's exactly the same thing.  changes to the
> variable will be reflected in both widgets, and changes to *either*
> widget will be reflected in the variable, and therefore also in the
> other widget.



>  > On the other hand, the oddness multiplied since the value replication
>  > doesn't happen if I set the textvariable to a variable.
>
> sure does, if you use the same internal variable for both widgets.

After reading your post, I realized the reason why it doesn't
replicate was because I set the variable to an empty string, which
doesn't initialize the textvariable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception message output problem

2007-12-22 Thread Lie
On Dec 23, 4:30 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Lie a écrit :
>
> > PPS: Actually, what makes a tuple is both the parens and the comma,
>
> Nope, it's definively the comma. You can check the language's grammar,
> it's part of the doc. Or just test FWIW:
>
> Python 2.4.3 (#1, Mar 12 2007, 23:32:01)
> [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on
> linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> a = 1,
>  >>> type(a)
> 
>  >>>
>
> > with comma as the minimum signifier, inspect this: "str(a) +
> > str((a,b,c))", you have to use the double parens, one to make the
> > tuple and the other as part of the str.
>
> This is a problem of operator precedence.

I think some people have misunderstood me, I know parens isn't a
formal definition for tuples, but it's more or less a de facto
grammar, as it is hard to create parens-less tuples without the
interpreter mistaking it for other things, except for a few cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL in Windows Folder

2007-12-24 Thread Lie
On Dec 25, 3:04 am, "Markus Gritsch" <[EMAIL PROTECTED]> wrote:
> On 24/12/2007, Chris Mellon <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 23, 2007 12:27 PM, Markus Gritsch <[EMAIL PROTECTED]> wrote:
> > > On 23/12/2007, Christian Heimes <[EMAIL PROTECTED]> wrote:
> > > > Markus Gritsch wrote:
> > > > > why does the Python installer on Windows put the Python DLL into the
> > > > > Windows system32 folder?  Wouldn't it be more clean to place it into
> > > > > the Python installation folder beside the python.exe file?
>
> > > > It's the easiest and best way to expose Python for 3rd party
> > > > applications and COM. The DLL is removed by the Windows Installer when
> > > > its usage counter drops to 0. There is no need to worry ;)
>
> > > I am not worrying about an orphaned DLL.  The Problem is that this way
> > > the Python DLL is being made available for 3rd party applications,
> > > which possibly need a version of Python which is compiled using
> > > another compiler.  We are embedding Python into our application which
> > > gets compiled using MSVC 8.0.  We like to link dynamically, so the
> > > Python interpreter is not statically linked into the program.  The
> > > Python DLL from the Python installer in the Windows system32 folder is
> > > compiled using MSVC 7.1.
>
> > What the python installer is doing is the Right Thing for making the
> > standard python dll available to third party applications.
>
> But this forces the 3rd party application being compiled with the same
> compiler as the Python DLL which is MSVC 7.1 for Python 2.5 which is a
> quite old compiler nowadays.

Unfortunately, Windows doesn't give a lot of support around preventing
DLL duplication. It is regular to found multiple duplicate DLLs on a
Windows system (especially for different version), a common example is
msvcrtxx.dll, which is C's runtime, many program pack their own msvcrt
into their installation package. Therefore it is important for a
windows program to include all the required DLLs into the installer
package and use their own, unless they're sure that they can use other
version (good programs are not DLL implementation specific and good
DLLs maintain a stable interface).

> > Applications that want a specific version of a specific DLL should use
> > the mechanisms available for doing so, instead of relying on there
> > being a specific version of the python dll in the windows folder.
>
> We do not rely on having some specific version of the Python DLL in
> the Windows system 32 folder.  However, the MSVC 7.1 compiled version
> gets in the way when using a different compiler.

If that's the case, just use the MSVC 7.1's compiled code, there won't
be much difference. If you insist to use your own version (or don't
have a choice), you could instead pack your own DLL, use the local
DLL, and ignore the system's DLL. That's the Best Practice in Windows.

> Kind regards,
> Markus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL in Windows Folder

2007-12-26 Thread Lie
On Dec 27, 12:30 am, "Markus Gritsch" <[EMAIL PROTECTED]> wrote:
> On 26/12/2007, Lie Ryan <[EMAIL PROTECTED]> wrote:
> > > On Dec 25, 2007 4:43 PM, Markus Gritsch <[EMAIL PROTECTED]> wrote:
> > > On 24/12/2007, Lie <[EMAIL PROTECTED]> wrote:
>
> > > > (good programs are not DLL implementation specific
>
> > > Assume an application embedding Python being compiled with MSVC 8.0.
> > > It uses the runtime msvcr80.dll.  If you now pass objects created in
> > > your application to the Python interpreter which is compiled with MSVC
> > > 7.1 which uses msvcr71.dll, you are asking for serious trouble.  It is
> > > not a matter of being a "good program".
>
> > don't cut my word, good programs aren't DLL implementation specific and good
> > DLL have consistent interface (consistent interface implies consistent
> > behavior). Of course this is a bit "utopia", as most DLL would sadly have to
> > change its interfaces once or twice and it is sometimes impossible for
> > programs to be completely free from its DLLs implementation
>
> Instead of being upset about cutting your word (which was not my
> intention, sorry about that), it would be nice if you could make a
> statement concerning the problem I mentioned: Having an object being
> created by one MSVC runtime, msvcr80.dll and passing it to another
> one, msvcr71.dll.

I'm not upset, but if my wording seems to be like an upset person I'm
sorry, English is not my first language, and I'm very bad at choosing
words.

A simple solution (but possibly inefficient, if the object is complex
and need to be exchanged thousands of times) for the problem mentioned
is to convert the object to a common agreed format that both sides can
understand when transferring the data such as a simple string (not a
string object, just simple string with no strings attached: pun (not)
intended).

In your case, which is:
> Assume an application embedding Python being compiled with MSVC 8.0.
> It uses the runtime msvcr80.dll.  If you now pass objects created in
> your application to the Python interpreter which is compiled with MSVC
> 7.1 which uses msvcr71.dll, you are asking for serious trouble.  It is
> not a matter of being a "good program".

No, you're not asking for trouble, you're passing the object to the
Python DLL, not to the msvcr71 behind the Python so it shouldn't be a
problem in a good designed program and DLL. This isn't a case about
msvcr71 talking with msvcr8, nor it is msvcr71 with your program, nor
it is msvcr8 with Python DLL, this is a case of Your Program talking
to Python DLL.

One way to solve this is:
Assuming you don't have access to Python internals (although since
Python is open source, you do have access) you could build a wrapper
around Python Interpreter. The wrapper has two functions. One: accepts
a string input (string as simple string, not string object) that
describes the original object and returns a file that Python can pick
with pickle. Two: accepts a pickled object and returns a string that
describes the pickled object that Your Application could understand.

This functions could be built in into Your Application, but the
easiest way is to build the wrapper with Python, as you won't need to
know how to read and write pickled file.

For a simple case, where the object that needs to be passed is
predetermined your function could just pass any data that is required
to reconstruct the original object to the wrapper (for example, in a
vector class, just the values of x, y, z), a versatile way to pass
them is by command-line arguments, like "wrapper 1 2 3 > output". The
wrapper would add any other required infos (methods, operator
overloads, etc) before pickling the object and call the Python DLL to
unpickle the object. For the vice versa case, the wrapper unpickle the
file returned from Python DLL, and convert it to a format Your Program
could understand, then notifying your program.

Of course there may be other easier, more efficient ways to solve this
problem, but this is a proof-of-concept that it is possible to compile
your application in VS8 while still using the official VS
Python.

But I can't think of a need why Python DLL needs to be used like this
though

> > > > If that's the case, just use the MSVC 7.1's compiled code, there won't
> > > > be much difference.
>
> > > See above.
>
> > I think you don't get my point... if you don't modify the python interpreter
> > (from what I understand, you just recompile your Python DLL without
> > modification), there is no need to compile your own interpreter, it just
> > makes problem and the performance benefits is outweighed by the pro

Re: convert pdf to png

2007-12-27 Thread Lie
On Dec 27, 7:33 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Good point.  Not that I am willing to risk it (just using the pdf is not
> > such a bad option)  but I am wondering if it would make sense to create
> > a ramdrive for something like this.  if memory is needed, swap would
> > happen, which should be better than creating files.
>
> You mean permanently deprivating your server of it's precious ram than
> only temporarily? And so far, swapping has always been the worst thing
> to happen for me - whereas mere disk-IO didn't slow _everything_ down.
>
> You should really check your premises on what is affecting performance,
> and what not. And get a faster server...
>
> Diez

What resources this server is lacking currently?
Harddisk space
Harddisk bandwidth (the server just wouldn't stop reading/writing at
peak times)
RAM
Network
CPU

In short, what resource is the most precious and what resources you
still have spares?

Possible option:
* Serve the PDFs directly
--> Harddisk space - low, as it's not converted
--> Harddisk bandwidth - low, depends on how much its requested
--> RAM - low, virtually no RAM usage
--> Network - low, depends on how much its requested
--> CPU - low, virtually no processing is done
--> The simplest to implement, moderate difficulty for users that
don't have PDF reader
--> Users that don't have a PDF reader might experience difficulties,
nowadays most people have Adobe Reader on their computer, and most
people at least know about it. Many computers are also preinstalled
with a pdf reader.

* Preconvert to PNGs, the conversion is done at another computer to
not restrain the server
--> Harddisk space - High, as file is saved as image file
--> Harddisk bandwidth - Moderate, as there are many files and overall
are big
--> RAM - low, virtually no RAM usage
--> Network - Moderate, as the total file served is big
--> CPU - Low, virtually no processing is done
--> Simple

* Serve a precompressed, preconverted PNGs
--> Harddisk space - Moderate-high, should be smaller than just PNG
--> Harddisk bandwidth - Moderate-High, as files can't be served in
chunks
--> RAM - Low, Virtually no RAM usage
--> Network - High, as files can't be served in chunks
--> CPU - Low, virtually no processing is done
--> Moderately-Simple
--> Might be problem if users don't have unzipper (XP, Vista, and most
Linux provides unzipper on default installation, older OSes might not)
--> Files can't be served in chunks, users have to download whole zip
before opening any

* Convert the PDFs to PNG on the fly:
--> Harddisk space - Low, take as much as serving direct PDF
--> Harddisk bandwidth - Moderate to Low, depending on implementation
--> RAM - Moderate, as processing is done, RAM is clearly needed
--> Network - Moderate, as the files served as PNG
--> CPU - High, complex processing is done on the CPU before the file
can be sent to the network
--> Complex to implement

Seeing these options, I think it is much better to serve the PDFs
directly, it's very simple, and very efficient on the server. If
you're afraid that not everyone have PDF readers, direct them to
Adobe's site or serve the installation files on the server. The
installation for the reader is a one-off download, so it should only
choke the server for the first several weeks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cloud computing (and python)?

2008-01-05 Thread Lie
> I mean, really, I've been using web-mail and various varieties of
> remote
> storage for over a decade.  What is *new* about the concept?  (I see
> some
> hints above, but it's mixed in with a lot of other stuff...)

In essence, you're correct, this concept of cloud computing actually
have existed for some time, but there is a difference between the
"classic" cloud computing and "new" cloud computing. The classic cloud
computing is rather limited emails, bbs, newsgroup, etc while the new
cloud computing also refers to the newly available scope such as word
processing, image processing, and even video editing.

In essence they're the same, you store your files on their server, and
you used a webbased tools to access your file, but nowadays people
wouldn't consider the classic cloud computing a cloud computing
anymore, as they've become too "normal".

It's not a completely meaningless marketing buzz phrase, the concept
has existed for some time, but the word is new.

Another way to look at this is: "classic" cloud computing are cloud
computing that is done because it can't be done the other way (what
use is an email address if you could only receive emails if your
desktop is always on, what use is a newsgroup if people could only
post if they are physically in front of the computer hosting the
newsgroup). While the "new" cloud computing refers to applications
that previously exist as desktop applications, but now ported to
become web-based applications, meaning the application could be usable
without the "cloud", but some features like universal availability
could not be used.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic inheritance question

2008-01-05 Thread Lie
On Jan 5, 5:40 pm, [EMAIL PROTECTED] wrote:
> Jeroen Ruigrok van der Werven wrote:
>
> > Shouldn't this be:
>
> > self.startLoc = start
> > self.stopLoc = stop
>
> Thanks! Of course it should. Old Java habits die slowly.

No, seriously it isn't Java habits only, most other languages wouldn't
need explicit calling of class name.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does **kw mean?

2008-01-11 Thread Lie
On Jan 11, 4:38 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I've been reading the following example, and couldn't figure out, what
> **kw mean. (It's an empty dictionary, but what's the semantics):

It's a keyword argument. It's some kind of repository for arguments
that aren't recognized.

If you have function like this:
def func(a, *args, *kw):
print a
print args
print kw

and you call the functin like this:
func('value A', 'value B', 'value C', argumentA = 'value D', argumentB
= 'value D')
the extra arguments would normally raise an error, but with the * and
**, Python would:
- assign 'value B' and 'value C' to args
- assign 'argumentA':'value D' and 'argumentB':'value E' to kw

so if you run the function, it will output:

value A
('value B', 'value C')
{'argumentB': 'value E', 'argumentA': 'value D'}


this args and kw can be accessed like a tuple and dictionary
respectively

See '4.7.2 Keyword Arguments' and '4.7.3 Arbitrary Argument Lists' on
Python Help File
-- 
http://mail.python.org/mailman/listinfo/python-list


Property with Arguments

2008-01-11 Thread Lie
Is there a way to create a property with arguments? Or an index value
like a list?

To be used in the form like:

someClass.someProperty['arguments'] = 'some value'
or
someClass.someProperty('argument1', 'argument2') = 'some value'

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


Re: Property with Arguments

2008-01-11 Thread Lie
On Jan 11, 6:20 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > Is there a way to create a property with arguments?
>
> That's called method in Python, and has it's own syntax.  You cannot
> assign to methods.

So you've got to use methods? It was in VB.NET that I learned about
property with arguments, which is basically passing multiple values to
the property, one of which is considered the real value and the others
are metadata values. Now that I thought about it, I could use tuple to
pass multiple values... well there is a missing semantic concerning
which are real values and metadata values, but it doesn't really
matter.

>  > Or an index value like a list?
>
> Make the property that returns a list-like object (hooking __getitem__,
> __setitem__, etc).
>

well, I want to avoid creating an object or (worse) modifying existing
object, as the program I'm working on is very short and simple, and I
want to keep it that way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Exceptions - How do you make it work like built-in exceptions?

2008-01-13 Thread Lie
A built-in exceptions, when raised, would print traceback that points
out the offending code, like this:

Traceback (most recent call last):
  File "F:\dir\code.py", line 43, in 
a = 1/0 <<<---
ZeroDivisionError: integer division or modulo by zero

a user-made exception, when raised, would print traceback that points
out the code that raises the exception

Traceback (most recent call last):
  File "F:\dir\code.py", line 48, in 
raise SomeException('Some Exception Message') <<<---
SomeException: Some Exception Message

which is generally of little use (yeah, it's possible to trace the
code from the line number, but sometimes it might not be that easy,
cause the line number is (again) the line number for the raising code
instead of the offending code)

The sample exception was generated from this code:

class SomeException(Exception):
pass

try:
a = 1/0
except:
raise SomeException('Some Exception Message')


Is it possible to make the user-made exception points out the
offending code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic inheritance question

2008-01-14 Thread Lie
On Jan 7, 2:46 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Lie a écrit :
>
> > On Jan 5, 5:40 pm, [EMAIL PROTECTED] wrote:
>
> >>Jeroen Ruigrok van der Werven wrote:
>
> >>>Shouldn't this be:
>
> >>>self.startLoc = start
> >>>self.stopLoc = stop
>
> >>Thanks! Of course it should. Old Java habits die slowly.
>
> > No, seriously it isn't Java habits only, most other languages wouldn't
> > need explicit calling of class name.
>
> Where is the "explicit calling of class name" exactly ?

Perhaps I was a bit tired when writing that (I wouldn't understand
what I wrote if I were you)... what I meant is most other languages
doesn't usually enforce us to explicitly state the containing class
name, which in python is generally called "self". Most other languages
1) automatically assign the containing class' object in a keyword
(Java: this, VB: Me) behind the screen, and 2) automatically searches
variable name in both the local variable table and the containing
class variable table (so to refer to a class variable named var from a
method inside the class, we only need to write var, not self.var as in
python). In VB, Me is extremely rarely used, in Python, self is all
over the place. Well, there is positive and negative to both sides,
convenience in VB, and flexibility in Python.

Compare the following codes:
VB.NET:
Public Class A
Dim var
Public Function aFunction()
return var

Python:
class A:
def aFunction(self):
return self.var
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exceptions - How do you make it work like built-in exceptions?

2008-01-14 Thread Lie
On Jan 14, 1:51 am, "Mark Tolonen" <[EMAIL PROTECTED]>
wrote:
> "Lie" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
>
>
> >A built-in exceptions, when raised, would print traceback that points
> > out the offending code, like this:
>
> > Traceback (most recent call last):
> >  File "F:\dir\code.py", line 43, in 
> >    a = 1/0 <<<---
> > ZeroDivisionError: integer division or modulo by zero
>
> > a user-made exception, when raised, would print traceback that points
> > out the code that raises the exception
>
> > Traceback (most recent call last):
> >  File "F:\dir\code.py", line 48, in 
> >    raise SomeException('Some Exception Message') <<<---
> > SomeException: Some Exception Message
>
> > which is generally of little use (yeah, it's possible to trace the
> > code from the line number, but sometimes it might not be that easy,
> > cause the line number is (again) the line number for the raising code
> > instead of the offending code)
>
> > The sample exception was generated from this code:
> > 
> > class SomeException(Exception):
> >    pass
>
> > try:
> >    a = 1/0
> > except:
> >    raise SomeException('Some Exception Message')
> > 
>
> > Is it possible to make the user-made exception points out the
> > offending code?
>
> The raise statement *was* the offending (unhandled exception) code.  The
> ZeroDivisionError was handled by your except clause.
>

Well, what you meant by offending code and what I meant by offending
code is different, what I meant by offending code as the code that
makes the exception _need_ to be called (i.e. the a=1/0) and in my
view (in this case), anything inside the except clause is not a real
code, as it doesn't do anything "useful" for the program.

> You can override the traceback your exception will use with the
> three-expression form of the raise statement (See Section 6.9 "The raise
> statement" in the Python Reference Manual) by passing the traceback of the
> original exception:
>
> ## CODE #
>
> import sys
>
> class SomeException(Exception):
>     pass
>
> try:
>     a=1/0
> except:
>     org_type,org_value,org_traceback = sys.exc_info()
>     raise SomeException,'had some problems with this code',org_traceback
>
> ## OUTPUT ##
>
> Traceback (most recent call last):
>   File "exc.py", line 7, in 
>     a=1/0
> SomeException: had some problems with this code
>
> --Mark

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


Re: How to get user home directory on Windows

2008-01-14 Thread Lie
On Jan 14, 8:21 am, "Martin P. Hellwig" <[EMAIL PROTECTED]> wrote:
> Giampaolo Rodola' wrote:
> > Hi all,
> > I'm trying to use the pywin32 extension to find out the user's home
> > directory but currently I didn't find a solution yet.
> > What I'd need to do is not getting the home directory of the currently
> > logged in user but something like:
>
>  get_homedir("frank")
> > "C:\home\users\frank"
>  get_homedir("josh")
> > "C:\home\users\josh"
>
> > Is there a way to do that?
> > I tried to search through the Pywin32 documentation with no luck.
> > In addition I'm not practiced with the Windows API at all.
>
> Well, windows, to my knowledge, uses the same base path for all profiles
> (this is not true for the My Documents folder which can differ). So what
> you could do is get the location from the ALLUSERPROFILE environment
> variable, go one folder higher and iterate through that.
> Ignoring the folders for the 'pseudo' users: 'All Users', 'Default
> User', 'LocalService' and 'NetworkService'.
>
> hth
> --
> mph

There is one problem with that, sometimes the folders for the users
are not the same with the user name, usually because of deleting user
name without deleting the profile, then recreate a user with similar
name. It doesn't happens everytime, but it could.

Possibly it is possible to get the SID of the user name (using the way
described in Tim Golden's Microsoft Link' post), then find the user
directory from the registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft
\Windows NT\CurrentVersion\ProfileList\[PUT SID HERE]\Profile Image
Path
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__ explanation please

2008-01-15 Thread Lie
I've been in this Python mailing list for a few days, and I've noticed
several things here: There are too many fundamentalist!

Don't play stupid and all, don't be a fundamentalist. It might be true
that __init__ isn't a constructor and __new__ might be the constructor
(some people even claimed __new__ is also not a constructor).

>From the base definition of a constructor: constructor is the creator
of an object. In this case, __new__ is technically the constructor
while __init__ is an initializer.

However, it is also to be noted that __init__ is what makes an object
meaningful, and that makes it a constructor in a sense (while still
technically a constructor). Without initialization, an object is
meaningless, even if the definition of the initializer is to leave it
as it is.

Python creates object by doing something like this:
a = anObject(arg1, arg2, arg3)

These arguments is then passed to __new__ and __init__ for their
arguments in its sake of creating and initializing the object. Then
anObject() returns an instance of anObject.

>From an outsider's point of view, there is no difference between
__new__ and __init__ since they're "implementation details" (in other
languages, these are private functions[1] that is invisible to
outsiders, Python doesn't like privacy but the semantic of being
implementation detail still exist). For an outsider, there is
absolutely no need to know that __new__ and __init__ exists, they just
need to know anObject()'s arguments, which is the public view of the
constructor and initializer[2].

[1] Well, for fundamentalists: constructors aren't usually private
though, usually they're Friend or Protected Friend which prohibits
outsiders from calling it but allow other classes inheriting from it
to call them.
[2] In this sense, from outsider's POV anObject() is the constructor.


If you can't be convinced with this argument, then I'd give you
another that's a bit more Pythonic:
DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
like a duck, it is a duck!

>From the class programmer's point of view, __init__ acts like an
object constructor in other languages, there is no significant
difference between __init__ and constructor in other languages. The
fact that __init__ works with side-effect as opposed to returning the
object is not a significant point and can be considered as an
implementation difference (I'm not aware of any major programming
language that returns an instance of itself in its return value
[except for Python]).

For example, in VB.NET, there is no doubt that Sub New() is a
constructor, despite New() works only by side effect, and returning
anything results in an error (since it is a Sub or a method in
Python's dictionary). Not only VB, C++ and C# also use side effect in
its constructors and doesn't return a value. In this sense, VB's New, C
++ constructor, and C# constructor is equal to Python's __init__, thus
the Duck Typing spirit applies here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic inheritance question

2008-01-16 Thread Lie
On Jan 15, 9:00 pm, Bruno Desthuilliers  wrote:
> Lie a écrit :
>
>
>
> > On Jan 7, 2:46 am, Bruno Desthuilliers
> > <[EMAIL PROTECTED]> wrote:
> >> Lie a écrit :
>
> >>> On Jan 5, 5:40 pm, [EMAIL PROTECTED] wrote:
> >>>> Jeroen Ruigrok van der Werven wrote:
> >>>>> Shouldn't this be:
> >>>>> self.startLoc = start
> >>>>> self.stopLoc = stop
> >>>> Thanks! Of course it should. Old Java habits die slowly.
> >>> No, seriously it isn't Java habits only, most other languages wouldn't
> >>> need explicit calling of class name.
> >> Where is the "explicit calling of class name" exactly ?
>
> > Perhaps I was a bit tired when writing that (I wouldn't understand
> > what I wrote if I were you)... what I meant is most other languages
> > doesn't usually enforce us to explicitly state the containing class
> > name, which in python is generally called "self".
>
> 'self' (or whatever you name it) is not the "containing class name",

Current instance is what I meant, thanks for pointing out the
incorrect term I used.

> it's the first argument of the function - which usually happens to be
> the current instance when the function is used as a method.

And that's the point, self (or anything you name it) is almost always
the current instance and that makes it functionally the same as Me and
this in VB and Java.

> > Most other languages
> > 1) automatically assign the containing class' object
>
> s/containing class' object/current instance/
>
> > in a keyword
> > (Java: this, VB: Me) behind the screen,
>
> That's not very far from what a Python method object does -
> automatically assign the current instance to something. The difference
> is that Python uses functions to implement methods (instead of having
> two distinct contructs), so the only reliable way to "inject" the
> reference to the current instance is to pass it as an argument to the
> function (instead of making it pop from pure air).

It isn't very far, but Python makes it obvious about the assignment
(not behind the screen).

> There are some benefits to this solution. One of them is the ability to
>   dynamically assign functions as methods. So if you do have some
> function taking an object as first argument, you can easily turn it into
> a method.

Indeed, many languages doesn't allow dynamic assignment of function
which makes having an automatic assignment of current instance to Me/
this possible and with minimal harm.

> > and 2) automatically searches
> > variable name in both the local variable table and the containing
> > class variable table  (so to refer to a class variable named var from a
> > method inside the class, we only need to write var, not self.var as in
> > python).
>
> This - as you know - cannot work well with Python's scoping rules and
> dynamicity. Anyway, implicit object reference is definitively a
> BadThing(tm) wrt/ readbility, specially with multiparadigm languages
> (like Python or C++). Why do you think s many C++ shops impose the
> m_something naming scheme ?

Implicit object reference for the containing class has little harm, if
a class is so complex that there are more than 10 class-level
variable, then it is obvious that that class needs to be fragmented to
smaller classes. Remembering less than 10 variable and avoiding naming
collision among just 10 variable is not hard (and 10 is really too
many, most classes should only use 2-4 variables), especially if you
have a good IDE that employs Intellisense-like technology (IDLE has
it). And it is always a Bad Thing(tm) to use the same name for two
variable in the class and in function (which is the main and only
source of possible ambiguity) in ANY language, even in Python.

> Anyway, I actually know 3 languages (4 if C# works the same) that has
> this implicit 'this' (or whatever the name) 'feature', and at least 5
> that don't. So I'm not sure that the "most other languages" qualifier
> really applies to point 2 !-)

What's this 5 languages? Are they a mainstream, high-level languages
or lesser known, low-level languages? C-family, Java, and Basic are
the Big Three of high-level programming language.

> > In VB, Me is extremely rarely used,
>
> I used to systematically use it - like I've always systematically used
> 'this' in C++  and Java.

And that is what reduces readability. A proficient VB/C/Java
programmer would frown upon the extra, unneeded garbage as they
thought it was clear already that the variable refers to a class-level
variable. It is 

Re: __init__ explanation please

2008-01-17 Thread Lie
On Jan 16, 5:34 am, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
> > >From the base definition of a constructor: constructor is the creator
> > of an object. In this case, __new__ is technically the constructor
> > while __init__ is an initializer.
>
> > However, it is also to be noted that __init__ is what makes an object
> > meaningful, and that makes it a constructor in a sense (while still
> > technically a constructor). Without initialization, an object is
> > meaningless, even if the definition of the initializer is to leave it
> > as it is.
>
> You don't need to have an __init__ defined.  A subclass has to
> explicitly call the parent's __init__ or the parent's __init__ is never
> run.  

In other languages, constructor might be optional. In the case of non-
existent constructor, compilers would add an empty constructor, but
what's the difference (from programmer's POV) between Python ignoring
__init__ and other languages adding empty constructor? That's just an
implementation detail.

> If the __init__ makes the object meaningful, then how meaningful
> is an object without an __init__?  

It actually depends on the object, some objects might be pretty
meaningless without being initialized (or its members altered from
outside very carefully). Examples include a simple vector class. If
the vector is not initialized, the x and y equals None, which is not a
valid value for vector, which means the object is meaningless.

> I'm pretty sure that an object
> without an __init__ is still a viable, working object.

I'm sure it is, although it's initial value might not be a valid
value.

> > If you can't be convinced with this argument, then I'd give you
> > another that's a bit more Pythonic:
> > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
> > like a duck, it is a duck!
>
> But you don't need __init__ to be a duck!

lol...

> > >From the class programmer's point of view, __init__ acts like an
> > object constructor in other languages, there is no significant
> > difference between __init__ and constructor in other languages.
>
> How many times can you call an object's constructor in other languages?
> __init__ can be called repeatedly.

That's a very good argument to separate __init__ from a real
constructor, but how many projects you do would require object
recycling (which is the only reason I can think of for calling
initializers more than once)? Object recycling should only be done on
systems which lacks resources because it have big potential to
introduce bugs caused by incomplete cleaning.

> __init__ is the last straw that breaks the camel's back.  Or rather, the
> last method we see in the object creation process, and thus must be
> 'guilty' of being a constructor.  Only a fundamentalist would blame the
> victim instead of the real criminal, __new__.

It's not about blaming, rather they shared parts in the act.

> We're splitting hairs.  And I'm pretty sure that, aside from being a
> spiffy thought experiment, no one cares as long as it works and makes
> sense.   =)

I agree with that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic inheritance question

2008-01-20 Thread Lie
On Jan 16, 9:23 pm, Bjoern Schliessmann  wrote:
> Lie wrote:
> > [EMAIL PROTECTED]> wrote:
> >> I used to systematically use it - like I've always systematically
> >> used 'this' in C++  and Java.
>
> > And that is what reduces readability.
>
> IMHO not, IOPHO not. This is the nth time (n >> 1) this discussion
> comes up here. If I have learned one thing from those very lengthy
> discussions, it's that Python's "self" handling is not going to
> change.

And ah... yes, I don't wish it go away either. In VB, excessive Me
reduces readability, but in Python it doesn't.

> > A proficient VB/C/Java programmer would frown upon the extra,
> > unneeded garbage as they thought it was clear already that the
> > variable refers to a class-level variable.
>
> C programmers surely have no opinion concerning C because it has no
> native classes.

C-family, ok? Please stop taking my words to its letters.

> Personally, I've seen many C++ programs with complex class designs
> where it definitely helps to consistently use "this->". I cannot
> remember all local (and global) variables in bigger methods.

In that case, you have the _option_ to do it.

> > There is one major positive point: convenience and shorter code.
> > (isn't that two?)
>
> Shorter code is not per se positive, neither is it convenient. If it
> was, everyone would use perl.

Not always, but sometimes it do help not to be obliged to use the
class name especially in short, simple programs (as opposed to big
projects that requires hundreds of thousands of lines of code) that is
changed frequently (being in heavy development). A good real-life
example for this would be for new learner of programming or the
language, they would write a lot of ten liners that is changed a LOT
of times due to their (yet) incomplete understanding of the concepts.

> >> it's the first argument of the function - which usually happens to be
> >> the current instance when the function is used as a method.
>
> > And that's the point, self (or anything you name it) is almost always
> > the current instance
>
> # this is a plain function. In this function,
> # 'obj' can be whatever that happens to have a (numeric)
> # 'stuff' attribute
> def func(obj, arg):
>    return (obj.stuff + arg) / 2.0
>
> # this is a class with an instance attribute 'stuff'
> class Foo(object):
>     def __init__(self, bar):
>       self.stuff = bar + 42
>
> # this is another (mostly unrelated) class
> # with a class attribute 'stuff'
> class Bar(object):
>    stuff = 42
>
> # this is a dummy container class:
> class Dummy(object): pass
>
> # now let's play:
> import new
>
> d = Dummy()
> d.stuff = 84
> print func(d, 1)
>
> d.baaz = new.instancemethod(func, d, type(d))
> print d.baaz(2)
>
> f = Foo(33)
> print func(f, 3)
> Foo.baaz = func
> f.baaz(4)
>
> print func(Bar, 5)
> Bar.baaz = classmethod(func)
> Bar.baaz(6)
>
> >  and that makes it functionally the same as Me and
> > this in VB and Java.
>
> Depends on the context, cf above !-)

Please again, stop taking letters to the words, I don't meant them to
be exactly the same, rather the same would meant that they generally
can be considered equal, exceptions exists of course. And btw, I don't
understand what you meant by your example, they seemed to be a
completely OK program for me, even though it's a bit confusing to
follow[2].

[2] btw, the reason it's a bit confusing to follow is one of my
points: It is a Bad Thing(tm) to use the same name for different
variables even in a language like Python that enforce explicit naming
of classes

> >>> Most other languages
> >>> 1) automatically assign the containing class' object
> >> s/containing class' object/current instance/
>
> >>> in a keyword
> >>> (Java: this, VB: Me) behind the screen,
>
> >> That's not very far from what a Python method object does -
> >> automatically assign the current instance to something. The difference
> >> is that Python uses functions to implement methods (instead of having
> >> two distinct contructs), so the only reliable way to "inject" the
> >> reference to the current instance is to pass it as an argument to the
> >> function (instead of making it pop from pure air).
>
> > It isn't very far, but Python makes it obvious about the assignment
> > (not behind the screen).
>
> Exactly. And given both the simplicity of the solution and what it let
> you do, that's a *very* GoodThing(tm) IM

Re: Basic inheritance question

2008-01-21 Thread Lie
> > Please stop taking my words to its letters.
>
> So we're supposed to actually guess what you really mean ???

That's what human does, otherwise you'll "Fail the Turing Test".

> >> Personally, I've seen many C++ programs with complex class designs
> >> where it definitely helps to consistently use "this->". I cannot
> >> remember all local (and global) variables in bigger methods.
>
> > In that case, you have the _option_ to do it.
>
> Make no sens when maintaining code wrote by someone that didn't use this
> 'option'.
>
> (snip)
>
>
>
>  it's the first argument of the function - which usually happens to be
>  the current instance when the function is used as a method.
> >>> And that's the point, self (or anything you name it) is almost always
> >>> the current instance
> >> # this is a plain function. In this function,
> >> # 'obj' can be whatever that happens to have a (numeric)
> >> # 'stuff' attribute
> >> def func(obj, arg):
> >>    return (obj.stuff + arg) / 2.0
>
> >> # this is a class with an instance attribute 'stuff'
> >> class Foo(object):
> >>     def __init__(self, bar):
> >>       self.stuff = bar + 42
>
> >> # this is another (mostly unrelated) class
> >> # with a class attribute 'stuff'
> >> class Bar(object):
> >>    stuff = 42
>
> >> # this is a dummy container class:
> >> class Dummy(object): pass
>
> >> # now let's play:
> >> import new
>
> >> d = Dummy()
> >> d.stuff = 84
> >> print func(d, 1)
>
> >> d.baaz = new.instancemethod(func, d, type(d))
> >> print d.baaz(2)
>
> >> f = Foo(33)
> >> print func(f, 3)
> >> Foo.baaz = func
> >> f.baaz(4)
>
> >> print func(Bar, 5)
> >> Bar.baaz = classmethod(func)
> >> Bar.baaz(6)
>
> >>>  and that makes it functionally the same as Me and
> >>> this in VB and Java.
> >> Depends on the context, cf above !-)
>
> > Please again, stop taking letters to the words, I don't meant them to
> > be exactly the same, rather the same would meant that they generally
> > can be considered equal,
>
> If you still think that way after having read the above code, then I
> can't help. We obviously don't share the same mental model here.

I don't get what you're trying to meant, in that piece of code self is
used in the regular way, in a regular context.

> > exceptions exists of course. And btw, I don't
> > understand what you meant by your example, they seemed to be a
> > completely OK program for me,
>
> Indeed it's ok (even if totally useless by itself). The point is that
> 'self' (or whatever you name it) is just and only the first argument of
> a function, period.

And it is... but I still don't get what you meant

> > even though it's a bit confusing to
> > follow[2].
>
> Nothing in it should be confusing to anyone having a decent knowledge of
> Python's object model IMHO.
>
> > [2] btw, the reason it's a bit confusing to follow is one of my
> > points: It is a Bad Thing(tm) to use the same name for different
> > variables
>
> Where do I "use the same name for different variables" here ?

It's not confusing in the way of object model, but in the way that you
used meaningless names in overloaded manner.

> > even in a language like Python that enforce explicit naming
> > of classes
>
> Python doesn't "enforce" explicit name of classes - IIRC, there are ways
> to instanciate anonymous class objects. But I definitively don't see how
> this relate to this discussion.

We're not talking about anonymous class objects here, and I'm sure you
actually understand what I meant by "naming the class" from previous
discussions.

> Yes, I know, "please guess what I mean" !-) but sorry, there's no sens
> discussing a technical point without using accurate and appropriate
> technical naming of technical concepts invlved.

Well, it's not my fault for being born as a non-native speaker of
English, sometimes what I meant might goes a bit off from what I
write. Anyway, human languages aren't designed to be fully
unambiguous, so it is natural for human to provide a margin of errors
when speaking to each other, well unless you're not a human...

> > Most other languages
> > 1) automatically assign the containing class' object
>  s/containing class' object/current instance/
> > in a keyword
> > (Java: this, VB: Me) behind the screen,
>  That's not very far from what a Python method object does -
>  automatically assign the current instance to something. The difference
>  is that Python uses functions to implement methods (instead of having
>  two distinct contructs), so the only reliable way to "inject" the
>  reference to the current instance is to pass it as an argument to the
>  function (instead of making it pop from pure air).
> >>> It isn't very far, but Python makes it obvious about the assignment
> >>> (not behind the screen).
> >> Exactly. And given both the simplicity of the solution and what it let
> >> you do, that's a *very* GoodThing(tm) IMHO.
>
> > I agree, it's a Good Thing but it doesn't make the point less pointy

Re: Encrypting a short string?

2008-02-16 Thread Lie
On Feb 12, 2:45 am, erikcw <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to devise a scheme to encrypt/obfuscate a short string that
> basically contains the user's username and record number from the
> database.  I'm using this encrypted string to identify emails from a
> user. (the string will be in the subject line of the email).
>
> I'm trying to figure out which approach I should use to encrypt the
> data.  The string will be less than 20 characters long, and I'd like
> the encrypted version to be about the same size.
>
> I tried DES in the Crypto module, but the cipher text was to long to
> be usable in this case.
>
> Any suggestions?
>
> Thanks!

There is a simple encryption, called ROT13 (Rotate 13). This is very
unsecure for any cryptographical purpose, but enough to make
uninformed user to think it's just a random piece of letters.

The ROT13 is done by adding 13 to each character, so
A => N,
B => O,
C => P,
D => Q, etc

the neat trick to this encryption is the algorithm is really simple
and you don't need a separate decoding algorithm as text ==
ROT13(ROT13(text)). This algorithm also guarantees that any two
different text would have two different ciphertext
-- 
http://mail.python.org/mailman/listinfo/python-list


How about adding rational fraction to Python?

2008-02-16 Thread Lie
Would all these problems with floating points be a rational reason to
add rational numbers support in Python or Py3k? (pun not intended)

I agree, there are some numbers that is rationals can't represent
(like pi, phi, e) but these rounding problems also exist in floating
points, and rational numbers wouldn't be so easily fooled by something
like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first
problem with rational is that to get an infinite precision rational,
the language would have to have an infinite length integers, which
Python have given us. The second problem with rationals is to keep
rationals in its most simple, trivial form. This can be solved with a
good GCD algorithm, which can also be a nice addition to Python's math
library.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-16 Thread Lie
On Feb 17, 1:40 am, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > Would all these problems with floating points be a rational reason to
> > add rational numbers support in Python or Py3k? (pun not intended)
>
> > I agree, there are some numbers that is rationals can't represent
> > (like pi, phi, e) but these rounding problems also exist in floating
> > points, and rational numbers wouldn't be so easily fooled by something
> > like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first
> > problem with rational is that to get an infinite precision rational,
> > the language would have to have an infinite length integers, which
> > Python have given us. The second problem with rationals is to keep
> > rationals in its most simple, trivial form. This can be solved with a
> > good GCD algorithm, which can also be a nice addition to Python's math
> > library.
>
> http://www.python.org/dev/peps/pep-0239/

Yes, I'm aware of the PEP and actually have been trying for some time
to reopen the PEP.

The reason that PEP is rejected is because Decimal is accepted, which
I think is a completely absurd reason as Decimal doesn't actually
solve the rounding problems and equality comparison problem. Some
people have also pointed out that Decimal IS Inexact, while a rational
number is always exact except if you have an operation with a (binary
or decimal) floating point involved (this can be easilty resolved by
making fraction recessive, i.e. an operation that receive a fraction
and a float should return a float).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-16 Thread Lie
On Feb 17, 2:26 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Feb 16, 1:35 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> > Would all these problems with floating points be a rational reason to
> > add rational numbers support in Python or Py3k? (pun not intended)
>
> It's already in the trunk!  Python will have a rational type (called
> Fraction) in Python 2.6 and Python 3.0, thanks largely to the work of
> Jeffrey Yaskin.
>
> Mark

Really? I didn't know that (last time I checked they frowned at me for
asking that). It's going to be be great if Python supports fractional
number. Although rationals have its limitations too, it is a much
better choice compared to floats/Decimals for most cases. One thing
though, the time I've spent on creating a rational class myself would
be 'somewhat' wasted, although I don't really mind that since it was
fun in any case.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-16 Thread Lie
On Feb 17, 4:25 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 16, 3:03 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> > Although rationals have its limitations too, it is a much
> > better choice compared to floats/Decimals for most cases.
>
> Maybe that's true for your use cases, but it's not true for most cases
> in general.

OK, that might have been an overstatement, but as I see it, it is
safer to handle something in a Fraction compared to floats (which is
why I uses fractions whenever possible in non-computer maths).

> Rationals are pretty useless for almost any extended calculations,
> since the denominator tends to grow in size till it's practically
> unusbale, which means you have to periodically do non-exact reductions
> to keep things running, and if you do that you might as well be using
> floating point.

Rationals aren't that good if the same piece of variable is to be
calculated again and again because of its growth, but there are a lot
of cases where the data would only require five or six or so
operations done on it (and there are thousands or millions of such
datas), rationals is the perfect choice for those situations because
it is easier to use thanks to the comparison safety. Or in the
situations where speed isn't as important and accuracy is required,
Fraction may be faster than decimal and more accurate at the same time
(someone need to test that though).

> Rationals have their occasional special purpose uses, but for most
> cases they're at best marginally better then floats and more often
> incomparably worse.

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


Re: How about adding rational fraction to Python?

2008-02-17 Thread Lie
> Consider what happens when you add two fractions:
>
> 1/2 + 1/5
>
> To do that, you have to take the LCD of the denomintor, in this case
> 10, so you get
>
> 5/10 + 2/10 = 7/10
>
> Now imagine that you're adding a lot of different numbers with a lot
> of different bases.  That LCD's going to be pretty big.  To make
> matters worse, imagine taking this number as the divisor in a later
> calculation: a new denominator would appear (7).  So you get
> denominators that you didn't even input, which can make LCDs go
> higher.
>
> Any iteration with repeated divisions and additions can thus run the
> denominators up.  This sort of calculation is pretty common (examples:
> compound interest, numerical integration).

Wrong. Addition and subtraction would only grow the denominator up to
a certain limit

> > The thing I don't like about rationals is that they give a false sense
> > of security.  They are performing reasonably, and then you make a slight
> > change or some circumstance changes slightly and suddenly they blow up.
>
> Or, to put it another way, rationals and floats both are dangerous, but
> in different ways. The performance of rationals can fall drastically, and
> floating point calculations can suddenly become inaccurate. You make your
> choice and take your chances.

When I mean safety, fraction is safe in calculation integrity safety,
it is always safe to do calculations in fraction (although at one time
the huge calculation might stall the system, the calculation will
always be correct all the time). But actually there is a way to ensure
performance safety in Fraction class, fraction might grow
uncontrollably only if the data is multiplied or divided. If you're
just doing addition and subtraction, the denominator growth is limited
to a certain range given a limited range of data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread Lie
On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Paul Rubin wrote:
> > Jeff Schwab <[EMAIL PROTECTED]> writes:
> >> Why not?  They seem intuitive to me.  I would find it weird if you
> >> couldn't have 0-tuple, and even weirder if you couldn't have a
> >> 1-tuple.   Maybe my brain has been warped by too much C++ code.
>
> > The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
> > 3-tuple is three numbers, and a 1-tuple is one number.  That would
> > mean a number and a 1-tuple of numbers are the same thing, not
> > separate types.
>
> No, that doesn't follow.  A set with one element is not the same thing
> as that element, a sequence of one element is not the same thing as that
> element, and a tuple with one element is not the same thing as that element.

Probably the analogue of tuples in human language would be like this:
A: What ice-cream flavour do you have?
B: "Vanilla", "Chocolate", and "Strawberry"

If, for example, he only have Vanilla:
A: What ice-cream flavour do you have?
B: "Vanilla"

This way of thinking makes 1-tuple the same as the element itself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-23 Thread Lie
On Feb 23, 4:02 pm, zaley <[EMAIL PROTECTED]> wrote:
> On Feb 22, 11:06 pm, "Jesper"  wrote:
>
>
>
> > Give PyScripter fromhttp://www.mmm-experts.com/atry
>
> > It is for Windows, though it is written in Delphi and not in C/C++
>
> > /Jesper
>
> > "zaley" <[EMAIL PROTECTED]> skrev i en meddelelsenews:[EMAIL PROTECTED]
> > Of course, python scripts debugger
>
> > On 2ÔÂ22ÈÕ, ÏÂÎç3ʱ22·Ö, zaley <[EMAIL PROTECTED]> wrote:
>
> > > My project need a simple scripts debugger . I hope I can find
> > > something instructive
>
> > > Stefan Behnel дµÀ£º
>
> > > > zaley wrote:
> > > > > Is there a open souce IDE writen by C( C++) or partly writen by C( C+
> > > > > +)?
>
> > > > Tons of them. What do you want to do with it?
>
> > > > Stefan- Hide quoted text -
>
> > - Show quoted text -
>
> But PyScripter is not a open source project

Am I correct to say that the reason why you wanted an open source C++
IDE is because you wanted the freedom to modify your own programming
environment?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-24 Thread Lie
On Feb 24, 11:23 am, zaley <[EMAIL PROTECTED]> wrote:
> On Feb 24, 6:48 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>
>
>
> > Lie wrote:
> > > On Feb 23, 4:02 pm, zaley <[EMAIL PROTECTED]> wrote:
> > >> On Feb 22, 11:06 pm, "Jesper"  wrote:
>
> > >>> Give PyScripter fromhttp://www.mmm-experts.com/atry
> > >>> It is for Windows, though it is written in Delphi and not in C/C++
> > >>> /Jesper
> > >>> "zaley" <[EMAIL PROTECTED]> skrev i en meddelelsenews:[EMAIL PROTECTED]
> > >>> Of course, python scripts debugger
> > >>> On 2ÔÂ22ÈÕ, ÏÂÎç3ʱ22·Ö, zaley <[EMAIL PROTECTED]> wrote:
> > >>>> My project need a simple scripts debugger . I hope I can find
> > >>>> something instructive
> > >>>> Stefan Behnel дµÀ£º
> > >>>>> zaley wrote:
> > >>>>>> Is there a open souce IDE writen by C( C++) or partly writen by C( C+
> > >>>>>> +)?
> > >>>>> Tons of them. What do you want to do with it?
> > >>>>> Stefan- Hide quoted text -
> > >>> - Show quoted text -
> > >> But PyScripter is not a open source project
>
> > > Am I correct to say that the reason why you wanted an open source C++
> > > IDE is because you wanted the freedom to modify your own programming
> > > environment?
> > >From the "About" window in PyScripter :
>
> > """
> > A freeware, open source Python scripter integrated
> > development environment created with the ambition to bring to
> > the Python community the quality and functionality available in
> > commercial IDEs available for other languages.
> > """
>
> > So I think we could say PyScripter IS an open source project.- Hide quoted 
> > text -
>
> > - Show quoted text -
>
> Really, what I want to do is that scripts can be executed step by
> step .
> I know By "Py_Runstring"  clauses  in main function can executed by
> step .
> But I can't know how to step into a function and how to step in a
> function.
> So I hope I can find something helpful in open source IDE for python.

IDLE (and all IDE's I know) can run programs step-by-step. In IDLE,
you've got to open the debug dialog (Debug -> Debugger). After opening
the debug dialog, you run your programs like normal and your program
execution would be halted on the first command until you navigate
yourself through the debug dialog. The debug dialog has a few buttons:
Go, Step, Over, Out, Quit. Go means your program would run until it
met a breakpoint[1], Step means your program would execute the next
instruction, Over means your program would execute until the next
instruction in the same level (you'll see what I meant after you
played around it for a while), Out means your program would execute
until it goes out of the current level, and Quit is like giving a
KeyboardInterrupt (it stops program execution)

[1] Set a breakpoint by right-clicking on a code line then select set
breakpoint.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-24 Thread Lie
On Feb 18, 1:25 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 17, 1:45 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> > > Any iteration with repeated divisions and additions can thus run the
> > > denominators up.  This sort of calculation is pretty common (examples:
> > > compound interest, numerical integration).
>
> > Wrong. Addition and subtraction would only grow the denominator up to
> > a certain limit
>
> I said repeated additions and divisions.

Repeated Addition and subtraction can't make fractions grow
infinitely, only multiplication and division could.

> Anyways, addition and subtraction can increase the denominator a lot
> if for some reason you are inputing numbers with many different
> denominators.

Up to a certain limit. After you reached the limit, the fraction would
always be simplifyable.

If the input numerator and denominator have a defined limit, repeated
addition and subtraction to another fraction will also have a defined
limit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-24 Thread Lie
On Feb 25, 12:46 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > On Feb 18, 1:25 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> >> On Feb 17, 1:45 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> >>>> Any iteration with repeated divisions and additions can thus run the
> >>>> denominators up.  This sort of calculation is pretty common (examples:
> >>>> compound interest, numerical integration).
> >>> Wrong. Addition and subtraction would only grow the denominator up to
> >>> a certain limit
> >> I said repeated additions and divisions.
>
> > Repeated Addition and subtraction can't make fractions grow
> > infinitely, only multiplication and division could.
>
> On what basis is this claim made?
>
> (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2)
>
> If d1 and d2 are mutually prime (have no common factors) then it is
> impossible to reduce the resulting fraction further in the general case
> (where n1 = n2 = 1, for example).
>
> >> Anyways, addition and subtraction can increase the denominator a lot
> >> if for some reason you are inputing numbers with many different
> >> denominators.
>
> > Up to a certain limit. After you reached the limit, the fraction would
> > always be simplifyable.
>
> Where does this magical "limit" appear from?
>
> > If the input numerator and denominator have a defined limit, repeated
> > addition and subtraction to another fraction will also have a defined
> > limit.
>
> Well I suppose is you limit the input denominators to n then you have a
> guarantee that the output denominators won't exceed n!, but that seems
> like a pretty poor guarantee to me.
>
> Am I wrong here? You seem to be putting out unsupportable assertions.
> Please justify them or stop making them.
>

Well, I do a test on my own fraction class. I found out that if we set
a limit to the numerators and denominators, the resulting output
fraction would have limit too. I can't grow my fraction any more than
this limit no matter how many iteration I do on them. I do the test is
by something like this (I don't have the source code with me right
now, it's quite long if it includes the fraction class, but I think
you could use any fraction class that automatically simplify itself,
might post the real code some time later):

while True:
a = randomly do (a + b) or (a - b)
b = random fraction between [0-100]/[0-100]
print a

And this limit is much lower than n!. I think it's sum(primes(n)), but
I've got no proof for this one yet.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-24 Thread Lie
On Feb 25, 1:21 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Feb 24, 1:09 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> > And this limit is much lower than n!. I think it's sum(primes(n)), but
> > I've got no proof for this one yet.
>
> It's the least common multiple of the integers 1 through n, or
> equivalently the product over all primes p <= n of the highest power
> of p not exceeding n.  So for n = 100, it's:
>
> 64 * 81 * 25 * 49 * 11 * 13 * 17 * ... rest of primes up to 100.
>
> For general n, this number is of roughly the same order of magnitude
> as e**n.

Ah, yes, I meant product(primes(n)), please forgive my honest mistake
which is partially caused by me not supposed to still be awake at this
time of the day. And thanks for Mark for noticing the mistake, and
here is the code I used:

import fraction
import random

frac = fraction.frac
ops = (frac.__add__, frac.__sub__)

a = frac(random.randrange(1, 10), random.randrange(1, 10))
b = frac(random.randrange(1, 10), random.randrange(1, 10))

while True:
o = ops[random.randrange(0, 2)]
a = o(a, b)
b = frac(random.randrange(1, 10), random.randrange(1, 10))
print a

I decided to keep the num/den limit low (10) because higher values
might obscure the fact that it do have limits. And through further
observations, I think it is sufficient if the limit is imposed in the
denominator only (numerator can have any values it wanted to,
denominator growth is determined only by the limit of denominator
growth).

I think I'll also post the code for the fraction class I used, if you
have other fraction class that can automatically simplify, you could
use that instead as this class suffers from a naive GCD
implementation:

 fraction.py 
from __future__ import division


def GCD(a, b):
if b == 0: return a
return GCD(b, a % b)


class frac:

''' Fraction Class



A fraction class.



Attributes:

num  -> the numerator of a fraction

den  -> the denominator of a fraction



Methods:

add(a, b)   -> add fraction a to fraction b and return a
new fraction

sub(a, b)   -> subtract fraction b from fraction a and
return a new fraction

mul(a, b)   -> multiply fraction a with fraction b and
return a new fraction

div(a, b)   -> divides fraction b from fraction a and
return a new fraction

invert(a)   -> invert the fraction (switch the numerator
and denominator)

neg(a)  -> negates the fraction (negates numerator)

powr(a, b)  -> raise fraction a to the power of b

simplify(a, b)  -> simplify fraction to its canonical
representation



__init__(a, b)  -> creates a new fraction

__str__(a, b)   -> returns a string representation. Mixed
fraction if possible

__repr__(a, b)  -> returns a string representation. Always
return vulgar fraction



Operators:

Conversion to fractions will be done automatically whenever
possible, in-place

operation is fully supported. Both regular and reflected
operation is supported.

a + b  -> Calls frac.add(a, b)

a - b  -> Calls frac.sub(a, b)

a * b  -> Calls frac.mul(a, b)

a / b  -> Calls frac.div(a, b)

a // b -> Floors the resulting fraction from frac.div(a, b)

-a -> Negates a fraction

+a -> Returns a copy of the fraction

~a -> Return the reciprocal of a



Comparisons:

Implemented through __cmp__(a, b), no rich comparison.

a == b  -> a equals b

a != b  -> a not equal b

a > b   -> a greater than b

a < b   -> a less than b

a >= b  -> a greater than or equal to b

a <= b  -> a less than or equal to b



Casting:

__complex__ -> Converts the fraction to floats and return the
result as complex number

__int__ -> Returns the whole part of the fraction in
Integer

__long__-> Returns the whole part of the fraction in Long

__float__   -> Returns the value of the fractino in Float



Exceptions:

ZeroDenominatorError

-> A fraction cannot have zero as its denominator



Bugs:

- At the meantime, the fraction class doesn't mix well if used

  together with floating type numbers. Inline operators and

  initializers implicitly assumed that numbers are either
integers or

  fraction. So if there are operations involving floating
point or

  you initialized a fraction with a floating point number, the
result

  would be something like a "floating point fraction".

'''



def __init__(self, a = 0, b = 1):

dev =

Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 25, 5:41 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 24 Feb 2008 10:09:37 -0800, Lie wrote:
> > On Feb 25, 12:46 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> Lie wrote:
> >> > On Feb 18, 1:25 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> >> >> On Feb 17, 1:45 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> >> >>>> Any iteration with repeated divisions and additions can thus run
> >> >>>> the denominators up.  This sort of calculation is pretty common
> >> >>>> (examples: compound interest, numerical integration).
> >> >>> Wrong. Addition and subtraction would only grow the denominator up
> >> >>> to a certain limit
> >> >> I said repeated additions and divisions.
>
> >> > Repeated Addition and subtraction can't make fractions grow
> >> > infinitely, only multiplication and division could.
>
> >> On what basis is this claim made?
>
> >> (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2)
>
> >> If d1 and d2 are mutually prime (have no common factors) then it is
> >> impossible to reduce the resulting fraction further in the general case
> >> (where n1 = n2 = 1, for example).
>
> >> >> Anyways, addition and subtraction can increase the denominator a lot
> >> >> if for some reason you are inputing numbers with many different
> >> >> denominators.
>
> >> > Up to a certain limit. After you reached the limit, the fraction
> >> > would always be simplifyable.
>
> >> Where does this magical "limit" appear from?
>
> >> > If the input numerator and denominator have a defined limit, repeated
> >> > addition and subtraction to another fraction will also have a defined
> >> > limit.
>
> >> Well I suppose is you limit the input denominators to n then you have a
> >> guarantee that the output denominators won't exceed n!, but that seems
> >> like a pretty poor guarantee to me.
>
> >> Am I wrong here? You seem to be putting out unsupportable assertions.
> >> Please justify them or stop making them.
>
> > Well, I do a test on my own fraction class. I found out that if we set a
> > limit to the numerators and denominators, the resulting output fraction
> > would have limit too. I can't grow my fraction any more than this limit
> > no matter how many iteration I do on them. I do the test is by something
> > like this (I don't have the source code with me right now, it's quite
> > long if it includes the fraction class, but I think you could use any
> > fraction class that automatically simplify itself, might post the real
> > code some time later):
>
> > while True:
> > a = randomly do (a + b) or (a - b)
> > b = random fraction between [0-100]/[0-100] print a
>
> > And this limit is much lower than n!. I think it's sum(primes(n)), but
> > I've got no proof for this one yet.
>
> *jaw drops*
>
> Please stop trying to "help" convince people that rational classes are
> safe to use. That's the sort of "help" that we don't need.
>
> For the record, it is a perfectly good strategy to *artificially* limit
> the denominator of fractions to some maximum value. (That's more or less
> the equivalent of setting your floating point values to a maximum number
> of decimal places.) But without that artificial limit, repeated addition
> of fractions risks having the denominator increase without limit.
>
> --
> Steven

No, it is a real limit. This is what I'm talking about. If the input
data has a limit, the output data has a real limit, not a defined-
limit. If the input data's denominator is unbounded, the output
fraction's denominator is also unbounded

In a repeated addition and subtraction with input data that have limits
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 25, 5:41 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 24 Feb 2008 10:09:37 -0800, Lie wrote:
> > On Feb 25, 12:46 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> Lie wrote:
> >> > On Feb 18, 1:25 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> >> >> On Feb 17, 1:45 pm, Lie <[EMAIL PROTECTED]> wrote:
>
> >> >>>> Any iteration with repeated divisions and additions can thus run
> >> >>>> the denominators up.  This sort of calculation is pretty common
> >> >>>> (examples: compound interest, numerical integration).
> >> >>> Wrong. Addition and subtraction would only grow the denominator up
> >> >>> to a certain limit
> >> >> I said repeated additions and divisions.
>
> >> > Repeated Addition and subtraction can't make fractions grow
> >> > infinitely, only multiplication and division could.
>
> >> On what basis is this claim made?
>
> >> (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2)
>
> >> If d1 and d2 are mutually prime (have no common factors) then it is
> >> impossible to reduce the resulting fraction further in the general case
> >> (where n1 = n2 = 1, for example).
>
> >> >> Anyways, addition and subtraction can increase the denominator a lot
> >> >> if for some reason you are inputing numbers with many different
> >> >> denominators.
>
> >> > Up to a certain limit. After you reached the limit, the fraction
> >> > would always be simplifyable.
>
> >> Where does this magical "limit" appear from?
>
> >> > If the input numerator and denominator have a defined limit, repeated
> >> > addition and subtraction to another fraction will also have a defined
> >> > limit.
>
> >> Well I suppose is you limit the input denominators to n then you have a
> >> guarantee that the output denominators won't exceed n!, but that seems
> >> like a pretty poor guarantee to me.
>
> >> Am I wrong here? You seem to be putting out unsupportable assertions.
> >> Please justify them or stop making them.
>
> > Well, I do a test on my own fraction class. I found out that if we set a
> > limit to the numerators and denominators, the resulting output fraction
> > would have limit too. I can't grow my fraction any more than this limit
> > no matter how many iteration I do on them. I do the test is by something
> > like this (I don't have the source code with me right now, it's quite
> > long if it includes the fraction class, but I think you could use any
> > fraction class that automatically simplify itself, might post the real
> > code some time later):
>
> > while True:
> > a = randomly do (a + b) or (a - b)
> > b = random fraction between [0-100]/[0-100] print a
>
> > And this limit is much lower than n!. I think it's sum(primes(n)), but
> > I've got no proof for this one yet.
>
> *jaw drops*
>
> Please stop trying to "help" convince people that rational classes are
> safe to use. That's the sort of "help" that we don't need.
>
> For the record, it is a perfectly good strategy to *artificially* limit
> the denominator of fractions to some maximum value. (That's more or less
> the equivalent of setting your floating point values to a maximum number
> of decimal places.) But without that artificial limit, repeated addition
> of fractions risks having the denominator increase without limit.
>
> --
> Steven

No, it is a real limit. This is what I'm talking about. If the input
data has a limit, the output data has a real limit, not a user-defined-
limit (FOR ADDITION AND SUBTRACTION). If the input data's denominator
is unbounded, the output fraction's denominator is also unbounded
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 25, 11:34 am, casevh <[EMAIL PROTECTED]> wrote:
> On Feb 24, 7:56 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > But that doesn't mean they become less manageable than
> > other unlimited precision usages. Did you see my example
> > of the polynomial finder using Newton's Forward Differences
> > Method? The denominator's certainly don't settle out, neither
> > do they become unmanageable. And that's general mathematics.
>
> Since you are expecting to work with unlimited (or at least, very
> high) precision, then the behavior of rationals is not a surprise. But
> a naive user may be surprised when the running time for a calculation
> varies greatly based on the values of the numbers. In contrast, the
> running time for standard binary floating point operations are fairly
> constant.
>
>
>
> > If the point was as SDA suggested, where things like 16/16
> > are possible, I see that point. As gmpy demonstrates thouigh,
> > such concerns are moot as that doesn't happen. There's no
> > reason to suppose a Python native rational type would be
> > implemented stupidly, is there?
>
> In the current version of GMP, the running time for the calculation of
> the greatest common divisor is O(n^2). If you include reduction to
> lowest terms, the running time for a rational add is now O(n^2)
> instead of O(n) for a high-precision floating point addition or O(1)
> for a standard floating point addition. If you need an exact rational
> answer, then the change in running time is fine. But you can't just
> use rationals and expect a constant running time.
>
> There are trade-offs between IEEE-754 binary, Decimal, and Rational
> arithmetic. They all have there appropriate problem domains.

I very agree with this statement. Fractionals do have its weakness,
and so do Decimal and Hardware Floating Point. And they have their own
usage, their own scenarios where they're appropriate. If you needed
full-speed calculation, it is clear that floating point wins all over
the place, OTOH, if you need to manage your precision carefully
Fractional and Decimal both have their own plus and mins

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


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 25, 1:58 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> What part of "repeated additions and divisions" don't you understand?

What part of additions and subtractions don't you understand? I'm
invalidating half of your statement, the division part, but validating
another half, the additions part and adding some statements on my own.

>
> Try doing numerical integration sometime with rationals, and tell me
> how that works out.  Try calculating compound interest and storing
> results for 1000 customers every month, and compare the size of your
> database before and after.
>

Since when have I said that fractional is appropriate for calculating
compound interests. Fractionals works best in scenarios where the
calculations are mostly addition and subtraction, not percentage
division and multiplications like in compounds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 25, 11:18 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 25, 9:41 am, Mensanator <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 25, 12:58�am, Carl Banks <[EMAIL PROTECTED]> wrote:
>
> > > On Feb 24, 10:56 pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
> > > > But that doesn't mean they become less manageable than
> > > > other unlimited precision usages. Did you see my example
> > > > of the polynomial finder using Newton's Forward Differences
> > > > Method? The denominator's certainly don't settle out, neither
> > > > do they become unmanageable. And that's general mathematics.
>
> > > No, that's a specific algorithm. �That some random algorithm doesn't
> > > blow up the denominators to the point of disk thrashing doesn't mean
> > > they won't generally.
>
> > > Try doing numerical integration sometime with rationals, and tell me
> > > how that works out. �Try calculating compound interest and storing
> > > results for 1000 customers every month, and compare the size of your
> > > database before and after.
>
> > Nobody said rationals were the appropriate solution
> > to _every_ problem, just as floats and integers aren't
> > the appropriate solution to _every_ problem.
>
> I was answering your claim that rationals are appropriate for general
> mathematical uses.
>
> > Your argument is that I should be forced to use
> > an inappropriate type when rationals _are_
> > the appropriate solution.
>
> I don't know where you got that idea.
>
> My argument is that rationals aren't suitable for ordinary uses
> because they have poor performance and can easily blow up in your
> face, trash your disk, and crash your program (your whole system if
> you're on Windows).
>
> In other words, 3/4 in Python rightly yields a float and not a
> rational.
>

And it should, as floats have native CPU support, 3/4 (with __future__
import) should yields 0.75. Fractional is safe for many usage
scenario, but obviously it is not appropriate for all cases, just like
floats and decimals. I think this mailing list already have enough
absolutist, who can go to either side of the camp but doesn't want to
be in the middle.

In real world, money is probably best described by float or Decimals,
as non-computer money calculations are used to do rounding at 1 cents.
But the interest rate is probably better described by rationals.

In trigonometry, _perhaps_ the world would be better if trigonometric
functions returns rational. Perhaps it is better to use rational for
pi (ratio of diameter and circumferrence) and phi (golden ratio). But
I think angles is better described as floats nevertheless.

> J Cliff Dyer:
> I'm in the camp that believes that 3/4 does indeed yield the integer 0,
> but should be spelled 3//4 when that is the intention.

That's creepy for people that are new to programming and doesn't know
how CPUs work and are used to general mathematics. That means most
people. As programming language are now more accessible to regular
people without specialized Computer Science degree, it is a just
natural trend that computer arithmetic must be done in an expectable
manner as seen by those general population not by people who holds a
CS degree.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 26, 9:02 pm, [EMAIL PROTECTED] wrote:
> > That's creepy for people that are new to programming and doesn't know
> > how CPUs work and are used to general mathematics. That means most
> > people. As programming language are now more accessible to regular
> > people without specialized Computer Science degree, it is a just
> > natural trend that computer arithmetic must be done in an expectable
> > manner as seen by those general population not by people who holds a
> > CS degree.
>
> Couldn't disagree with you more, the fact they don't specialise in
> Computer Science shouldn't be a reason to follow their "expected
> outcomes", they should be informed of the standard CS approach. I'm
> all for punishing people for making "well I thought it would always do
> the following..." thought process. The quicker they learn certain
> methods and expectations are wrong the quicker they get used to the
> proper thought patterns.

The problem lies on which maths is the real maths? In real world, 3/4
is 0.75 is 0.75 and that's an unchangeable fact, so programming
languages that do other things is either wrong or have their reason to
do that. Python, C, and other programming languages that uses integer
division by default choose to do default integer division because CPUs
execute integer division faster than floating division, but it doesn't
change the fact that 3/4 is equal to 0.75 but is not equal to 0.

I think a CS should understand that the choice of default integer
division was actually a workaround for the expensive operation, not
because 3/4 actually equals 0. As the more educated person, they
should still expect 3/4 to be 0.75 but could understand why if the
language they're using gives 0. Commoners are the less educated,
languages should appeal to as much people as it could, and giving 3/4
== 0 is the best way to confuse some people right away, instead giving
3/4 == 0.75 would just make the more educated CSs search for the
"regular"  division operator.

It is better to think this way:
CSs supposed brain thought:
try:
   print 3 / 4
except IntegerResult:
   print 'integer division workaround'
   if wants[floatdivision]: print 'searching for float division
operator'
   elif wants[integerdivision]: print 'that was already correct'

Commoner's supposed brain thought:
try:
   print 3 / 4




than this way:
CSs supposed brain thought:
try:
   print 3 / 4
except FPointResult:
   print 'This language is a jerk'

Commoner's supposed brain thought:
try:
   print 3 / 4

The first set of brain thought appeal to everyone, everyone is happy
with the result. The second set of brain thought kills a CS guy and
gives unhandled error to a commoner. DO you still think that default
integer division is better?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 26, 10:17 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
>Carl Banks <[EMAIL PROTECTED]> wrote:
>> On Feb 26, 9:29 am, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
>> > If 3/4 ever returned 0.75 in any language I would drop that language.
>
>> Have fun dropping Python, then, chief.  Integer division with / is
>> already deprecated, can be disabled ever since Python 2.4, and will be
>> wholly removed in Python 3.0.
>
>I have not been following Python development that closely lately so I
>was not aware of that. I guess I won't be going to Python 3 then.  It's
>great that Python wants to attract young, new programmers.  Too bad
>about us old farts I guess.

Don't worry, Python would still have integer division (// - double
slash), if you still prefer integer division.

> Lie <[EMAIL PROTECTED]> wrote:
> > The problem lies on which maths is the real maths? In real world, 3/4
> > is 0.75 is 0.75 and that's an unchangeable fact, so programming
>
> Which real world is that?  In my real world 3/4 is 0 with a remainder
> of 3.  What happens to that 3 depends on the context.  When I worked
> with a youth soccer group I was pretty sure that I would be disciplined
> if I carved up a seven year old player so that I could put 0.75 of a
> child on a team.

lol, when counting how much players needed you wouldn't do a division,
you count from one to eleven (a.k.a addition by one a.k.a. increment),
excepting at the point where number of available players + current
count = 11 (+ spares) (or better, you subtract the number of players
to the number of players required). Save the float division for the
time, 90 minutes / number of players if you wanted each child to play
an equal amount of time.

Good joke, and a true argument, I don't wish to see anyone chopped off
because I said floating point division is better.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread Lie
On Feb 26, 9:33 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 26 Feb 2008 04:29:18 -0800, Lie wrote:
> >> J Cliff Dyer:
> >> I'm in the camp that believes that 3/4 does indeed yield the integer 0,
> >> but should be spelled 3//4 when that is the intention.
>
> > That's creepy for people that are new to programming and doesn't know
> > how CPUs work and are used to general mathematics. That means most
> > people. As programming language are now more accessible to regular
> > people without specialized Computer Science degree, it is a just
> > natural trend that computer arithmetic must be done in an expectable
> > manner as seen by those general population not by people who holds a
> > CS degree.
>
> So why is it creepy then!?  ``3 // 4`` is for the people knowing about
> integer division and ``3 / 4`` gives the expected result for those who
> don't.  Those who don't know ``//`` can write ``int(3 / 4)`` to get the
> same effect.

yep, that's the point. The new division operator isn't that creepy
anymore by returning float instead of integer, kudos for whoever made
the change.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-29 Thread Lie
On Feb 28, 10:00 am, Paul Rubin  wrote:
> More examples:
>
>x = 1
>y = len(s) + x
>
> => ok, decides that x is an int
>
>x = 1
>y = x + 3.0
>
> => ok, decides that x is a float
>
>x = 1
>y = x + 3.0
>z = len(s) + x
>
> => forbidden, x cannot be an int and float at the same time.
>
> > I am so glad you're not the designer of Python.
>
> This is how Haskell works and I don't notice much complaints about it.

Ok, that means the line "y = x + 3.0" have a side effect of "x =
float(x)"? I think I would say that is an implicit behavior.


On Feb 28, 11:22 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> > You people can't tell the difference between "obvious" and "learned
> > conventions that came about because in limitations in the hardware at
> > the time".  Nobody would have come up with a silly rule like "x op y
> > must always have the same type as x and y" if computer hardware had
> > been up to the task when these languages were created.
>
> What makes you say they weren't?  Calculating machines that handled
> floating point are older than Python by far.
>

But much younger than the first programming language (if it could be
called as a language) that set the convention of int op int should
result in int 'cause our hardware can't handle floats.

On Feb 29, 6:15 am, Paul Rubin  wrote:
> Can you name an example of a calculating machine that both:
>   2) says 1/2 = 0.5 ?

Any pocket calculator to scientific calculator. Except perhaps my
calculator which is fraction scientific calculator where it stores 1/2
as rational and have another division operator for 1/2 == 0.5

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


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Mar 1, 11:23 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
(snip)
> But the type of `x` must be specialized somehow.  `x` doesn't start as
> `Int` or `Integer` but the very generic and AFAIK abstract type class `Num`.
>
> After seeing the second line the compiler finds an implementation for `+`
> and the type class `Fractional` for both operands and now thinks `x` must
> be a `Fractional`, a subclass of `Num`.
>
> Then comes the third line with `length` returning an `Int` and the
> `Fractional` `x` but there is no implementation for a `+` function on
> those types.

I see, but the same arguments still holds true: the second line have
an implicit side-effect of redefining x's type into Fractional type.
If I were the designer of the language, I'd leave x's type as it is
(as Num) and coerce x for current calculation only.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Mar 2, 2:32 am, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > I see, but the same arguments still holds true: the second line have
> > an implicit side-effect of redefining x's type into Fractional type.
> > If I were the designer of the language, I'd leave x's type as it is
> > (as Num) and coerce x for current calculation only.
>
> Num in Haskell is not a type, it is a class of types, i.e. if all you
> know about x is that it is a Num, then its actual type is
> indeterminate.  Types get inferred, they do not get coerced or
> "redefined".  The compiler looks at expressions referring to x, to
> deduce what x's type actually is.  If it is not possible to satisfy
> all constraints simultaneously, then the compiler reports an error.

So basically they refused to satisfy everything that is still possible
individually but would conflict if done together. (I know Haskell not
more than just its name so I don't understand the rationale behind the
language design at all) But I'm interested in how it handles these
cases:

x = 1
a = x + 1<< decides it's an int
b = x + 1.0  << error? or redefine to be float?
c = x + 1<< would this cause error while it worked in line 2?

A slightly obfuscated example:
l = [1, 1.0, 1]
x = 1
for n in l:
  c = x + n
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-01 Thread Lie
On Feb 29, 5:33 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> > > And rightly rejected by many other programming languages, including
> > > modern Python, not to mention calculators, real mathematics and
> > > common sense.
>
> > Lost me again.  I was not aware that calculators, real mathematics
> > and common sense were programming languages.
>
> I didn't say they were. Please parse my sentence again.

In the widest sense of the term computer and programming language,
actually calculators and real mathematics are programming languages.
Programming languages is a way to communicate problems with computer.
Computer is anything that does computation (and that includes
calculator and a room full of a bunch of people doing calculation with
pencil and paper[1]). The expressions we write in a calculator is a
(very limited) programming language, while mathematics conventions is
a language to communicate a mathematician's problems with the
computers[2] and other mathematicians

[1] Actually the term computer was first used to refer to this bunch
of people
[2] The computers in this sense is people that does computation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-02 Thread Lie
On Mar 2, 2:02 pm, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > So basically they refused to satisfy everything that is still possible
> > individually but would conflict if done together.
>
> I can't understand that.
>
> > x = 1
> > a = x + 1<< decides it's an int
>
> No, so far a and x are both Num (indeterminate)
>
> > b = x + 1.0  << error? or redefine to be float?
>
> This determines that a, b, and x are all floats.  It's not "redefined"
> since the types were unknown prior to this.
>
> Actually, I'm slightly wrong, 1.0 is not a float, it's a "Fractional"
> which is a narrower class than Num but it could still be Float, Double,
> or Rational.  Nums support addition, subtraction, multiplication, but
> not necessarily division.  So int/int is an error.  Fractionals support
> division.
>
> > c = x + 1<< would this cause error while it worked in line 2?
>
> No, c is also a float (actually Fractional)
>
> > A slightly obfuscated example:
> > l = [1, 1.0, 1]
>
> This is the same as l = [1.0, 1.0, 1.0].  In Haskell, all elements
> of a list must have the same type, so the 1.0 determines that l is
> a list of fractionals.
>
> > x = 1
> > for n in l:
> >   c = x + n
>
> Haskell does not have loops, but if it did, all these values would be
> fractionals.

That's quite complex and restrictive, but probably it's because my
mind is not tuned to Haskell yet. Anyway, I don't think Python should
work that way, because Python have a plan for numerical integration
which would unify all numerical types into an apparent single type,
which requires removal of operator's limitations.

On Mar 2, 2:23 pm, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > def mean(data): return sum(data)/len(data)
>
> > That does the right thing for data, no matter of what it consists of:
> > floats, ints, Decimals, rationals, complex numbers, or a mix of all of
> > the above.
>
> One of those types is not like the others: for all of them except int,
> the quotient operation actually is the inverse of multiplication.
> So I'm unpersuaded that the "mean" operation above does the "right
> thing" for ints.  If the integers being averaged were prices
> in dollars, maybe the result type should even be decimal.

In __future__ Python or Python 3.0, that mean function would work for
all types. And divisions on int is also inverse of multiplications,
just like subtraction is the inverse of addition:
from __future import division
a = 10
b = 5
c = a / b
if c * b == a: print 'multiplication is inverse of division'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-02 Thread Lie
On Mar 2, 10:02 pm, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > Anyway, I don't think Python should
> > work that way, because Python have a plan for numerical integration
> > which would unify all numerical types into an apparent single type,
> > which requires removal of operator's limitations.
>
> Well I think the idea is to have a hierarchy of nested numeric types,
> not a single type.

You hit the right note, but what I meant is the numeric type
unification would make it _appear_ to consist of a single numeric type
(yeah, I know it isn't actually, but what appears from outside isn't
always what's inside).

> > from __future import division
> > a = 10
> > b = 5
> > c = a / b
> > if c * b == a: print 'multiplication is inverse of division'
>
> Try with a=7, b=25

They should still compare true, but they don't. The reason why they
don't is because of float's finite precision, which is not exactly
what we're talking here since it doesn't change the fact that
multiplication and division are inverse of each other. One way to
handle this situation is to do an epsilon aware comparison (as should
be done with any comparison involving floats), but I don't do it cause
my intention is to clarify the real problem that multiplication is
indeed inverse of division and I want to avoid obscuring that with the
epsilon comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-03-03 Thread Lie
On Mar 2, 11:36 pm, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> Lie <[EMAIL PROTECTED]> writes:
> > You hit the right note, but what I meant is the numeric type
> > unification would make it _appear_ to consist of a single numeric type
> > (yeah, I know it isn't actually, but what appears from outside isn't
> > always what's inside).
>
> That is clearly not intended; floats and decimals and integers are
> really different from each other and Python has to treat them distinctly.

In certain operations it would, such as:
a = Decimal('32.324')
b = 90.3453
c = 43
d = a + b + c   <<< this should work without manual type casting

This behavior is what is intended in numeric type unification, floats
and decimals and integers should work together flawlessly without the
need for manual type casting. This gives the _impression_ of a single
numeric type (although programmers should still be aware that the
underlying type still exists). It's true Python have to treat them
differently, but programmers would be able to treat them all the same
(at least in most parts)

> > > Try with a=7, b=25
>
> > They should still compare true, but they don't. The reason why they
> > don't is because of float's finite precision, which is not exactly
> > what we're talking here since it doesn't change the fact that
> > multiplication and division are inverse of each other.
>
> What?  Obviously they are not exact inverses for floats, as that test
> shows.  They would be inverses for mathematical reals or rationals,
> but Python does not have those.

When I said multiplication and division are inverse, I was pointing
out the fact that even though float's inexactness make them imperfect
inverse, mult & div are still inverse of each other. In-practice, the
inversing behavior is impossible unless we have a way to represent
real number (which we don't), and the *workaround* to make them work
is to do epsilon comparison.

When I'm talking about things I usually talk in purely theoretical
condition first and considers practical implementations that doesn't
work that way as making up a workaround inside their limitations. In
this case, the theoretical condition is that multiplication and
division is inverse of each other. The practical consideration is
float is inexact and reals is impossible, and thus epsilon comparison
is necessary to walk around float's limitations so multiplication and
division could still be inverses.

Aside: Python would have rationals

> > One way to handle this situation is to do an epsilon aware
> > comparison (as should be done with any comparison involving floats),
> > but I don't do it cause my intention is to clarify the real problem
> > that multiplication is indeed inverse of division and I want to
> > avoid obscuring that with the epsilon comparison.
>
> I think you are a bit confused.  That epsilon aware comparison thing
> acknowledges that floats only approximate the behavior of mathematical
> reals.  

Yes, I realized that floats aren't the same as reals.

> When we do float arithmetic, we accept that "equal" often
> really only means "approximately equal".  But when we do integer
> arithmetic, we do not expect or accept equality as being approximate.
> Integer equality means equal, not approximately equal.  That is why
> int and float arithmetic cannot work the same way.

No, no, they don't work the same way, but they should appear to work
the same way as reals in pure mathematics do. Again, I'm talking in
theory first: ints and floats should work the same way, but since
practical considerations make them impossible, then they should at
least appear to work the same way (or they would have become
completely different things, remember duck typing?).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sympy: what's wrong with this picture?

2008-03-04 Thread Lie
On Mar 4, 1:12 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Mar 3, 11:58 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
>
> > Mensanator wrote:
> > > While we're on the subject of English, the word "worthless"
> > > means "has no value". So, a program that doesn't work would
> > > generally be "worthless". One that not only doesn't work but
> > > creates side effects that cause other programs to not work
> > > (which don't have bugs) would be "worse than worthless".
>
> > All programs have bugs, which means that in some circumstances, they
> > won't work.  
>
> And in such circumstances, would be worthless.
>
> > Therefore, by your reasoning, all programs are worse than
> > useless.
>
> That doesn't follow from my reasoning.
>
> Suppose you downloaded a new calculator program that
> couldn't add properly. That would be useless to you, right?
>
> But suppose the program contained a virus that erased
> your hard drive. That would be "worse than useless", wouldn't it?
>
>
>
> > > I'm not hard to please at all.
>
> > No, of course not, since logically you must think all software is useless.
>
> Somehow, I expected better logic from people who call themselves
> programmers.

Mensanator, for alls sake, you've done right by pointing out the bug
instead of muttering silently in your room, but there is a thing
called tolerance that you really should learn, it's about tolerating
and understanding the possibility that other people are humans too and
humans create mistakes, lots of them in fact and that includes you (if
you're humans). Along with tolerance should come a better choice of
wordings, instead of saying "it sucks because it does something
unexpected and unwanted" and telling everyone not to use it, you could
just say "it does something unexpected and unwanted" and say that you
wanted it fixed. It's not that you've done anything wrong, but it's
about your attitude.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-08 Thread Lie
On Mar 8, 12:19 am, rockingred <[EMAIL PROTECTED]> wrote:
> Dates can be a pain.  I wrote my own date program, simply because
> there are so many different ways to write a date:
>
> Mar 8, 2008
> March 8th, 08
> 03/08/08
> 03-08-2008
>
> And so on and so forth.  The tricky bit is how to tell the difference
> between Day, Month and Year.
>
> I wrote a program to check the format used for a date.  I assumed that
> any 4 digits together in a single group were the year.  Then I had a
> list of Months, with the first 3 characters of each and compared that
> to the field being checked, if found, then that was the month.  Then I
> assumed any number greater than 12 was a day.  If I couldn't match
> those criteria I assumed Month Day Year (the standard at the company I
> worked for).

If humans are sometimes confused about this, how could a computer
reliably tells the correct date? I don't think it's possible (to
_reliably_ convert string to date), unless you've got an agreed
convention on how to input the date.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-08 Thread Lie
On Mar 8, 8:34 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote:
> > Pierre Quentel <[EMAIL PROTECTED]> writes:
> >> I would like to know if there is a module that converts a string to a
> >> value of the "most probable type"
>
> >     Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
> >     >>> import this
> >     The Zen of Python, by Tim Peters
> >     ...
> >     In the face of ambiguity, refuse the temptation to guess.
>
> Good advice, but one which really only applies to libraries. At the
> application level, sometimes (but not always, or even most times!)
> guessing is the right thing to do.

Guessing should only be done when it have to be done. Users should
input data in an unambiguous way (such as using 4 digit years and
textual month name, this is the most preferred solution, as
flexibility is retained but ambiguity is ruled out) or be forced to
use a certain convention or be aware of how to properly input the
date. Guessing should be done at the minimum. Personally, when I'm
working with spreadsheet applications (in MS Office or OpenOffice) I
always input dates in an unambiguous way using 4-digit year and
textual month name (usually the 3-letter abbrevs for quicker
inputting), then I can confidently rely the spreadsheet to convert it
to its internal format correctly.

The general parsers like the OP wanted are easy to create if dates
aren't involved.

> E.g. spreadsheet applications don't insist on different syntax for
> strings, dates and numbers. You can use syntax to force one or the other,
> but by default the application will auto-detect what you want according
> to relatively simple, predictable and intuitive rules:
>
> * if the string looks like a date, it's a date;
> * if it looks like a number, it's a number;
> * otherwise it's a string.

The worse thing that can happen is when we input a date in a format we
know but the application can't parse and it consider it as a string
instead. This kind of thing can sometimes easily pass our nose. I
remembered I once formatted a column in Excel to write date with
certain style, but when I tried to input the date with the same style,
Excel can't recognize it, making the whole column rendered as useless
string and requiring me to reinput the dates again.

> Given the user-base of the application, the consequences of a wrong
> guess, and the ease of fixing it, guessing is the right thing to do.
>
> Auto-completion is another good example of guessing in the face of
> ambiguity. It's not guessing that is bad, but what you do with the guess.
>
> --
> Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-08 Thread Lie
Personally I preferred a code that has chosen good names but have
little or no comments compared to codes that makes bad names and have
twenty pages of comments to read and understand what it's about.
Personally, I think comments should be made as short and as concise as
possible and codes should try to be self-understandable if the
comments aren't accessible.
-- 
http://mail.python.org/mailman/listinfo/python-list


What c.l.py's opinions about Soft Exception?

2008-03-08 Thread Lie
I'm asking about people in c.l.py's opinion about a _probably_ very
Pythonic way of doing something if such features is implemented. It is
to be known that I'm not a Python expert and actually relatively new
to Python programming, so probably I'm just not thinking pythonic
enough yet or this feature might already exist somewhere in a
different name.
Anyway, I'm just asking for opinions, tell me problems I haven't
foreseen, or whether such things would be hard to implement, or
whether you think the idea is great or plain bad (and why).

Soft Exception
What is "Soft Exception"?
Soft Exception is an exception that if is unhandled, pass silently as
if nothing happened. For example, if a variable turns into NoneType,
it'll raise Soft Exception that it have become NoneException,
programmers that wants to handle it can handle it with a try...except
block while programmers that doesn't care about it (or know it won't
be a problem to his code) can just leave the code as it is.

Soft Exception differs from Hard Exceptions (the regular Exception) in
a way that Hard Exception must be handled at all cost or the program
will be terminated while Soft Exception allow programmers not to
handle it if they don't want to.

Soft Exception is similar to an event-based system, although Soft
Exception can only be handled by codes above it while Event-based
system can be handled by anyone aware of the handle pool. The Soft
Exception can also be thought as a Warning to the codes above it that
it has done something that the codes above might want to know.

Implementation:
Simple implementation might be done by catching all exceptions at the
highest level, then filtering which exceptions would be stopped (Soft
Exception) and which exceptions will be reraised and terminate the
program (Hard Exception). This is simple and can be easily implemented
but is inefficient as that means all soft exceptions must bubble
through its way to the top to find out if it is Soft or Hard.

A more through implementation would start from the raiser inspecting
the execution stack and finding whether there are any try block above
it, if no try block exist it pass silently and if one exist it will
check whether it have a matching except clause. This also circumvents
a problem that simple implementation have, as described below.

Syntax change is probably unneeded and a Soft Exception class may be
created by inheriting from BaseSoftException class.

Problems:
- If the raising statement is a complex statement (like function call)
instead of just a simple statement (like assignment from an
expression) the exception might catch a similar soft exceptions from
deep _inside_ the function call and handle it as if it happened in the
code it's protecting. This problem can be solved by raising Soft
Exception only once except if explicitly reraised (perhaps through
except SoftException: raise).
This can be done by modifying a flag that is turned off (Falsed) if
the Soft Exception is raised and turned on again (Trued) if the Soft
Exception is reraised. Normal Exceptions (Hard Exceptions) would have
this flag turned off (Falsed) if it is handled and turned on (Trued)
again if it is reraised.

- To be half useful, soft exceptions have to be raised everywhere here
and there, not just here and here only. This might require a massive
change in current codes, or at least in Python's official libraries.

- Irresponsible programmers. Sometimes lazy programmers might decides
to be lazy and make all exceptions soft so he doesn't have to handle
it.

Ideology Base:
- EAAP: Easier to apologize than to ask permission.

Others:
- Sometimes it might be useful to convert a Soft Exception into Hard
Exception or vice versa.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python installation problem

2008-03-08 Thread Lie
On Mar 9, 11:42 am, [EMAIL PROTECTED] wrote:
> Hi Folks,
>
> I downloaded a pre-compiled version 2.5, and intalled it without any
> error message; and I can command line playing on Python through firing
> up IDLE or command-line. However, I just can't compile the python file
> existing in a directory. Today, I tried to fire Python in a DOS
> window, then I got error message: Python is not a runnable command or
> batch file. It means that the eveiornment variables of my Python
> interpreter are not set well yet. My computer runs a Windows XP.
> Anyboy can help on this? Thanks!
>
> Muddy Coder

AFAIK, Python doesn't set environment variables in Windows. To change
the environment variable, you go to Control Panel > System > Advanced
> Environment Variables > System Variables > In "Path" entry, add
Python's installation directory to the end of it (remember to separate
it from other directories with semicolons ;

Alternatively, you can cd your way through python's directory and
always feed absolute path to python.exe, very tiresome, but doesn't
require you to add the environment variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote:
>
> > A more through implementation would start from the raiser inspecting
> > the execution stack and finding whether there are any try block above
> > it, if no try block exist it pass silently and if one exist it will
> > check whether it have a matching except clause. This also circumvents
> > a problem that simple implementation have, as described below.
>
> This will not be easy in particular in the presence of inheritance and
> dynamism. There is no way to statically decide whether an exception
> BException has the type AException and will be caught by the except
> clause in
>
> try:
> BLOCK
> except AException, e:
> print "SoftException %s caught"%e



> A feasible solution was to invert the try...except statement and
> creating a continuation.
>
> catch AException, a:
>print "SoftException A: %s"%a
> catch BException , b:
>print "SoftException B: %s"%b
> ...
> in:
>BLOCK
>
> Here each SoftException is raised initially when a catch clause is
> entered and a continuation is created that returns to the catch block
> of the raised SoftException if required. When a SoftException is
> raised within BLOCK a lookup will be made and if a corresponding
> SoftException was found that was raised by a catch-clause the current
> control flow will be suspended and the continuation is called.

I'd rather want to avoid any syntax changes, as I wished that Soft
Exception can be added to the language silently[1] so that new
programmers doesn't _need_ to know about it (although knowing it could
change the way they write codes to be more structured and simple).

[1] Definition of silently: Codes that aren't aware of this
functionality shouldn't break. Adding new syntax usually means adding
keywords, making possible break in current program.

On Mar 9, 12:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 08 Mar 2008 19:51:24 -0800, Lie wrote:
> > Soft Exception
> > What is "Soft Exception"?
> > Soft Exception is an exception that if is unhandled, pass silently as if
> > nothing happened. For example, if a variable turns into NoneType, it'll
> > raise Soft Exception that it have become NoneException, programmers that
> > wants to handle it can handle it with a try...except block while
> > programmers that doesn't care about it (or know it won't be a problem to
> > his code) can just leave the code as it is.
>
> > Soft Exception differs from Hard Exceptions (the regular Exception) in a
> > way that Hard Exception must be handled at all cost or the program will
> > be terminated while Soft Exception allow programmers not to handle it if
> > they don't want to.
>
> I don't think that there are very many cases where exceptions can be
> ignored safely. There are two main reasons for using exceptions:
>
> (1) Signaling an exceptional event.

In that case, programmers might decide whether to raise Soft or Hard
Exception. Hard Exception is much preferred.

> (2) An error occurred.

Which must always be handled with Hard Exception.

Adding another thing
(3) Informing codes above it about what's currently happening inside,
the thing is just a mundane report that might be useful to codes above

Which might be a useful place to use SoftExceptions

> I can't think of many cases where you would wish to ignore either, and
> just continue processing. The only examples I can think of are in loops,
> where you are doing the same thing over and over again with just a little
> change, and you wish to skip any problematic data, e.g.:
>
> def plot_graph(func, domain):
>     for x in domain:
>         plot(x, func(x))
>
> If an error occurs in plot() for one particular x value, you would want
> to ignore it and go on to the next point. But that's easy enough to do
> with a regular try...except block.

No, you're misunderstanding the purpose of Soft Exception, it's not
for silencing errors and not so much for exceptional cases. It's for
the more mundane tasks such as:

from __future__ import division

class SomeNumeric(object):
def __div__(a, b):
if b == 0: raise ZeroDivisionError  ## Hard Exception, don't
ignore me!
if a == 0: raise ZeroNumerator  ## Soft Exception
f = a / b
i = a // b
if f == float(i):
raise IntegerDivision  ## Soft Exception
return a // b
else:
raise FloatDivision## Soft Exception
return a / b

Most people can ignore the ZeroNumerator, IntegerDivision, and
FloatDivision 

Re: Regarding coding style

2008-03-09 Thread Lie
On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote:
> To Lie:
>
> > Personally I preferred a code that has chosen good names but have
> > little or no comments compared to codes that makes bad names and have
>
> Personally I don't.  Show me a good one.  Until you do, it's not that
> I won't like it, it's that I can't.  You know, in linguistics, there's
> what's called 'code switching', which is switching between two
> languages you know midstream.  People can understand 'hear' a language
> but not speak it.  If you speak it, .  If comments aren't
> the 'short version', then patience is the problem.  There's not one
> word for lots and lots of things.  Examples on backorder.

But I much prefer it that the code has good names AND concise
comments, not too short and not too long that it becomes obscure. If
the code is complex, that it's hard to explain in a few sentences, it
might be a good idea to refactor it.

If I have to choose between bad names + twenty pages of documentation
and good names + a paragraph of short documentation, I chose the
latter.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 6:57 pm, Bryan Olson <[EMAIL PROTECTED]> wrote:
> Lie wrote:
>
> [...]> Soft Exception is an exception that if is unhandled, pass silently as
> > if nothing happened.
>
> [...]
>
> > Implementation:
> > Simple implementation might be done by catching all exceptions at the
> > highest level, then filtering which exceptions would be stopped (Soft
> > Exception) and which exceptions will be reraised and terminate the
> > program (Hard Exception). This is simple and can be easily implemented
> > but is inefficient as that means all soft exceptions must bubble
> > through its way to the top to find out if it is Soft or Hard.
>
> If I'm following what you want, that "simple implementation" does
> not work.  If a function, possibly deep in a call stack, raises a
> soft exception that no caller above catches, what executes next?

The highest possible code that could catch exceptions would have
something like this:

try:
## Everything is happening inside me
except SoftException:
pass

> Correct me if I'm misunderstanding your idea: You want raising
> an un-caught soft exception to be equivalent to a 'pass';
> execution continues as if the 'raise' never happened.
>
> Catching everything at a high level does nothing like that. The
> exception causes execution to leave the function invoking the
> raise statement, and abolishes the stack state from the point of
> the raise to the point of the catch.

The high-level mentioned here is outside our own code, it'll be inside
Python's internal. When CPython (or any implementation of Python) sees
that a particular exception is raised to a certain point, it'll check
whether it is of type SoftException, and if it is, it'll return
program state to the place where the exception is raised before. I
don't know how Python's exception system works (as I tell you I know
next to nothing about Python's internal, although I'm interested to
know), so probably if there is any defect in the implementation
schemes I mentioned, it is simply caused by my ignorance.

> As Python exceptions currently work, "catching all exceptions
> at the highest level" is either what Python already does, or
> ill-defined nonsense. When an exception is uncaught, there is
> no useful "highest level", other than the level at which the
> program simply fails. Python *must* terminate execution upon
> an unhanded exception, because the program defined no state
> from which executions could correctly continue.

That's where the difference between Soft Exceptions and Hard
Exceptions lies. Soft Exception must be continued while Hard
exceptions must terminate programs. Possibly this is impossible at the
absolutely highest level, perhaps it should be done at the level that
can guarantee

> > A more through implementation would start from the raiser inspecting
> > the execution stack and finding whether there are any try block above
> > it, if no try block exist it pass silently and if one exist it will
> > check whether it have a matching except clause. This also circumvents
> > a problem that simple implementation have, as described below.
>
> The described problems do not include the "where should execution
> resume" problem, which I think is central to the issue.

I didn't mentioned it?
I think it's obvious when I say: Execution should resume as if nothing
happened, as if there is nothing raised, that means execution resumes
at the point after the raise statement. If something was caught,
execution isn't resumed and execution continues at the level of the
handler (possibly we could also add a "resume" to explicitly resume
the statement that was caught)

> Correct me
> if I've misunderstood: A "soft" exception is one that gets raised
> only if some calling frame has arranged to catch it.

That could be a way to implement it. And btw, that's a one-line-
explanation that hits the right note (although from a different view I
initially mentioned).

> The if-exception-would-be-unhanded-then-pass logic strikes me as
> interesting. It would be a huge change to Python, so I doubt it
> will get traction here.  Still, I'd say it's worth more
> consideration and discussion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 4:31 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 9 Mrz., 09:30, Lie <[EMAIL PROTECTED]> wrote:
> > On Mar 9, 12:05 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > > On 9 Mrz., 04:51, Lie <[EMAIL PROTECTED]> wrote:
>
> > > > A more through implementation would start from the raiser inspecting
> > > > the execution stack and finding whether there are any try block above
> > > > it, if no try block exist it pass silently and if one exist it will
> > > > check whether it have a matching except clause. This also circumvents
> > > > a problem that simple implementation have, as described below.
>
> > > This will not be easy in particular in the presence of inheritance and
> > > dynamism. There is no way to statically decide whether an exception
> > > BException has the type AException and will be caught by the except
> > > clause in
>
> > > try:
> > >     BLOCK
> > > except AException, e:
> > >     print "SoftException %s caught"%e
> > > A feasible solution was to invert the try...except statement and
> > > creating a continuation.
>
> > > catch AException, a:
> > >    print "SoftException A: %s"%a
> > > catch BException , b:
> > >    print "SoftException B: %s"%b
> > > ...
> > > in:
> > >    BLOCK
>
> > > Here each SoftException is raised initially when a catch clause is
> > > entered and a continuation is created that returns to the catch block
> > > of the raised SoftException if required. When a SoftException is
> > > raised within BLOCK a lookup will be made and if a corresponding
> > > SoftException was found that was raised by a catch-clause the current
> > > control flow will be suspended and the continuation is called.
>
> > I'd rather want to avoid any syntax changes, as I wished that Soft
> > Exception can be added to the language silently[1] so that new
> > programmers doesn't _need_ to know about it (although knowing it could
> > change the way they write codes to be more structured and simple).
>
> I just tried to save your proposal from being unimplementable. Maybe
> you can comment on it?

Perhaps I'm not the appropriate person to talk about whether unchanged
syntax is feasible for such implementation since I basically have no
idea about how Python's internals works. It's only that I think if
current syntax could be used, we could just use it (except if there is
a strong reason why it shouldn't be done).

> I know of course that syntax is Pythons holy cow but I'm not Guidos
> mouthpiece and have a different perspective on some aspects of the
> system for obvious reasons [1].

I agree, everybody have different perspective. But that differences is
what makes languages evolves as it'd be continuously searching for the
most optimal perspective.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 7:54 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 09 Mar 2008 00:30:51 -0800, Lie wrote:
> > (3) Informing codes above it about what's currently happening inside,
> > the thing is just a mundane report that might be useful to codes above
>
> > Which might be a useful place to use SoftExceptions
>
> Okay, now we're getting somewhere.
>
> So, I have a function foo() which raises a HardException on error, but it
> also raises a SoftException if it wants to notify me of something
> "mundane".
>
> def foo(sequence):
>     if args == []:
>         raise SoftException("empty list")
>     return len(args)
>
> Now, how do I use that?
>
> try:
>    x = foo(something)
> except TypeError:
>    print "you should pass a sequence"
>    sys.exit()  # unrecoverable error
> except SoftException:
>    print "you passed an empty list"
> print x
>
> Am I close?
>
> But there's a problem. Once the SoftException is caught, execution will
> continue from the line "print x" -- but the function foo() never got a
> chance to actually return a result!

In that particular case above, you don't need to handle the Soft
Exception. As stated in it's original purpose, you don't need to
handle a Soft Exception, it exists there if you need to handle the
exceptional case, but ignorable on other cases. _IF_ printing the "you
passed an empty list" is an important operation, you'd make it like
this:
try:
   x = foo(something)
except TypeError:
   print "you should pass a sequence"
   sys.exit()  # unrecoverable error
except SoftException:
print "you passed an empty list"
x = 0
print x

or alternatively:

try:
   x = foo(something)
except TypeError:
   print "you should pass a sequence"
   sys.exit()  # unrecoverable error
except SoftException:
print "you passed an empty list"
else:
print x

The case you states above only mentions that you haven't fully grasped
the workflow in exception-based system.

> In order to make that work, you would need a significant change to
> Python's internals. I don't know how difficult that would be, but I'm
> guess that it would be a lot of work for not much benefit.

I too don't know how difficult that'd be, especially because the only
thing I know about Python's internal is it implements its garbage
collector by ref counting (which is barely useful here).

> But even if that happened, it would mean that the one mechanism has TWO
> different effects:
>
> try:
>     x = foo(sequence)
> except SoftException:
>     print x  # this is okay, because foo() did return
> except TypeError:
>     print x  # this is NOT okay, because foo() never returned
>
> That is a recipe for confusion.

Both are not okay since foo() never return on both cases (soft
statement doesn't return to finish the try clause except if explicitly
resumed).

(snip)
> > Perhaps relabeling it as Warning, and renaming raise SoftException as
> > give Warning might make it more acceptable?
>
> Do you realise that Python already has a warnings module?

Ah... I completely forget about it, but anyway the Warning module is
unrelated to this. Perhaps we could just think of another name, but
names doesn't seems to be important in Python modules anyway, can you
guess what pickle/zip/mutex/quopri/curses is if you're new to Python
without looking at the documentations? There are some modules in
Python that have weird names, we ought to reduce it, but we can't
reduce it... we ought to live with it.

(snip)
> > A possible solution to this problem might be to check whether distance
> > is less than P1.radius + P2.radius in the calculateforce. But, this
> > obfuscate the code since we have to separate distance calculation from
> > the main formula (see !s),
>
> I don't agree that this obfuscates the code.

For a formula as complex as this:
http://www.mapleprimes.com/blog/axel-vogt/computing-the-complex-gamma-function-using-spouges-formula
it might be useful to fragment the formula to smaller pieces

but in a simple to moderately complex that still fits in one line,
fragmenting the code confuses the eye.

> And here's a way to do it that doesn't calculate anything twice, and
> doesn't require any exceptions:
>
> def calculateforce(P1, P2, dist):
>     return (P1.mass - P2.mass)/dist
>
> And then for all pairs of particles:
>
> dist = distance(P1, P2)
> if dist <= P1.radius + P2.radius:
>     clump(P1, P2)
>     break
> F = calculateforce(P1, P2, dist)

That... is the worst solution that c

Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Lie
On Mar 9, 9:29 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
(snip)
> You are an appropriate person to consider the workflow in a dynamic
> language, no matter how the language is implemented internally.

I agree, but the only thing I'm not confident to talk about is how
it'll be implemented, since I think an idea should suggest how it can
be implemented in practice to show that it's not just a nonsense paper
idea that's not possible in reality.

> Just start with function calls
>
>    maybe_raise(ZeroDivisionError)
>
> The only requirement is that maybe_raise has to know when it shall
> raise ZeroDivisionError. This depends on whether the exception is
> caught. How do the program knows this in advance? There are no static
> analysis techniques available.

Perhaps similar technique the compiler uses to determine whether a
function is a normal function or a generator function? Positive
forward lookup for any soft exceptions, which would then activate
matching soft exceptions inside the code?

> When maybe_raise is entered the system must know that the exception is
> handled in the future. You can't inspect the call stack for this
> purpose because the call stack represents past events and
> continuations ( and you can't rely on names ).
>
> So you need something like this
>
>    do_softexception(ZeroDivisionError)
>    try:
>       TRY_BLOCK
>    except ZeroDivisionError:
>       EXCEPT_BLOCK
>
> But this looks odd and the solution isn't DRY. So better one macro-
> transforms a new statement into this form.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-10 Thread Lie
On Mar 10, 12:12 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano wrote:
> > On Sat, 08 Mar 2008 22:24:36 -0800, Kay Schluehr wrote:
>
> >> On 9 Mrz., 06:30, Steven D'Aprano <[EMAIL PROTECTED]
> >> cybersource.com.au> wrote:
> >> Is it really so exotic that it requires the demand for more use cases?
>
> > Are the existing solutions really so incomplete that we need yet another
> > solution?
>
> > What problem are you trying to solve with SoftExceptions?
>
>     I actually implemented something like "soft exceptions" in a LISP
> program long ago. I called them "gripes".  They were a way that a function
> could complain about something it wanted the caller to fix. The caller
> could either fix it or decline to do so.
>
>     This was for a robotic planning application, where one module had detected
> that some precondition that it needed wasn't satisfied.  This was usually
> something like some physical object being in the wrong place for a later
> operation, and a previously planned move needed to be modified. Passing
> the problem back to the caller sometimes allowed an easy fix, rather than
> aborting the whole plan and building a new one.
>
>     This isn't a common problem.
>
>     In the rare cases that it is needed, it can be implemented with callbacks.
> It doesn't require a language extension.
>
>                                         John Nagle

The problem with callbacks is that it works only for a small amount of
callbacks, it'd be too messy to have twenty different callbacks.
And the ultimate problem with callbacks is that we can't determine
from the outside whether the operation should continue or breaks at
the point of the callback without some messy trick.

We can't always determine whether we want to do this:
def somefunc(argA, argB, callback = DO_NOTHING):
if argA == argB:
callback()

or this:
def somefunc(argA, argB, callback = DO_NOTHING):
if argA == argB:
callback()
return

perhaps we could do this:
if argA == argB:
if callback() == True: return

but that's so much extra codes written and would've been too messy to
write.

And actually this isn't a rare cases, and in fact is very common. It's
just that most cases that can be more cleanly written in
SoftException, can usually be handled in different ways, using tricks
that range from subtle to messy (like callbacks).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-11 Thread Lie
On Mar 11, 2:18 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > The problem with callbacks is that it works only for a small amount of
> > callbacks, it'd be too messy to have twenty different callbacks.
> > And the ultimate problem with callbacks is that we can't determine
> > from the outside whether the operation should continue or breaks at
> > the point of the callback without some messy trick.
>
> > We can't always determine whether we want to do this:
> > def somefunc(argA, argB, callback = DO_NOTHING):
> >     if argA == argB:
> >         callback()
>
> > or this:
> > def somefunc(argA, argB, callback = DO_NOTHING):
> >     if argA == argB:
> >         callback()
> >         return
>
> > perhaps we could do this:
> >     if argA == argB:
> >         if callback() == True: return
>
> > but that's so much extra codes written and would've been too messy to
> > write.
>
> > And actually this isn't a rare cases, and in fact is very common. It's
> > just that most cases that can be more cleanly written in
> > SoftException, can usually be handled in different ways, using tricks
> > that range from subtle to messy (like callbacks).
>
> I fail to see how your arguments follow.
>
> Regarding the number of callbacks: you can as well pass an object that
> has several methods to call.

If you passed an object that has several methods to call (using tuple
or list) and you want to handle several softexceptions and ignore some
others, you must still pass an empty methods to the one you want to
ignore, cluttering the caller's code by significant degree:

def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING,
DO_NOTHING)):
if a == 0: raise callback(0)
try:
a += b
except ZeroDivisionError:
raise callback(1)
if a <= 0: raise callback(2)
raise callback(3)
return a

somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo,
DO_NOTHING))

if instead we use dict, well, we know how convenient dict's syntax is for a lot of manual data entry.

## imagine if we want to handle five or more callbacks
somefunc(a, b, {callbackzero:handlerzero,
callbacktwo:handlertwo})

> And the above example can easily be accomplished with "normal"
> exceptions, like this:
>
> def toplelevel():
>      def callback(a, b):
>          if a == b:
>             raise InterruptException()
>      try:
>           work(callback)
>      except InterruptException:
>           pass
>
> def work(callback=callback):
>      a = 10
>      b = 20
>      callback(a, b)

That's why I said most things that can be more cleanly handled by
SoftException can usually be handled in other forms, although in a
more cluttered way.

That could be more cleanly written in SoftException as:
def work():
a = 10
b = 20
raise Equal(a, b)

def toplevel():
try:
work()
except Equal, args:
a, b = args
if a == b:
raise InterruptException

OR ALTERNATIVELY (Which one's better depends on the purpose, generally
the one below is better, but the one in the above is more flexible,
yet a bit less convenient to use)

def work():
a = 10
b = 20
if a == b: raise Equal

def toplevel():
try:
work()
except Equal:
raise InterruptException

The reason why SoftException is useful is similar to the reason why
for-loop and while  is useful. AFAIK, all looping cases can
be handled only by a blind loopers (a.k.a. while True:) and break, but
a blind loopers is very inconvenient to use, and for-loop and while
 simplifies a lot of codes a lot. Exactly the same reason
why SoftException is useful.

> And even more: the callback-approach can do things like this:
>
> a, b = callback(a,b)
>
> to change values, which makes it superior to SoftExceptions - unless I
> missed it's ability to capture context.

If there is a syntax support, you could also make "resume" able to
transfer values:

def somefunc(a, b):
if a == b: a, b = raise Equal(a, b)

def toplevel():
try:
somefunc(10, 20)
except Equal, args:
a, b = args[0], args[1] + 1
resume a, b

On Mar 11, 5:18 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> How would that differ from something like this:
>
> with add_soft_handler(SoftException):
> invoke_something()
>
> ... # deep down in code
>
> raise_soft(SoftException())
>
> The implementation of add_soft_handler and raise_soft is trivial - a bit
> of thread-local storage and a stack.

Perhaps you meant:
raise_soft(SoftException)

cause SoftException() may have side effects if called greedily

That could be done, but when raise_soft() returns, it returns to the
code that raises it so it must be 'break'en:

def caller(a, b):
if a == b:
raise_soft(SoftException)
break

but this makes SoftException must break everytime, which make it

Re: __iter__ yield

2008-03-11 Thread Lie
On Mar 10, 3:58 am, duccio <[EMAIL PROTECTED]> wrote:
> Hello!
> Someone knows if it's possible to make this __iter__ function with just
> one 'yield' intead of two?
> Is there some simpler way to make this  __iter__ iter through all nodes?
> Thanks!
>
> class Node:
>  def __init__(self, data=None):
>  self.childs=[]
>  self.data=data
>  def appendNode(self, n):
>  node=Node(n)
>  self.childs.append(node)
>  return node
>  def __str__(self):
>  return '<'+str(self.data)+'>'
>  def __iter__(self):
>  yield self #1
>  for n in self.childs:
>  for nn in n.__iter__():
>  yield nn #2
>
> n=Node()
> n.appendNode(1).appendNode(2).appendNode(3).appendNode(4)
> n.appendNode(11).appendNode(22).appendNode(33).appendNode(44)
> for node in n:
>  print node

Technically, the root node isn't a child node, and thus it shouldn't
show up in the iteration. I think a more semantically correct way for
this is to have the __str__() returns the current Node + All
Descendants Nodes (like the one you wanted for __iter__) and while
__iter__ only yields the child nodes (used by the __str__ to iterate
through itself), like this:

class Node:
def __init__(self, data=None):
self.childs=[]
self.data=data
def appendNode(self, n):
node=Node(n)
self.childs.append(node)
return node
def __str__(self):
## Returns root node + all descendants
return '<%s>\n' % self.data +
   ''.join(str(child) for child in self)
def __iter__(self):
## yields childrens only
for n in self.childs:
yield n

n=Node()
n.appendNode(1).appendNode(2).appendNode(3).appendNode(4)
## Note I added the line below for testing branches in
## lower nodes
n.childs[0].appendNode(222)
n.appendNode(11).appendNode(22).appendNode(33).appendNode(44)
print n

The missing functionality of returning current Node's name can be
easily solved by adding it in another function.

The main problem with __iter__ behavior you originally wanted is that
it doesn't reflect the nesting behavior of the Node class and you
could've been equally well served by using flat data structure if you
do that. I smell a bad data structure design here, you'd better revise
your design.

To reflect the nesting, you could do it like this:

class Node:
def __init__(self, data=None):
self.childs=[]
self.data=data
def appendNode(self, n):
node=Node(n)
self.childs.append(node)
return node
def __str__(self):
## This reflects nesting behavior better
return '\n<%s>' % (str(self.data) +
   ''.join(str(child) for child in self))

## Uncomment this and Comment the statement above
## for an alternate data structure you might be
## interested in, the format below resembles HTML
##curNode = str(self.data)
##return '\n<%s>%s\n' % (
##curNode,
##''.join(str(child) for child in self),
##curNode)

def __iter__(self):
for n in self.childs:
yield n

n=Node()
n.appendNode(1).appendNode(2).appendNode(3).appendNode(4)
n.childs[0].appendNode(222)
n.appendNode(11).appendNode(22).appendNode(33).appendNode(44)
print n


This changes the data structure quite a lot though, but the data
structure is bad from the start.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-11 Thread Lie
On Mar 10, 4:16 am, [EMAIL PROTECTED] wrote:
> On Mar 9, 4:25 am, Lie <[EMAIL PROTECTED]> wrote:
>
> > On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote:
>
> > > To Lie:
>
> > > > Personally I preferred a code that has chosen good names but have
> > > > little or no comments compared to codes that makes bad names and have
>
> > > Personally I don't.  Show me a good one.  Until you do, it's not that
> > > I won't like it, it's that I can't.  You know, in linguistics, there's
>
> > But I much prefer it that the code has good names AND concise
> > comments, not too short and not too long that it becomes obscure.
>
> What do you mean?  If 'obscure' is the right word, then it's
> subjective (from metrics import obscurity?), which means that 10% of
> the people disagree with you, or 90% do.  The end-all be-all, there is
> no such thing.  I don't think it's obscure; I do.  Is it?

No, there is a point where everyone would say obscure. Such as a
simple two integer addition function that have thirty pages of
documentation and that have names like:
def dosomereallyfunkythings(argumentoneissomethingadded,
argumentbisaddinga):
""" blah blah blah blah
...
30 or so pages later...
...
Ok, that is the end of it, it's a complex function actually
"""
return argumentoneissomethingadded + argumentbisaddinga

(remember you don't have access to source code, so you have to
decipher the documentation for what the function is about)

I prefer to see something like this:
def add(a, b):
return a + b

Even without documentation I'd know immediately what it does from the
name (add)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to factor using Python?

2008-03-11 Thread Lie
On Mar 10, 12:08 pm, Nathan Pinno <[EMAIL PROTECTED]> wrote:
> How do I factor a number? I mean how do I translate x! into proper
> Python code, so that it will always do the correct math?
>
> Thanks in advance,
> Nathan P.

Factorial algorithm is a very simple and common algorithm, and it's
one of the most basic of all recursive algorithm
def fact(x):
return x * fact(x - 1)

That recursive function is very close to the basic definition of
factorials, that is
x! = x * (x - 1)!

If however, you expected x to be a real (float) value, you'd better
consider the gamma function as Mark Dickinson pointed out. Wikipedia
is a good start to create your gamma function:
http://en.wikipedia.org/wiki/Factorial
http://en.wikipedia.org/wiki/Gamma_function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to factor using Python?

2008-03-11 Thread Lie
On Mar 11, 11:47 pm, Lie <[EMAIL PROTECTED]> wrote:
> On Mar 10, 12:08 pm, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>
> > How do I factor a number? I mean how do I translate x! into proper
> > Python code, so that it will always do the correct math?
>
> > Thanks in advance,
> > Nathan P.
>
> Factorial algorithm is a very simple and common algorithm, and it's
> one of the most basic of all recursive algorithm
> def fact(x):
>     return x * fact(x - 1)

As an exercise (actually I forget), I'll let you figure out yourself
why the above function doesn't work. There is only one simple line to
be added and all's done.

Hint: There are two important elements in all recursive algorithm, the
catch-all return statement (which I've given you) and the conditioned
return statement (which you've got to figure out yourself)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What c.l.py's opinions about Soft Exception?

2008-03-11 Thread Lie
(If there is anything weird that I say, please ignore it since I'm
writing this half-sleeping)

On Mar 12, 12:00 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
(snip)

> I totally fail to see where
>
> raise Equal(a, b)
>
> is less cluttered or not than
>
> callback(a, b)
>
> Actually, the latter is even less cluttered, misses a raise - if pure number
> of literals is your metric, that is.

You don't just compare by the calling code, you've got to compare also
by the surrounding codes. The calling codes in SE might be a little
bit messy, but it worths by making the code surrounding it more clean
and structured. And anyway, if you used Context Object callback, they
will be as messy as each other.

> > If there is a syntax support, you could also make "resume" able to
> > transfer values:
>
> >     def somefunc(a, b):
> >         if a == b: a, b = raise Equal(a, b)
>
> >     def toplevel():
> >         try:
> >             somefunc(10, 20)
> >         except Equal, args:
> >             a, b = args[0], args[1] + 1
> >             resume a, b
>
> Sure, you can make all kinds of things, but so far you didn't come up with a
> comprehensive feature description that just _does_ specify what SEs are and
> what not.

- Exception that aren't handled when no handler exists for it.
- It's not a way for notifying errors
- It's a way to describe status changes to higher codes
- Everything described in the first post

> > Perhaps you meant:
> >     raise_soft(SoftException)
>
> > cause SoftException() may have side effects if called greedily
>
> Nope, I didn't, and it's beside the point.

Then what happen when SoftException is called? And a side-effect
occurs?

> > That could be done, but when raise_soft() returns, it returns to the
> > code that raises it so it must be 'break'en:
>
> >     def caller(a, b):
> >         if a == b:
> >             raise_soft(SoftException)
> >             break
>
> > but this makes SoftException must break everytime, which make it lost
> > its original purpose, so you have to add return code to raise_soft
> > whether you want to break it or not:
>
> You didn't understand my example. If there is a handler registered, it will
> be invoked. If not, nothing will be raised. The exact same amount of
> state-keeping and lookups needs to be done by the SE-implementation.

I do understand your example. And even if I misunderstood you about
passing context object, the same problem still exists in context
object based solution, i.e. functions can't make the called function
break automatically, it must be 'break' manually or the program will
go astray (break ==> return, sorry I confused it with break for
loops). And if you used InterruptException to break, it doesn't play
well with multiple SoftExceptions.

The final, resulting code by function passing below is extremely
messy, see if you can make it cleaner and with the same
functionalities and all to the SE version.

def called(a, b, cont_obj = Null_CO):
if a == b:
a, b = cont_obj.a_equal_b(a, b)
cont_obj.addition(a, b)
return a + b

def caller():
class cont_obj(object):
def a_equal_b(a, b):
if a < 0 and b < 0:
return a + 1, b  # resume
raise InterruptException(('a_e_b',)) # break

def addition(a, b):
if a > b:
return
raise InterruptException(('addit', (a, b)))   # break

try:
called(10, 10, cont_obj)
except InterruptException, args:   # if breaken
ret, arg = args
if ret == 'a_e_b': return -1
a, b = arg
if ret == 'addit': return a ** b


# by adding try clauses, and you've really equalize the biggest
overhead of SE.
# And I don't think you could create a less messy InterruptException
handler,
# the other solution to it would be to create a handler for each
unique returns
# but that would make it exceed the second SE overhead, the Exception
Declaration
# In other words, the tricks that is used to emulate the SoftException
would all
# have higher code overhead compared to using the clean, structured
SEs

# * Overheads means garbage code that's important to make something
work

# The code is separated into three parts, "try except", and cont_obj,
and called. Worse, the cont_obj can't determine what happen if they
got unresumed errors, without using some tricky part.

Compare that code above with:

def called(a, b):
if a == b:
a, b = raise a_equal_b(a, b)
raise addition(a, b)
return a + b

def caller():
class a_equal_b(Exception): pass
class addition(Exception): pass

try:
ret = called(10, 10)
except a_equal_b(a, b):
if a < 0 and b < 0:
resume a + 1, b
return -1
except addition(a, b):
if a > b: resume
return a ** b

# The cod

Re: List mutation method gotcha - How well known?

2008-03-13 Thread Lie
On Mar 13, 2:36 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am surprised that it took me so long to bloody my nose on this one.
>
> It must be well known - and I would like to find out how well known.
>
> So here is a CLOSED BOOK multiple choice question - no RTFM,
> no playing at the interactive prompt:
>
> Given the following three lines of code at the interactive prompt:
>
> foo = [1,2,3,4]
> x = foo.append(5)
> print x
>
> What will be the output (choose one):
>
> 1)  [1,2,3,4]
> 2)  [1,2,3,4,5]
> 3)  That famous picture of Albert Einstein sticking out his tongue
> 4)  Nothing - no output
> 5)  None of the above
>
> I undertake to summarise answers posted to complete this "survey".
>
> - Hendrik

I think I'll choose 3. Well, no, I suppose the correct behavior
_should_ be undefined (i.e. what it returns is an implementation
details that should not be relied on). The fact that it returns None
is just a "coincidence" that happens to happen every time you tested
it (you can't prove by ignorance)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List mutation method gotcha - How well known?

2008-03-14 Thread Lie
On Mar 14, 4:57 pm, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
> Lie napisa³(a):
>
>
>
> >> foo = [1,2,3,4]
> >> x = foo.append(5)
> >> print x
>
> >> What will be the output (choose one):
>
> >> 1)  [1,2,3,4]
> >> 2)  [1,2,3,4,5]
> >> 3)  That famous picture of Albert Einstein sticking out his tongue
> >> 4)  Nothing - no output
> >> 5)  None of the above
>
> >> I undertake to summarise answers posted to complete this "survey".
>
> > I think I'll choose 3. Well, no, I suppose the correct behavior
> > _should_ be undefined (i.e. what it returns is an implementation
> > details that should not be relied on). The fact that it returns None
> > is just a "coincidence" that happens to happen every time you tested
> > it (you can't prove by ignorance)
>
> I think in Python there's no notion of "void" return type. Deliberate
> choice to return None for functions that modify objects in place seems
> to be OK as long as it is used consistently and documented. Which is the
> case.

No, there is no need for "void" return type, what I meant is that
everything that's not said in the documentation should be assumed to
be an implementation detail, a method or a function that doesn't say
anything about its return type should be assumed to return an
implementation detail (which basically means: Don't rely on this). The
fact that list.append returns none is just a coincidence, you might
encounter another list.append that returns different thing some time
in the future, or the far future, or perhaps at the end of the
galaxy's life.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find string in file

2008-03-16 Thread Lie
On Mar 14, 8:25 pm, [EMAIL PROTECTED] wrote:
> Hi friends !!
>
> I'm neophite about python, my target is to create a programa that
> find  a specific string in text file.
> How can do it?
>
> Thanks
> fel

I'd recommend regular expression (import re) if the string you're
searching is in a complex format (like all strings that starts with a
dollar sign followed by an arbitrary number of numbers which might or
might not contain commas every three number).

If what you're searching is just simple queries (like searching where
"Hello" appeared in the text you'd better use the string modules. as
they're simpler to use and faster.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert int to float

2008-03-16 Thread Lie
On Mar 16, 4:43 am, Guido van Brakel <[EMAIL PROTECTED]> wrote:
> Hello
>
> I have this now:
>
> > def gem(a):
> >     g = sum(a) / len(a)
> >     return g
>
> > print gem([1,2,3,4])
> > print gem([1,10,100,1000])
> > print gem([1,-2,3,-4,5])
>
> It now gives a int, but i would like to see floats. How can integrate
> that into the function?
>
> Regards,
>
> --
> Guido van Brakel
> Life is like a box of chocolates, you never know what you're gonna get
> --

Python 2's division operator's default behavior is to do integer
division whenever all of its operands are integers/long and do float
division if any of them are float/decimal, in Python 3, this is going
to be changed so that division would always be float division and
while integer division would have its own operator "//".

You can change the default behavior of Python 2 by importing division
behavior from __future__ module (from __future__ import division), or
you could convert one of the operands to float ("float(a) / b" or "a /
float(b)").
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List mutation method gotcha - How well known?

2008-03-16 Thread Lie
On Mar 15, 1:01 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote:
> > No, there is no need for "void" return type, what I meant is that
> > everything that's not said in the documentation should be assumed to
> > be an implementation detail, a method or a function that doesn't say
> > anything about its return type should be assumed to return an
> > implementation detail (which basically means: Don't rely on this). The
> > fact that list.append returns none is just a coincidence, you might
> > encounter another list.append that returns different thing some time
> > in the future, or the far future, or perhaps at the end of the
> > galaxy's life.
>
> I expect functions with no documentation of what they return to return
> `None`.  Assuming they are documented at all, of course.  :-)
>
> It's like not writing a ``return`` statement in the code: there's always an
> implicit ``return None`` at the end of every function.

I personally won't to rely on it. Sometimes a return statement might
be documented, but not complete enough, like this:

def genericadd(a, b):
"""
Adds two number, returns the same as longadd if
either operands are long type and returns the same
as intadd if all operands are int type.

"""
if isinstance(a, long) or isinstance(b, long):
return longadd(a, b)
if isinstance(a, int) and isinstance(b, int):
return intadd(a, b)
return "Error"

This function is written badly on purpose to simulate what a less-than-
intelligent programmer might write, which is in no control of ours as
a class user.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-16 Thread Lie
On Mar 11, 4:15 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Mar 11, 3:19 am, [EMAIL PROTECTED] wrote:
>
> > The trick in the case of when you do not want to guess, or the choices
> > grow too much, is to ask the user to tell you in what format they want
> > it and format according to their wishes.
>
> > Neatly avoids too much guessing and isn't much extra to add.
>
> The plot is about understanding input, not formatting output.

And what he meant is simply to make an agreement with the user on how
he/she would format his/her input and to disallow input from formats
that haven't been agreed to avoid guessing. That is the cleanest and
most polite solution, although I'd suspect it would be considered less
user friendly by regular user although power user would be most happy
with that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this valid ?

2008-03-20 Thread Lie
On Mar 20, 4:18 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> by accident I typed a double value test,
> and to my surprise it seems to work.
> Is this valid ?
>
> a = 2
> b = 2
>
> a == b == 2
>
> thanks,
> Stef Mientki

a == b == 2
is equivalent to
a == b and b == 2
except that b is only evaluated once for the whole comparison
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dividing tuple elements with an int or float

2008-03-23 Thread Lie
On Mar 20, 1:06 pm, royG <[EMAIL PROTECTED]> wrote:
> hi
> i am trying to resize some images.First i'd read the size as a 2
> tuple  and then i want to divide it by 2 or 4 or 2.5 etc..
>
> suppose
> origsz=(400,300)
> i want to divide the origsize by 2.5 so i can resize to (160,120)

There are several ways to do what you wanted:

-
width = origsz[0] * scale
height = origsz[1] * scale
return width, height
-
width, height = origsz
return width * scale, height * scale
-
return origsz[0] * scale, origsz[1] * scale
-
# and an overly complex way of doing this
return tuple(x * scale for x in origsz)
-


> scale=2.5
> how can i get the newsz?
> obviously origsz/2.5 won't work  ..
> thanks
> RG

Aside: I think you're a bit confused about the semantic of scaling in
image resizing, when you want to halve the image size (e.g. 100x100 ->
50x50) you scale it by 0.5, and when you want to double the image size
(e.g. 100x100 -> 200x200) you scale it by 2. This operation is done by
multiplication, not division. (i.e. scaling a 400x300 images by 2.5
means upsizing the image into 1000x750)

On Mar 20, 9:28 pm, "Jerry Hill" <[EMAIL PROTECTED]> wrote:
(snip)
> That works fine for a 2-tuple, but might get unwieldy for larger
> tuples, or if you don't know the length until runtime.  A more general
> solution might use a generator expression, like this:
(snip)

I think since the semantic of origsz is well defined (width-height
pair of an image) it will always be a 2-tuple, anything other than 2-
tuple should either be discarded or raise an error (depending on
design choice).

P.S.: If you're sure that you want to use division, make sure to "from
__future__ import division" or convert the scaling factor into floats
or you'll most likely get the wrong result as Python defaults to
integer division (due to be changed in Python 3). And you should
remember that the resulting image size should also be (integer,
integer) since you can't have an image that's 100.2432x392.9875
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dividing tuple elements with an int or float

2008-03-23 Thread Lie
On Mar 22, 2:23 pm, [EMAIL PROTECTED] wrote:
> > Sane programmers don't write such semi-functional things (unless it
> > helps expressing the problem in certain domains).
> > I now think that deprecating map, lambda & Co. was a good thing after
> > all.
>
> If you write it that way the first time, you need therapy.  Actually,
> at this point, I (for one, personally) want to investigate 'certain
> domains'.  Tell me it's really bad at everything or what it's good
> at.  What can I respect about it?

If you (castiro..) write it your way, you'll surely win the Obfuscated
Python Code Contest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this doable

2008-03-23 Thread Lie
On Mar 22, 1:11 am, MRAB <[EMAIL PROTECTED]> wrote:
> On Mar 21, 11:48 am, fkallgren <[EMAIL PROTECTED]> wrote:> Hi.
>
> > I have a little problem. I have a script that is in the scheduler
> > (win32). But every now and then I update this script and I dont want
> > to go to every computer and update it. So now I want the program to 1)
> > check for new version of the script, 2) if there is a new version,
> > copy that verision from server to local drive, 3) shutdown the program
> > and start it up again as the new version.
>
> > The problem is that I can't run this script directly from server so it
> > have to run it locally.
>
> > Anyone having any bright ideas??
>
> The script could just check to see if the version on the server is
> more recent and if it is then copy it over the local one, start the
> local one, and then quit.
>
> Python compiles the script to bytecode and then interprets the
> bytecode, so when the script is being run the .py or .pyw source
> itself isn't being used and can be overwritten. I've tried the
> following on Windows XP and it works:
>
> (snip)

Even if the .py and .pyw is being locked, you could always use a
helper script that calls the main program if there is no update. This
way, the main program is never called directly, only by the updater
script. Such implementation is trivial.

# updater script
# when you're running your program, you
# call this script instead of the real
# main program
if needupdate():
update()
else:
callmainprogram()

# main program
# this script should never be called
# directly, only by the updater program
# (well, except perhaps on development stage)
def checkupdate():
if needupate():
callupdatescript()
terminateself() # possibly saving state, etc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type conversion

2009-01-10 Thread Lie
On Jan 3, 10:23 am, r  wrote:
> On Jan 2, 7:46 pm, Steven D'Aprano  
> wrote:
>
> ...incessant rambling about a news reader , 101 excuses for butting
> into a thread
> [snip]

... public display of ignorance of newsgroup ethics, 101 excuses for
not knowing proper terminologies.

> Throw your newsreader in the garbage and use Google groups, less
> headache, more filling!
>

Really? I found Google Groups lacking for many thing. Google Groups'
only advantage is being browser-based.

> No need to worry about
> "hidden headers" And you may even get a star or 2 :)

Don't you realize that even Google Groups handles those hidden headers
too. And that the hidden headers aren't really hidden, even in Google
Groups.

> > If people are ignoring a thread, they won't even see your post even though 
> > you have changed the subject line.
>
> Yea NO $#Y, that makes a lot of sense, if i am ignoring something i
> course i will not see it!
> OK, Steven so you did not go off topic you simply high-jacked this
> thread. I get it now :)

"Yea NO $#Y", that doesn't make sense. Yea or NO? or $#Y?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better algorithm?

2009-01-13 Thread Lie
On Jan 3, 4:38 am, mr  wrote:
> As has been noted, the best is to fix the input to be regular-3-
> tuples. For the fun of it, here's another variation of a solution:
>


Yet another solution:

for i in l:
k, u, v = i[0], None if len(i) == 2 else i[1], i[-1]

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


Re: Is there a better algorithm?

2009-01-13 Thread Lie
On Jan 3, 11:55 am, Kottiyath  wrote:
> On Jan 3, 2:38 am, mr  wrote:
>

> It is a code to post some data to HTML server.
> Even though usually the POST values are of type(name, value), if file
> transfer is involved, then POST values change to (name, filename,
> value).
> My view was that since filename is a rare occurance and doesnt make
> sense in a usual POST, I had not kept it as a full 3 tuple.
> Since so many programmers (that too much more capable than me) are
> suggesting that it is code smell, I am reviewing my decision.

Is it possible to change (name, filename, value) into (name, value,
filename) instead?

In most cases optional arguments should be last. There are some very
exceptional case, where early optional argument might be better, like
python's range, which type signature is: [[start,] stop[, step]] (i.e.
with one argument, it is assigned to stop, instead of start)
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-15 Thread Lie
On Jan 5, 9:03 am, Derek Martin  wrote:
> On Sat, Jan 03, 2009 at 10:15:51AM +, Marc 'BlackJack' Rintsch wrote:
> > On Fri, 02 Jan 2009 04:39:15 -0600, Derek Martin wrote:
>
> > > On Tue, Dec 30, 2008 at 02:21:29PM +, John O'Hagan wrote:
> > > What the Python community often overlooks, when this discussion again
> > > rears its ugly head (as it seems to every other hour or so), is that its
> > > assignment model is BIZARRE, as in it's conceptually different from
> > > virtually all other languages substantially taught in undergraduate
> > > computer science programs.
>
> > What's the difference between Python and Java or C# here!?  Or are they
> > also "BIZARRE"!?
>
> I am happily ignorant of C#.  As for Java, take the following code:
>
>   a = 6;
>   a = 5;
>
> In Python, when you execute the equivalent code, it causes two
> different objects to spring into existence, the first of which may be
> cleaned up by the GC (except that since we're using small integers,
> that's not likely to happen).  Unless I'm misinformed (which is very
> possible, my experience with Java has been extremely limited) in Java
> that's not the case...  the storage is allocated to the name a when
> you execute its declaration, and the *same storage* is reused upon
> subsequent assignment.
>
> That behaves exactly like named bins.
>
> > > And for that matter, it's pretty unintuitive generally.
>
> > Names and objects are quite "natural" IMHO.  There are many real world
> > objects which we attach one or more names to, or refer to in sequences
> > like "please give me the third book on that shelve" (``shelve[2]``).
>
> Indeed, but the way we assign names to them does not behave as it does
> in Python.  Nor does Python's assignment work like it does in algebra,
> or anywhere else the Python student is particularly likely to have
> seen variable assignment before encountering it in Python.  Let's
> define intuitive, shall we?  From dictionary.com (choosing the
> definition which most easily makes my point):
>
>   intuitive: adj.  capable of being perceived or known by intuition.
>
> I'm going to go out on a limb and assert that there's NO POSSIBLE WAY
> a student could intuit Python's variable assignment behavior, having
> never been exposed to that same behavior prior.  It needs to be
> taught.

Which limb would you like to go with?

> > > That is, in what I'll call "normal" computer languages, a variable name
> > > is thought of as the address of a bin where some data is stored, and the
> > > name is inexorably tied to that bin.
>
> > You just call that "normal" or "intuitive" because that's what you
> > learned first.
>
> In a sense, yes... but isn't that what intuition really is?  You can
> figure something out whithout being told how it works...  That's
> either because it's immediately obvious from observing it, or it
> behaves like something you've seen before.  That is what intitive is.

No. You've just said it yourself, something is intuitive if "it
behaves like something you've seen before". People have different
experience, people deeply involved in mathematics would see "named
bin" is the obvious thing to go, however commoners (including
mathematician) will have different say: "Derek is the name of a human
object" instead of "Derek is a specific collection of atoms that
resembles human".

This is also why python community tend to avoid the use of "variable",
because python's name doesn't behave like variables in mathematics, it
behaves like "name". (heck, one would argue that even "variable" in
programming is not exactly the same as "variable" in mathematic
either)

> > I think the "bin model" is more complex because you don't just have a
> > name and an object but always that indirection of the "bin".
>
> I cheerfully disagree. :)  "Named bins" is essentially how algebra
> works, and how several generations of computer languages, not to
> mention the actual machine language those generated, behaved, before
> the current crop.  Those interpretations came first, because, much as
> in the evolution of any other science, that was the model which was
> most intuitive or easily explained.

No, it is neither the most intuitive nor easily explained, but indeed
it is the simplest to implement as humans at that time have limited
capability to design chips. In the early days, ease of use is not a
priority, simplicity is.

> But you need not take my word for it.  Simply read the archives and
> see for yourself how much confusion this has caused on this list.
> [Please include the closely related behavior of parameter passing in
> your search.]

The first time I used python, I didn't have any idea how the object
model works, and I don't have experience in similar programming
concept nor was python my first language, yet I have no difficulty in
understanding why things goes like it is. For me, at least, python's
object model is intuitive (do you remember about the limb?).
--
http://mail.python.org/mailman/listinfo/python-list


Re: why o/p is different ???

2009-01-16 Thread Lie
On Jan 15, 1:34 pm, asit  wrote:
> I recently faced a peculiar o/p.
>
> My objective is to remove the command name(my script name) from
> sys.argv[0].
> I coded like this
>
> import urllib
> import sys
>
> print "\n\n\t\tlipun4u[at]gmail[dot]com"
> print "\t\t"
>
> apppath = sys.argv[0].split("/")
> appname = apppath[len(apppath)-1]
> print appname
>
> if len(sys.argv) not in [2,3]:
>     print "Usage : " + appname + "  [options]"
>     print "e.g. : " + appname + "www.google.com--verbose"
>     print "\n\t[option]"
>     print "\t\t--verbose/-V for verbose output"
>     print "\t\t-r for recursive scan"
>     sys.exit(1)
>
> site = appname.replace("http://","";).rsplit("/",1)[0]
> site = "http://"; + site.lower()
> print site
>
> It showed the required o/p in the IDLE
> here is the o/p
>
>                 lipun4u[at]gmail[dot]com
>                 
> linkscan.py
> Usage : linkscan.py  [options]
> e.g. : linkscan.pywww.google.com--verbose
>
>         [option]
>                 --verbose/-V for verbose output
>                 -r for recursive scan
>
> Traceback (most recent call last):
>   File "I:/Python26/linkscan.py", line 18, in 
>     sys.exit(1)
> SystemExit: 1
>
> But in command prompt the o/p is still faulty
>
>                 lipun4u[at]gmail[dot]com
>                 
> I:\Python26\linkscan.py
> Usage : I:\Python26\linkscan.py  [options]
> e.g. : I:\Python26\linkscan.pywww.google.com--verbose
>
>         [option]
>                 --verbose/-V for verbose output
>                 -r for recursive scan
>
> I:\Python26>
>
> regards
> asit dhal

Of course the pragmatic approach is just to include

appname = 'linkscan.py'

at the top of the document.

I agree apppath might change (because you copied the program to
different places, different bin directory on different machine), but
there is no reason linkscan.py should change. And if you have to
change the invoking name, sometimes it might be more useful for users
to know the REAL name of the program (probably the user friendly
version, e.g. "Link Scanner" or "Link Scanner 1.0"), instead of the
name of the script it is run from (without the apppath). It is trivial
for human user to guess where the script is located and what the
appname is from the full apppath (path+name)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Import without executing module

2009-02-03 Thread Lie
On Feb 3, 1:37 pm, Ray  wrote:
> I'll enclose the top-level commands with the if statement above...its
> just a minor change, but it seems unavoidable.
>
> Thanks again!
>
> Ray

If you really don't want the file to be changed, you could (depends on
the module) use the module as a subprocess. The ideal solution is for
the module to have an if __name__ == '__main__': to determine whether
it is being used as a module or a standalone program though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3D CAD -- need collaborators, or just brave souls :)

2009-02-19 Thread Lie
On Feb 18, 8:02 pm, r  wrote:
> Hello Josh,
> Blender is a lost cause. It is a powerful app but the UI is horrible.
> Even the Blender folks admit only a complete rewrite could solve the
> major flaws that plague the design. So maybe i could salvage 
> some code
> but for what i have in mind, Blender will look like a piece of
> software from the middle ages. And i am absolutly only looking to do
> this in 3D, 2D is boring.

Blender's UI is designed for effective and efficient 3D workflow, not
for low learning curve.

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


Re: end of print = lower productivity ?

2008-11-29 Thread Lie
On Nov 25, 11:44 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > p = print
> > p("f")
> >> Voila, 4 keystrokes saved :-)
>
> > When I write "print", it is both effortless and instantaneous : my
> > hands do not move, a wave goes through my fingers, it all happens in a
> > tenth of a second.
>
> > Contrast this with what one has to go through to catch the SHIFT key,
> > and then the "(" : move the left hand, press SHIFT, move the right
> > hand, aim "(", press, miss, press again. Same thing at the end of the
> > function call.
>
> > I know it sounds ridiculous, but it does *impair* my debugging
> > productivity. Taylor would agree.
>
> It's not so much "rediculous" as a failure of your editor to
> assist you.  In Vim (my editor-of-choice), I'd do something like
>
>    :iab print print()

seriously, I don't think anyone in Windows uses vim and there are
quite a lot of Windows Python user. Since when is python becoming
exclusive community for Linux/Unix-like/Cygwin users that Windows
users who have nothing but Notepad is put aside.

Python has long "advertised" itself as a language that is better off
without an IDE, i.e. encourages plain text editor over IDE. By
introducing print-as-function, doing a simple print does requires you
to use more shift-key than before, but having to configure your text
editor to substitute print to print() is just as nice and disgusting
as using an IDE, I, for instance, hates when my text editors tries to
be smarter than me. A practical example is Scribes Text Editor, which
"features" auto-pair completion, which drives me mad for it trying to
close tags where I only want open tags. I never used that "smart"
editor again ever since (even if I know I can turn that off easily).

> and that's the end of it.  Or you could be even lazier if you
> don't name your variables "p":
>
>    :iab p print()
>
> in which case you can just type
>
>    p"
>
> and it automatically populates with
>
>    print(")
>
> with the cursor after the double-quote ready for you to type the
> string's contents.  Net gain:  5 characters in old-Python and 6
> characters in new-Python ;-)

Is that supposed to be a joke?

> Any editor environment worth its salt should allow you to do
> things like this (insert abreviated text or template text).  The
> gains made from making "print" a function far outweigh niggling
> things that simple editor-tweaks can overcome.
>
> -tkc

In general, I don't hate the print-as-function for having to type open
and closing parens. I am, in fact, indifferent to that change. But
I've got to say that I HATE "smart-ass" (read: less than stupid)
editors. I'm sure when my dislike for "smart" editors is coupled with
someone's else's hate for print-as-function, s/he would consider end
of print-as-statement as lowering productivity.
--
http://mail.python.org/mailman/listinfo/python-list


Re: end of print = lower productivity ?

2008-11-29 Thread Lie
On Nov 26, 3:08 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
>
>
> > On Nov 25, 5:05 pm, peter <[EMAIL PROTECTED]> wrote:
> >> BUT you now can do
>
> > p = print
> > p("f")
> >> Voila, 4 keystrokes saved :-)
>
> > All right. Let's talk about that.
>
> > When I write "print", it is both effortless and instantaneous : my
> > hands do not move, a wave goes through my fingers, it all happens in a
> > tenth of a second.
>
> > Contrast this with what one has to go through to catch the SHIFT key,
> > and then the "(" : move the left hand, press SHIFT, move the right
> > hand, aim "(", press, miss, press again. Same thing at the end of the
> > function call.
>
> > I know it sounds ridiculous, but it does *impair* my debugging
> > productivity. Taylor would agree.
>
> If the relative difference between pressing space & ( impairs your
> absolute debugging productivity, it pretty much follows that the latter
> must be very low for such a minimal overhead to make such a difference.
>
> Try learning touchtype. Might increase your debugging, programming &
> writing productivity manyfold.

It doesn't work. I'm already a touch typist. But my touch typing
rhythm is disturbed when there is a pair characters, as my internal
pair-completion would do something like this: ()""string.
I am a perfectionists, I hate having unclosed pair characters (though
I hate editors that auto-complete pairs even more, as it always
mistook my attempt to place open tags that already have closing tags
as need to be auto-closed). I am also a control-freak, as you might
have guessed. And I don't like patchwork, e.g. correcting the editor's
mistaken attempt, I'd rather do the whole thing manually than having
it done automatically but sometimes need manual intervention, if
something is automatized, do it completely, else don't.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ?

2008-11-29 Thread Lie
On Nov 26, 1:45 pm, "Barak, Ron" <[EMAIL PROTECTED]> wrote:
> Hi Pythonistas,
>
> I read diaz's comments with interest, but - in my current configuration, I'm 
> unable to use pdb.
>
> I'm developing on cygwin and use wxPython.
> Consequently, I cannot use native cygwin Python, but my Python is actually 
> the Windows XP Python (i.e.,  /cygdrive/c/Python25/python.exe).
> This means that pdb (and, for that matter any Python shell (like IDLE)) gets 
> stuck upon invocation.
>
> I was wandering: is anybody able to use native Python on cygwin, or 
> alternately, to use Windows Python under cygwin in IDLE/pdb ?
>
> Thanks,
> Ron.
>
> -Original Message-
> From: Diez B. Roggisch [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, November 25, 2008 17:54
> To: [EMAIL PROTECTED]
> Subject: Re: end of print = lower productivity ?
>
> [EMAIL PROTECTED] wrote:
>
> > I want my productivity back.
>
> > In Python 2.x, I could easily write things like -- print "f" / print
> > "add" / print "done" -- to a lot of different places in my code, which
> >...
> > debugging tool it was.
>
> I used to use print a lot. Once I found
>
> import pdb; pdb.set_trace()
>
> I massively lost interest in it. And gained *much* more debugging 
> power/productivity.
>
> Also, using logging instead of print allows you to keep the output producing 
> statements in your code, while turning them on only if things get fishy.
>
> Diez

A joke indeed.

pdb and logging is too much for beginners, which most likely does not
yet understand the workings of the debugger and logger (and pdb's many
quirks). Don't forget that we're all beginners once. Python's learning
curve shouldn't raise with time, it should get lower so more people
can join in the board.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any project whose patches are all available?

2008-11-30 Thread Lie
On Nov 28, 1:57 pm, ZelluX <[EMAIL PROTECTED]> wrote:
> Hi, all
>
> I want to write a version-tracking tool for Python projects, and need
> some sample projects whose even smallest modifications can be
> downloaded from the internet.
>
> Could you recommend some to me?
> Thanks for your reply

When the project matures, why not have the project itself hosted on
the version tracking tool?
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-11-30 Thread Lie
On Nov 28, 12:28 pm, r <[EMAIL PROTECTED]> wrote:
> To think...that I would preach freedom to the slaves and be lynched
> for it...IS MADNESS!
>
> Not one vote for Python, not a care. I think everyone here should look
> deep within their self and realize the damage that has been done
> today! I hope Guido's eyes never see this thread, for he may lose all
> hope in humanity. He only spent the last 18 years of his life pursuing
> this thing called Python. Maybe 1,2,3, years from now someone will see
> this thread and post a vote for Python. Maybe as simple as "I will
> fight for Python" , "I am not scared to go up against the status quo".
> For that day will be a glorious day. That day shall be Python Day!
> I will never give UP!

+1 for python to be used more
+1 for python to be used as scripting language on another app
+1 for python to be used as scripting langauge on a Google program
+1 for python to be used as scripting language on Sketchup
-4 for any sort of fanboyism
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >