What is this syntax ?

2011-06-19 Thread candide

With Python 2.7 :

>>> x="foo"
>>> print '"'+x+'"'
"foo"
>>>


What is this curious syntax on line 2 ? Where is it documented ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is this syntax ?

2011-06-19 Thread candide

OK,  thanks for your explanation, it was just stringisation !


I erroneously focused on

+x+

as a kind of placeholder unknown to me, instead of left and right 
concatenations ;)


It would be more readable for me if it were edited

>>> print '"' + x + '"' # better spacing
"foo"
>>>

or with string formatting :

>>> x="foo"
>>> print '"%s"' %x
"foo"
>>>

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


Extracting subsequences composed of the same character

2011-03-31 Thread candide

Suppose you have a string, for instance

"pyyythhooonnn ---> "

and you search for the subquences composed of the same character, here 
you get :


'yyy', 'hh', 'ooo', 'nnn', '---', ''

It's not difficult to write a Python code that solves the problem, for 
instance :


def f(text):
ch=text
r=[]
if not text:
return r
else:
x=ch[0]
i=0
for c in ch:
if c!=x:
if i>1:
r+=[x*i]
x=c
i=1
else:
i+=1
return r+(i>1)*[i*x]

print f("pyyythhooonnn ---> ")


I should confess that this code is rather cumbersome so I was looking 
for an alternative. I imagine that a regular expressions approach could 
provide a better method. Does a such code exist ?  Note that the string 
is not restricted to the ascii charset.

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


Re: Extracting subsequences composed of the same character

2011-04-01 Thread candide
Thanks, yours responses  gave me the opportunity to understand the 
"backreference" feature, it was not clear in spite of my intensive study 
of the well known RE howto manual.

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


Extracting repeated words

2011-04-01 Thread candide

Another question relative to regular expressions.

How to extract all word duplicates in a given text by use of regular 
expression methods ?  To make the question concrete, if the text is


--
Now is better than never.
Although never is often better than *right* now.
--

duplicates are :


better is now than never


Some code can solve the question, for instance

# --
import re

regexp=r"\w+"

c=re.compile(regexp, re.IGNORECASE)

text="""
Now is better than never.
Although never is often better than *right* now."""

z=[s.lower() for s in c.findall(text)]

for d in set([s for s in z if z.count(s)>1]):
print d,
# --

but I'm in search of "plain" re code.



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


Extracting "true" words

2011-04-01 Thread candide
Back again with my study of regular expressions ;) There exists a 
special character allowing alphanumeric extraction, the special 
character \w (BTW, what the letter 'w' refers to?). But this feature 
doesn't permit to extract true words; by "true" I mean word composed 
only of _alphabetic_ letters (not digit nor underscore).



So I was wondering what is the pattern to extract (or to match) _true_ 
words ? Of course, I don't restrict myself to the ascii universe so that 
the pattern [a-zA-Z]+ doesn't meet my needs.

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


Alphabetics respect to a given locale

2011-04-01 Thread candide
How to retrieve the list of all characters defined as alphabetic for the 
current locale  ?

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


Re: Extracting repeated words

2011-04-02 Thread candide

Le 02/04/2011 00:42, Ian Kelly a écrit :


You could use a look-ahead assertion with a captured group:


regexp = r'\b(?P\w+)\b(?=.+\b(?P=dup)\b)'
c = re.compile(regexp, re.IGNORECASE | re.DOTALL)
c.findall(text)


It works fine, lookahead assertions in action is what exatly i was 
looking for, many  thanks.

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


Re: Alphabetics respect to a given locale

2011-04-02 Thread candide

Le 01/04/2011 22:55, candide a écrit :

How to retrieve the list of all characters defined as alphabetic for the
current locale ?



Thanks for the responses. Alas, neither solution works.

Under Ubuntu :

# --
import string
import locale

print locale.getdefaultlocale()
print locale.getpreferredencoding()

locale.setlocale(locale.LC_ALL, "")

print string.letters

letter_class = u"[" + u"".join(unichr(c) for c in range(0x1) if
unichr(c).isalpha()) + u"]"

#print letter_class
# --

prints the following :


('fr_FR', 'UTF8')
UTF-8
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz


I commented out the letter_class printing for outputing a flood of 
characters not belonging to the usual french character set.



More or less the same problem under Windows, for instance, 
string.letters gives the "latin capital letter eth" as an analphabetic 
character (this is not the case, we never use this letter in true french 
words).




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


Re: Extracting "true" words

2011-04-02 Thread candide

Le 02/04/2011 01:10, Chris Rebert a écrit :


"Word" presumably/intuitively; hence the non-standard "[:word:]"
POSIX-like character class alias for \w in some environments.


OK



Are you intentionally excluding CJK ideographs (as not "letters"/alphabetic)?


Yes, CJK ideographs don't belong to the locale I'm working with ;)



And what of hyphenated terms (e.g. "re-lock")?



I'm interested only with ascii letters and ascii letters with diacritics


Thanks for your response.

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


Argument of the bool function

2011-04-08 Thread candide
About the standard function bool(), Python's official documentation 
tells us the following :


bool([x])
Convert a value to a Boolean, using the standard truth testing procedure.


In this context, what exactly a "value" is referring to ?


For instance,


>>> x=42
>>> bool(x=5)
True
>>>


but _expression_ :

x=42


has no value.






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


Re: Argument of the bool function

2011-04-08 Thread candide

Le 08/04/2011 18:43, Ian Kelly a écrit :


"x=42" is an assignment statement, not an expression.


Right, I was confounding with C ;)

In fact, respect to this question, the documentation makes things 
unambiguous :



-
In contrast to many other languages, not all language constructs are 
expressions. There are also statements which cannot be used as 
expressions, such as print or if. Assignments are also statements, not 
expressions.

-







In "bool(x=5)", "x=5" is also not an expression.  It's passing the
expression "5" in as the parameter x, using a keyword argument.



You are probably right but how do you deduce this brilliant 
interpretation from the wording given in the documentation ?





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


Re: Argument of the bool function

2011-04-08 Thread candide

Le 09/04/2011 00:03, Ethan Furman a écrit :


 > bool([x])
 > Convert a value to a Boolean, using the standard truth testing
 > procedure.
 >

As you can see, the parameter name is 'x'.



OK, your response is clarifying my point ;)


I didn't realize that in the bool([x]) syntax, identifier x refers to a 
"genuine" argument [I was considering x as referring to a "generic" 
object having a boolean value].



Nevertheless, compare with the definition the doc provides for the 
builtin function dir():


dir([object])
[definition omited, just observe the declaration syntax]

Now, lets make a try

>>> dir(object="Explicit is better than implicit")
Traceback (most recent call last):
  File "", line 1, in 
TypeError: dir() takes no keyword arguments
>>>

Not very meaningful, isn't it ?



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


Re: Argument of the bool function

2011-04-09 Thread candide

Le 10/04/2011 01:22, Robert Kern a écrit :


No one is saying that every instance of "foo([arg])" in the docs means
that the given argument is named such that it is available for keyword
arguments. What people are saying is that for bool(), *that happens to
be the case*.




what a piece of luck! ;)
--
http://mail.python.org/mailman/listinfo/python-list


Retrieving Python Keywords

2011-04-09 Thread candide
Python is very good at introspection, so I was wondering if Python (2.7) 
provides any feature to retrieve the list of its keywords (and, as, 
assert, break, ...).

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


Re: Retrieving Python Keywords

2011-04-10 Thread candide

Le 10/04/2011 04:09, John Connor a écrit :

Actually this is all it takes:
import keywords
print keywords.kwlist



>>> import keywords
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named keywords
>>>


so I considered first  it was a joke ! ;) In fact the import doesn't 
need plural, and... Python is very very introspective ;)



Thanks and thanks to Steven too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving Python Keywords

2011-04-10 Thread candide

Le 10/04/2011 04:01, Terry Reedy a écrit :


Yes. (Look in the manuals,



I did : my main reference book is the Martelli's /Python in a Nutshell/ 
and the index doesn't refer to the keyword import





or try the obvious imports ;-)



The only obvious I saw was sys module.

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


Re: Argument of the bool function

2011-04-10 Thread candide

Le 08/04/2011 18:41, Benjamin Kaplan a écrit :


bool(x=5) is just passing the value 5 as the argument "x" to the function.




Anyway, passing x as a keyword argument to the bool function appears to 
be very rare : i did a regexp search for about 3 source-code Python 
files (among them official Python source-code, Django, Sphinx, Eric 
source-code and many more sources of valuable Python code) and I didn't 
find even one.

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


Re: Python IDE/text-editor

2011-04-16 Thread candide

Le 16/04/2011 15:50, Adam Tauno Williams a écrit :


gedit provides a Python interpreter/console 'embedded' in the GUI
(provided the plugin is enabled).




I agree, cf. this screenshot  :

http://i52.tinypic.com/snj7a0.jpg

but i'm not sure gedit run easily under Windows.


Kate editor has the same feature.
--
http://mail.python.org/mailman/listinfo/python-list


Equivalent code to the bool() built-in function

2011-04-16 Thread candide

Consider the following code :

# --
def bool_equivalent(x):
return True if x else False


# testing ...

def foo(x):
return 10*x

class C:
pass

for x in [42, ("my","baby"), "baobab", max, foo, C] + [None, 0, "", [], 
{},()]:

print bool(x)==bool_equivalent(x)
# --


Is the bool_equivalent() function really equivalent to the bool() 
built-in function ?




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


Re: Equivalent code to the bool() built-in function

2011-04-16 Thread candide

Le 16/04/2011 23:38, Ben Finney a écrit :


So the answer to the OP's question is no: the function isn't equivalent
to the type,



Can bool() type and bool_equivalent() function return different values ?



because the OP's ‘bool_equivalent’ function necessarily
uses the built-in ‘bool’ type, while the reverse is not true.



The documentation doesn't seem to state it performs this call. I'm 
referring to

-- §5.10 Boolean operations in Document Reference Python 2.7
-- bool()'s description in Library Reference
-- §5.1 Truth Value Testing in Library Reference




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


Re: Equivalent code to the bool() built-in function

2011-04-16 Thread candide

Le 16/04/2011 23:13, Ben Finney a écrit :


The ‘bool’ built-in is not a function.

 >>>  type(bool)
 




Oops, unfortunate confusion!! but built-in types and built-in functions 
are sometimes so similar from the user's point of view ;)


All the same, you can notice that the official documentation describes 
bool() as a built-in function, cf. 
http://docs.python.org/library/functions.html

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


Re: Equivalent code to the bool() built-in function

2011-04-17 Thread candide

Le 17/04/2011 04:39, Ben Finney a écrit :



Why do you need to know? (I should have asked that question earlier.)




First because I was doubting the true interest of the bool() type. In 
fact, it appears that it's _semantically_ a shortcut for
True if x else False. I could't imagine a builtin function having a so 
trivial implementation. Compare with float() or int(). I also try to 
consider how essential the bool() type is. Again compare with int() or 
str() types.


In the orther hand, I'm builting a sort of documentation for learning 
Python. In order to spell out the purposes of the bool() type, I guessed 
that giving an equivalence code could help.

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


Re: Equivalent code to the bool() built-in function

2011-04-17 Thread candide

Le 17/04/2011 11:46, Ben Finney a écrit :
> candide  writes:
>
>> First because I was doubting the true interest of the bool() type. In
>> fact, it appears that it's _semantically_ a shortcut for
>> True if x else False.
>
> That bends my brain. Both ‘True’ and ‘False’ are instances of the ‘bool’
> type. So of course the ‘bool’ constructor will return them.

A user of the Python programming language can sensibly handle boolean 
values and write a lot of good code and at the same time completely 
ignore all the object oriented stuff behind the True and False instances.


> What is the
> “shortcut” you refer to?

bool(x) is nothing more than a shortcut for the following expression : 
True if x else False.
Compare for instance with the str() type whose implementation is far 
more complicated. When learning Python, you early and communly use str() 
type but use sparingly the bool() type. On the other hand, the learner 
cannot replace himself the service str() provide (hard to write an 
equivalent code). It's not the case for the bool() type : True if foo 
else False.




>
> Remember, the point of a type is to encapsulate both behaviour and an
> exclusive domain of possible values. The Boolean type is particularly
> simple, so I don't see why you would be surprised that the behaviour of
> the ‘bool’ constructor is simple – that's a feature of that type.
>

In fact, bool() is so simple that at first glance I didn't see any use 
for it.



>> In the orther hand, I'm builting a sort of documentation for learning
>> Python.
>
> Something different fromhttp://docs.python.org/tutorial/>.
>


More : something _opposite_ to the official Python tutorial ;) I found 
this tutorial very unfriendly and very unsmooth, poorly structured, 
providing overloaded examples, unable to distinguish essential from 
incidental, full of bad explanations, etc. OOP presentation is terribly 
verbose and speculative, chapter on error handling is very hard to 
follow if you are not aware of the exception mechanism, etc


This is not a surprise, as the abstract explains :

"This tutorial does not attempt to be comprehensive and cover every 
single feature, or even every commonly used feature."


The nice graphical aspect of the tutorial (thanks to Sphinx) doesn't 
compensate the many weaknesses of the content.


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


Re: Equivalent code to the bool() built-in function

2011-04-18 Thread candide

Le 18/04/2011 10:33, Raymond Hettinger a écrit :


# --
def bool_equivalent(x):
  return True if x else False


It's faster to write:

def bool_equivalent(x):
 return not not x




faster and ... smarter ;)
--
http://mail.python.org/mailman/listinfo/python-list


What’s wrong with scientific Python?

2014-01-19 Thread candide


http://cyrille.rossant.net/whats-wrong-with-scientific-python/


Any comments ?
-- 
https://mail.python.org/mailman/listinfo/python-list


What the Pythons docs means by "container" ?

2015-02-17 Thread candide
Official Python documentation very frequently invokes a mysterious *container* 
data structure. The PLR manual explains :

--
Some objects contain references to other objects; these are called containers.
--

So containers contain : what a great definition!

To be more precise, the "container" wording suggests a data structure _storing_ 
items somewhere and that the number of items in the container has a memory 
footprint. This is exacly the "container" definition given by the ISO C++ 
standard (cf.  
http://www.open-std.org/jtc1/sc22/open/n2356/lib-containers.html) :

--
Containers are objects that store other objects.
--

So I was considering a Python range object NOT being a container: indeed, 
range(10**6) does NOT store 10**6 integers and range(10**6) has a small memory 
footprint in the contrary to the associated list :

--
>>> from sys import getsizeof
>>> r = range(10**6)
>>> L = list(r)
>>> getsizeof(r)
24
>>> getsizeof(L)
4500056
>>> 
--

Then, mining the official docs, I realized that the collections module provides 
an ABC Container class allowing you to know if a given object is a container or 
not. And what a surprise, a range object IS a container !

--
>>> from collections import Container
>>> r = range(10**6)
>>> isinstance(r, Container)
>>> 
True

>>>
--

So, what documentation means by the generic term of "container"? 

I agree with the existence of built-in containers (list, dict and the like) and 
the existence of special containers provided by the collections module (most of 
them inheriting from a built-in container) but I can't find a precise 
definition explaining what is a "container object" or a "container type". 

The docs at :

https://docs.python.org/3.2/reference/datamodel.html#object.__contains__

explains that a container is an object compatible with the membership test (in 
and not in operators). So a file is a container ? recall a file supports the in 
operator :

--
$ touch my_test.txt
$ python3.2
Python 3.2.3 (default, Feb 28 2014, 00:22:33) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 42 in open("my_test.txt")
False
>>> from collections import Container
>>> isinstance(open("my_test.txt"), Container)
False
>>> 
--




Reference of interest :

http://blog.wachowicz.eu/?p=132
http://stackoverflow.com/questions/11575925/what-exactly-are-containers-in-python-and-what-are-all-the-python-container

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


Re: What the Pythons docs means by "container" ?

2015-02-17 Thread candide
> 
> Shrug. It is a useful descriptive term when you want to talk about things. You

Python Language Referenceb (PLR) is expected to give formal and acurate 
definition, not "descriptive term to talk about things".

> might keep in mind that a "container"'s _primary_ purpose is usually its 
> containing function. So a list. But not so some arbitrary object, even though 

"containing function" ? Does PLR document this "containing function"?


> most objects have references to other objects.

have or contain ;)  ? 


 
> Duck typing again: this bases the term on behaviour, not memory use.

Again this is undocumented. Compare with the definition of duck-typed 
iterators, cf. https://docs.python.org/3.2/library/stdtypes.html#iterator-types

On the other hand, recall that the new behavior of range since Python 3 is 
motivated by memory considerations, quoted from the doc : 




The advantage of the range type over a regular list or tuple is that a range 
object will always take the same (small) amount of memory, no matter the size 
of the range it represents (as it only stores the start, stop and step values, 
calculating individual items and subranges as needed).



> Neither of these things has a .__contains__ method; the "in" operator falls 
> back to iteration if there is no .__contains__.


The documentation is fuzzy and inconsistant here: containers are supposed to 
implement the membership test, dixit the doc. 


> 
> A container usually lets you test "in" in a nondestructive/nonconsuming

"usually" ? I need something more acurate ;)


> fashion. An iterable can be "in"ed, but it will be consumed. So iterables are 
> not, of themselves, containers.

First this is undocumented. Second, range objects are considered as iterable by 
the doc. And you are telling us that an iterable is not a container. And range 
has a __contains__ method.

> 
> So, range? A range object knows its bounds and state; it can answer "in" 
> without consuming the range iteration, so it is effectively a container.

Again, this no-consuming feature is completely undocumented. And unconvincing: 
do you regard a linked list as not being a container ?

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


Re: What the Pythons docs means by "container" ?

2015-02-17 Thread candide
Le mercredi 18 février 2015 01:50:16 UTC+1, Chris Angelico a écrit :

> 
> So, what's a container? It's a thing that you put other objects into.

I agree with this approach. The important point to consider here is the last 
word in your definition : "into". There is the container and there is the 
content (the objects into). The so-called built-in containers (list, string, 
etc) are in conformance with this view. Now, regarding a range object as a 
container disagrees completely with the definition given in the PLR : there is 
no contents and hence there is no container. For instance, range(10**6) doesn't 
hold any kind of object, there are no reference to the int objects 0, 1, 2, ... 
As the range's docstring explains, range returns a VIRTUAL sequence.
-- 
https://mail.python.org/mailman/listinfo/python-list


Ternary operator associativity

2014-03-06 Thread candide
According to the official documentation, the ternary operator has left-to-right 
associativity :

---
Operators in the same box group left to right (except for comparisons, 
including tests, which all have the same precedence and chain from left to 
right -- see section Comparisons -- and exponentiation, which groups from right 
to left).
---


Nevertheless, the ternary operator grouping seems to be from right to left, 
compare :


>>> p = 0 if 1 else 0 if 0 else 1
>>> p
0
>>> left_to_right = (0 if 1 else 0) if 0 else 1
>>> right_to_left = 0 if 1 else (0 if 0 else 1)
>>> p == left_to_right
False
>>> p == right_to_left
True
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


print function and unwanted trailing space

2013-08-31 Thread candide


What is the equivalent in Python 3 to the following Python 2 code:

# -
for i in range(5):
print i,
# -

?

Be careful that the above code doesn't add a trailing space after the 
last number in the list, hence the following Python 3 code isn't 
strictly equivalent:



# -
for i in range(5):
print(i, end=' ')   # <- The last ' ' is unwanted
print()
# -
--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 10:43, Andreas Perstinger a écrit :

> How about
>
>  >>> print(" ".join(str(i) for i in range(5)))
> 0 1 2 3 4
>


Thanks for your answer. The output is stricly the same but the code 
doesn't suit my needs :


1) I'm porting to Python 3 a Python 2 full beginner course : the 
learners are not aware of the join method nor the str type nor 
generators stuff;
2) Your code introduce a (sometimes) useless conversion to str (consider 
a string instead of range(5)).



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


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 13:16, Steven D'Aprano a écrit :



Of course it does. Have you actually tried it?



Of course I did, redirecting the output to a file in order to spot an 
eventually trailing space. I did the same for the Python 3 code.

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


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 12:31, Peter Otten a écrit :
> softspace = False
> for i in range(5):
>  if softspace:
>  print(end=" ")
>  print(i, end="")
>  softspace = True
> print()


The if instruction imposes useless testing (we know in advance the 
problem to occur at the very end of the loop) and useless writing 
(writing '').


The following is clearer

# -
n=5
for i in range(n-1):
print(i, end=' ')
print(n-1)
# -


but doesn't solve all the cases (imagine a string or an iterator).
--
http://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 13:24, Ned Batchelder a écrit :


For a beginner course, the trailing space is fine, use this code.


I was really expecting there was a trick but I'll follow your advice, 
after all the trailing space is invisible!


Nevertheless, this can be quite annoying. For instance, some automated 
program testing (cf. http://www.spoj.com/, http://acm.timus.ru/, etc) 
expect the exact output to get accepted, no byte more or a byte less.






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


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 12:31, Peter Otten a écrit :


with `softspace` saved as a file attribute, is gone in Python3.



After reading

http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function


I understand what you meant by "softspace". Thanks.

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


Re: print function and unwanted trailing space

2013-08-31 Thread candide

Le 31/08/2013 15:59, Peter Otten a écrit :




To make it crystal clear, the above was to illustrate the algorithm used in
Python 2, not a suggestion.



Ok sorry, I misinterpreted.




> I still think you should live with a trailing space


Are you sure ? The following code

#--
import io

output = io.StringIO()
n=5
for i in range(n-1):
print(i, end=' ', file=output)
print(n-1, file=output)
print(output.getvalue().count(' '))
#--


outputs 4, the correct number of space character.



> or go with my actual
> suggestion
>
> print(*range(5))
>


It's a very good suggestion (the best one in fact) but rather 
complicated to explain to pure novices in programming.


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


Auto-completion: why not module name?

2015-03-16 Thread candide
Python 3.4 provides auto-completion facility within a Python console embedded 
in a command line terminal. 


But apparently this facility doesn't allow the user to complete with standard 
module name. For instance, editing the following :

>>> import ma

and hitting the TAB key doesn't generate 

math 

as I was expecting but the following strings :

map( max(

[tested on Ubuntu 12.10]

Is it the expected behaviour ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Evaluation order

2015-07-09 Thread candide
The official doc explains that :

Python evaluates expressions from left to right.

cf. https://docs.python.org/3.3/reference/expressions.html#evaluation-order


But consider the following snippet :


>>> t=[2020, 42, 2015]
>>> t*(1+int(bool(t.sort(
[42, 2015, 2020]
>>>


Is there not some contradiction with left-right evalutation? 





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


Re: Evaluation order

2015-07-10 Thread candide
Le vendredi 10 juillet 2015 04:02:56 UTC+2, Chris Angelico a écrit :


 
> I'm not sure what contradiction you're referring to, here. The
> evaluation that you're pointing out says, as Terry showed via the
> disassembly, that Python's first action is to look up the name 't' and
> grab a reference to whatever object it points to. 


But in order to perform an operation, the interpreter has to evaluate the 
operands and "evaluating" is not "grabbing a reference to". 

> The execution of
> t.sort() has to happen before the multiplication, because of the
> parentheses.
>



Official docs explains what evaluation is :

When the name is bound to an object, evaluation of the atom yields that object.

So, since the Python interpreter is performing evaluation from left to right, 
the first operand of the expression :

t*(1+int(bool(t.sort(

evaluates to [2020, 42, 2015]. Next, the second operatand evaluates to the 
integer 1. So I was expecting the result to be a shallow copy of the first list 
[2020, 42, 2015] (the value of t before side effect produced by the sort 
method). On the contrary, the final result takes into in account the side 
effect and it is as if the first operand has been evaluated twice before 
execution of the multiplication operation.




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


0 + not 0

2015-07-11 Thread candide
>>> 0 + not 0
  File "", line 1
0 + not 0
  ^
SyntaxError: invalid syntax
>>>


What is syntactically wrong with 0 + not 0?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 0 + not 0

2015-07-11 Thread candide
Le samedi 11 juillet 2015 13:21:03 UTC+2, Chris Angelico a écrit :
> I think you're misreading the table; 'not' has *lower* precedence than '+'.
> 


Right but Python docs helps a lot in misreading ;) Following the iconicity 
principle, it's pretty obvious that one has to display table priority beginning 
with items having the highest priority, cf. for instance table operator 
precedence for Java provided by oracle tutorial or for the C language as given 
by the K&R book.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 0 + not 0

2015-07-11 Thread candide
Le samedi 11 juillet 2015 13:31:03 UTC+2, Luuk a écrit :

> 
> But operator precedence of 'not' is higher than of '+' 


Right but what does this prove? For instance, unary minus has higher precedence 
than exponentiation but the expression

2 ** -1

doesn't raise a syntax error.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 0 + not 0

2015-07-11 Thread candide
Le samedi 11 juillet 2015 14:05:58 UTC+2, Chris Angelico a écrit :

> You'll see down below a footnote referring to this as a special case.

I didn't spot the footnote and I don't regard it as dealing with a "special 
case": the footnote is paraphrasing the precedence hierarchy given by the 
table. I  see it more as a glose (operator exponentiation is not so common in 
programming languages) or, better, a warning because precedence of unary minus 
is "between" two "multiplicative" operators (** and *).

By the way, example provided by the doc in this footnote doesnt't properly 
illustrate the precedence of ** versus unary minus : whatever the precedence 
is, there is only one way to evaluate 2**-1. On the opposite, -1**2 (for 
instance) leads to two evaluations : (-1)**2 and -(1**2) and would provide an 
appropriate and better example.




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


Re: 0 + not 0

2015-07-11 Thread candide
Le samedi 11 juillet 2015 15:38:51 UTC+2, Serhiy Storchaka a écrit :

> This looks as a bug to me. Please file a report on http://bugs.python.org.


OK, I'll report.
-- 
https://mail.python.org/mailman/listinfo/python-list


global and loop control variable

2015-07-23 Thread candide
About global declarations, Python Language Ref (PLR) explains:

[https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement]
~
Names listed in a global statement must not be used
in the same code block textually preceding that global statement.
~



What I understand is that the following code is incorrect:

# ---
def f():
x=42
global x

f()
print(x)
# ---

And indeed, executing this piece of code "raises" a warning :

~
test.py:3: SyntaxWarning: name 'x' is assigned to before global declaration
  global x
42
~

Now, global declaration has another restriction, as PLR explains:

[https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement]
~
Names listed in a global statement must not be defined as formal parameters
or in a for loop control target, 
~

What I understand is that the following is a must-not-code:

# ---
def f():
global i
for i in range(1,3):
print(10*i)

f()
print(i)
# ---

But, the later code executes silently without any warning:

~
10
20
2
~

So my question is: what is the restriction about global as loop control 
variable the docs is referring to?
-- 
https://mail.python.org/mailman/listinfo/python-list


42**1000000 is CPU time free

2015-07-24 Thread candide
Of course, computing 42**100 is not free:


# --
import time

a=time.clock()

N=100
42**N

b=time.clock()

print("CPU TIME :", b - a)
# --


~~
CPU TIME : 2.37

real0m2.412s
user0m2.388s
sys 0m0.016s
~~

So please, explain the following:


# --
import time

a=time.clock()

42**100

b=time.clock()

print("CPU TIME :", b - a)
# --

~~
CPU TIME : 0.0

real0m2.410s
user0m2.400s
sys 0m0.008s
~~

(focus on the CPU TIME!!)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 42**1000000 is CPU time free

2015-07-24 Thread candide
Thanks to all for your response, I was not aware that the interpreter evaluated 
 pure litteral expressions at compile time.
-- 
https://mail.python.org/mailman/listinfo/python-list


Single underscore in interactive mode

2014-06-25 Thread candide
According to the official documentation (The Python Language Reference, Release 
3.2):


---
The special identifier _ is used in the interactive interpreter to
store the result of the last evaluation;
---


This description is not very specific. Which evaluation is it about ? Consider 
the following interactive mode session:

>>> z = 42 + 1
>>> _
Traceback (most recent call last):
  File "", line 1, in 
_
NameError: name '_' is not defined
>>> 

As explained by the docs, an assignment statement _evaluates_ the expression on 
the right hand side. So we can deduce that at the very beginning of the 2nd 
prompt, "the result of the last evaluation" is 43. Nevertheless, calling _ 
raises a NameError exception!



In fact it seems that underscore returns the value of the last expression 
statement which is different from None :


>>> 4*10+2
42
>>> _
42
>>> "hello"
'hello'
>>> _
'hello'
>>> print(42)
42
>>> _
'hello'
>>> None
>>> _
'hello'
>>>


Can somebody provide a correct specification of the _ identifier in interactive 
mode ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Single underscore in interactive mode

2014-06-25 Thread candide

> 
> Please say either in a tracker issue or here where you found this 
> 
> statement. 



https://docs.python.org/3.4/reference/lexical_analysis.html#reserved-classes-of-identifiers
-- 
https://mail.python.org/mailman/listinfo/python-list


TypeError expected in an augmented assignment

2014-07-02 Thread candide
An hybrid list-tuple concatenation is not allowed

>>> []+(1, 2)
Traceback (most recent call last):  
  
  File "", line 1, in
  
TypeError: can only concatenate list (not "tuple") to list  
  
>>>  



hence I was expecting (*) that the following code raises a TypeError :

>>> x = []  
>>>   
>>> x += (1, 2) 
>>>   
>>> x   
>>>   
[1, 2]  
  
>>>


Any explanation ?


(*) as the docs states, the augmented assignment is supposed to perform the 
concatenation : 
An augmented assignment (...) performs the binary operation specific to the 
type of assignment on the two operands (...)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError expected in an augmented assignment

2014-07-03 Thread candide

>  >>> seq = [1,2]
> 
>  >>> seq.extend((3,4))


OK, this feature is referenced in the Python Library reference here : 

https://docs.python.org/3.2/library/stdtypes.html#typesseq-mutable

not thoroughly referenced but, anyway, referenced.





> 
>  >>> seq+= {5, 6}  # the order of extending is not determined
> 
>  >>> seq
> 
> [1, 2, 3, 4, 5, 6]
> 
>  >>>

Good and interesting observation. But I can't find out where this feature is 
referenced in the Language/Library Reference. Because, as my first post 
explains, augmented assignment performs the binary operation associated to the 
augmented assignment, cf. 

https://docs.python.org/3.2/reference/simple_stmts.html#augmented-assignment-statements

so seq+= {5, 6} performs seq + {5, 6}, the later raising a TypeError.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: TypeError expected in an augmented assignment

2014-07-03 Thread candide


> >From that link:
> 
> 
> 
> """
> 
> An augmented assignment expression like x += 1 can be rewritten as x =
> 
> x + 1 to achieve a similar, but not exactly equal effect. In the
> 
> augmented version, x is only evaluated once. Also, when possible, the
> 
> actual operation is performed in-place, meaning that rather than
> 
> creating a new object and assigning that to the target, the old object
> 
> is modified instead.
> 
> """
> 
> 
> 
> The significance here is that the augmented assignment may not
> 
> necessarily be at all comparable to the non-augmented version, but
> 
> ought to have *approximately* the same *intention*. 


This is not my reading. 




> 
> of situations where the two will differ, eg when there are multiple
> 
> references to the same object:
> 
> 
> 
> >>> a = b = [1,2]
> 
> >>> a += [3]
> 
> >>> a,b
> 
> ([1, 2, 3], [1, 2, 3])
> 
> >>> a = a + [4]
> 
> >>> a,b
> 
> ([1, 2, 3, 4], [1, 2, 3])
> 
> 

OK but this behavior is in conformance with the Reference Manual (cf. your 
quote above : "when possible, the actual operation is performed in-place"). 
This is not my point because the doc explictly claims that "an augmented 
assignment [...] performs the binary operation specific to the type of 
assignment on the two operands".
-- 
https://mail.python.org/mailman/listinfo/python-list


Python top learning language

2014-07-08 Thread candide
http://www.infoworld.com/d/application-development/python-bumps-java-top-learning-language-245774
-- 
https://mail.python.org/mailman/listinfo/python-list


Usefulness of the "not in" operator

2011-10-08 Thread candide

Python provides

-- the not operator, meaning logical negation
-- the in operator, meaning membership

On the other hand, Python provides the not in operator meaning 
non-membership. However, it seems we can reformulate any "not in" 
expression using only "not" and "in" operation. For instance


>>> 'th' not in "python"
False 


>>> not ('th' in "python")
False
>>>


So what is the usefulness of the "not in" operator ? Recall what Zen of 
Python tells


There should be one-- and preferably only one --obvious way to do it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 14:41, Alain Ketterlin a écrit :


Operators like "not in" and "is not" should
really be considered single tokens, even though they seem to use "not".
And I think they are really convenient.


I realize that I was confused by the lexical form of the "not in" 
operator : it is made by juxtaposing two other operators. Operators 
composed from two other operators exist, for instance != but the two 
cannot be separated, for instance


2 !   =   3

is not a valid expression. Said in another way, in Python syntax, 
usually a "lexically juxtaposed operator"  is seen as a whole. This is 
not the case for an operator such as "is not" or "not in" because for 
example


>>> 2  is not  3

is a valid statement.

A notin operator or isnot operator would be less confusing (at least in 
my case ;) ).

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


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 14:01, Steven D'Aprano a écrit :





> And "not in" is the obvious way to do it.
>
>

Obvious ? Not so. I performed some code mining and it appears that even 
good sources make use of  "not (foo in bar)" expressions.



 begin examples ***

from drpython/drPluginDialog.py
-
if not (plugin in self.parent.pluginstoremove):


from numpy/f2py/crackfortran.py
---
if not (l[0] in spacedigits):


from crunchy1.0alpha1/crunchy/src/plugins/vlam_editor.py
--
if (("no_copy" in vlam) and not ("no_pre" in vlam)) or (not python_code):


from Cpython/Python-3.1a1/Lib/logging/__init__.py
--
if not (hdlr in self.handlers):

from Cpython/Python-2.6.2/Lib/idlelib/configHandler.py
---
if not (configType in ('main','extensions','highlight','keys')):
raise InvalidConfigType, 'Invalid configType specified'

from 
pygtk-2.22.0/gtk/webkitgtk/WebKit-r93015/Source/JavaScriptCore/KeywordLookupGenerator.py

-
if not (key[0] in self.keys):

from pypy/pypy-pypy-release-1.6/lib-python/2.7/logging/__init__.py
--
if not (hdlr in self.handlers):

 end examples ***

_Many_ more examples of this type are avalaible.

The obviousness of an "is not" operator is very debatable. Do you have 
standard functions or method such as

isnotinstance, isnotsubset, isnotdir, isnotfile, isnotalpha, etc ?

In my case, It took a long time to realize the existence of a "true" 
"not in" operator as I explain in my response to Alain.



Imagine, /Dive Into Python/ book doesn't describe this operator per se 
and provides only one source file using it. Official Python tutorial at 
python.org didn't provide even one.




> "If the key is not in the ignition, you won't be able to start the car."
>
> "If not the key is in the ignition, you won't be able to start the car."
>
>
> Who like that second one speaks?
>


Depends if you are aware of negative form conjugation.


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


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 12:42, candide a écrit :



 >>> not ('th' in "python")
False
 >>>




After browsing source code, I realize that parenthesis are not necessary 
("not" has higher precedence than "in").

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


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 12:50, Jon Clements a écrit :


10 - 5 as 10 + -5 (as obviously the - is redundant as an operation),
and 10 / 2 as int(10 * .5) or something, who needs a divide!?




OK, I see your point but I was supposing non-membershipness seldom 
needed and in fact one can suppose that test membership is heavily more 
used than test non-membership.


In fact, it seems that most Python operators have an "antonym" operator, 
for instance :


== vs !=
< vs >=
is vs is not
+ vs -

etc

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


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 17:13, Thorsten Kampe a écrit :

* candide (Sat, 08 Oct 2011 16:41:11 +0200)

After browsing source code, I realize that parenthesis are not
necessary ("not" has higher precedence than "in").


Lower precedence.



Ooops, thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Usefulness of the "not in" operator

2011-10-08 Thread candide

Le 08/10/2011 17:16, Dave Angel a écrit :


You should say
"... parenthesis are not necessary ("not" has LOWER precedence than "in")."




I should, yes, I confess ;)


In my defense, I must tell that Python document reference here :

http://docs.python.org/reference/expressions.html#summary


has an anti-iconic way to display the order precedence.


If an operator OP1 has higher precedence than an operator OP2 , it means 
that, at evaluation time, you execute OP1 FIRST and operator OP2 later. 
So, its seems very natural to present FIRST operator with stronger 
precedence.



So, if you iconically present this material in a tabular display, you 
present FIRST (ie at the top because usually we process tabular material 
starting on the upper part) what you need to calculate FIRST and, again, 
you present


at the TOP the HIGHer precedence

and

at the BOTTOM the LOWer precedence.

Documentations usually provide the table in this order (higher to 
lower), cf. the table in K&R book for C programing language or here for 
the C++ PL :


http://en.cppreference.com/w/cpp/language/operator_precedence

or again there for the Java PL :

http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html








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


Re: Usefulness of the "not in" operator

2011-10-10 Thread candide

Le 10/10/2011 10:06, John Ladasky a écrit :


Who like that second one speaks?


Yoda his name is.  Programs in Forth he must.



;)


We can add to the list :

-- Tarzan
-- Geronimo
-- don Alexandro de la Vega dying in the arms of Zorro
...

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


Opportunity missed by Python ?

2011-10-13 Thread candide

Dart is the very new language created by Google to replace Javascript.
So Python was not able to do the job? Or may be they don't know about 
Python at Google ;) ?

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


randrange exceptional behavior

2011-10-24 Thread candide
Where is documented the behaviour of the standard function randrange  in 
the case of an empty list ? for instance randrange(42,33) ? May I rely 
on an ValueError type error?

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


Importing a module from a non-cwd

2011-10-24 Thread candide

Hi,

It's easy to open a file not located in the current working directory 
(cwd). But how about importing a module?


For instance, suppose I have a file, say my_file.py, located in the cwd, 
say /home/candide/ and suppose the module to be imported, say 
my_module.py, is located in the /home/candide/foo/ directory.




How my_file.py can import the my_module.py module ?

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


Re: randrange exceptional behavior

2011-10-24 Thread candide

Le 24/10/2011 22:09, MRAB a écrit :


but for choice(seq) it says:



Ah of course, I should have checked there


"""If seq is empty, raises IndexError."""

>


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


__dict__ attribute for built-in types

2011-10-27 Thread candide
I realize that built-in types objects don't provide a __dict__ attribute 
and thereby i can't set an attribute to a such object, for instance



>>> a=[42,421]
>>> a.foo="bar"
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute 'foo'
>>> a.__dict__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'list' object has no attribute '__dict__'
>>>


So, i was wondering :

-- why this behaviour ?
-- where the official documentation refers to this point ?


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


Re: __dict__ attribute for built-in types

2011-10-27 Thread candide

Le 27/10/2011 13:03, Duncan Booth a écrit :




-- where the official documentation refers to this point ?


See http://docs.python.org/reference/datamodel.html for the docs about
__slots__

There is also the API documentation which describes at a low level how
to control whether or not instances have a dict:
  http://docs.python.org/c-api/typeobj.html#tp_dictoffset

I'm not sure though where you find a higher level statement of which
builtin types have a __dict__.




OK, thanks for the information abouts the slots. Nevertheless, this 
cannot answer completely my question. Some builtin types like string, 
lists, integer, float, dictionaries, etc have the property that 
instances of those types don't provide a __dict__ attribute. I can't 
imagine the documentation lets pass silently this point.


But beside this, how to recognise classes whose object doesn't have a 
__dict__ attribute ?

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


Re: __dict__ attribute for built-in types

2011-10-27 Thread candide

Le 28/10/2011 00:19, Steven D'Aprano a écrit :


What, you think it goes against the laws of physics that nobody thought
to mention it in the docs?



No but I'm expecting from Python documentation to mention the laws of 
Python ...






But beside this, how to recognise classes whose object doesn't have a
__dict__ attribute ?


The same way as you would test for any other attribute.


hasattr(42, '__dict__')

False





OK but I'm talking about classes, not instances  : 42 has no __dict__ 
attribute but, may be, 43 _has_ such attribute, who knows in advance ? ;)


Let'have a try :

>>> hasattr(43, '__dict__')
False
>>>


so we have proved by induction that no integer instance has a 
dictionnary attribute ;)





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


Re: __dict__ attribute for built-in types

2011-10-27 Thread candide

Le 28/10/2011 00:57, Hrvoje Niksic a écrit :


was used at class definition time to suppress it.  Built-in and
extension types can choose whether to implement __dict__.



Is it possible in the CPython implementation to write something like this :

"foo".bar = 42

without raising an attribute error ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: __dict__ attribute for built-in types

2011-10-27 Thread candide

Le 28/10/2011 02:02, MRAB a écrit :



No, built-in classes written in C have certain limitations, but why
would you want to do that anyway?





Mainly for learning purpose and Python better understanding.

Actually, I have a class of mine for drawing graphs with the Graphviz 
software. The nodes of the graph to be represented was supposed to have 
2 attributes, say title and shortName. Now, I want to plot a graph whose 
nodes are pure string. So to fit the class interface, I was trying to 
add title and shortName attribute to every string node.


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


Re: __dict__ attribute for built-in types

2011-10-28 Thread candide

Le 28/10/2011 05:02, Patrick Maupin a écrit :


You can easily do that by subclassing a string:

class AnnotatedStr(str):
 pass

x = AnnotatedStr('Node1')
x.title = 'Title for node 1'




Less or more what I did. But requires to transport the string graph 
structure to the AnnotatedStr one.


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


Re: __dict__ attribute for built-in types

2011-10-28 Thread candide

Le 28/10/2011 10:01, Steven D'Aprano a écrit :


didn't think of it. This is hardly a surprise. Wanting to add arbitrary
attributes to built-ins is not exactly an everyday occurrence.





Depends. Experimented programmers don't even think of it. But less 
advanced programmers can consider of it. It's is not uncommun to use a 
Python class like a C  structure, for instance :


class C:pass

C.member1=foo
C.member2=bar


Why not with a built-in type instead of a custom class?





the natural logarithm of a googol (10**100). But it's a safe bet that
nothing so arbitrary will happen.


betting when programming ?  How curious! ;)



Also, keep in mind the difference between a *class* __dict__ and an
*instance* __dict__.



You mean this distinction

>>> hasattr('', '__dict__')
False
>>> hasattr(''.__class__, '__dict__')
True
>>>


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


Re: __dict__ attribute for built-in types

2011-10-28 Thread candide

Le 28/10/2011 11:08, Hrvoje Niksic a écrit :


longer be allowed for the interpreter to transparently cache them.  The
same goes for integers and other immutable built-in objects.



On the other hand, immutability and optimization don't explain the whole 
thing because you can't do something like [].bar = 42.






If you really need to attach state to strings, subclass them as Steven
explained.  All code that accepts strings (including all built-ins) will
work just fine, transparent caching will not happen, and attributes are
writable.


OK, thanks, I'll consider it seriously. Actually I have a directed graph 
whose nodes are given as string but it's oversimplistic to identify node 
and string (for nodes requiring specific methods).

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


Use and usefulness of the as syntax

2011-11-12 Thread candide

First, could you confirm the following syntax

import foo as f

equivalent to

import foo
f = foo



Now, I was wondering about the usefulness in everyday programming of the 
as syntax within an import statement. Here are some instances retrieved 
from real code of such a syntax


import numpy as np

import math as _math

import pickle as pickle


-- In the first case, the syntax is motivated by brevity need, isn't it ?
-- The second case seems to be rather widespread and causes math 
attribute to be private but I don't figure out why this matters.

-- In the last case, I can see no point

So what is the pragmatics of the as syntax ?

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


Re: Use and usefulness of the as syntax

2011-11-17 Thread candide

Le 12/11/2011 13:29, Arnaud Delobelle a écrit :


-- The second case seems to be rather widespread and causes math attribute
to be private but I don't figure out why this matters.


This way math doesn't get bound in the global namespace when doing
"from module import *"




To contextualize more, I guess you are referring to the following 
situation :




# a.py
import math as _math


# b.py
from a import *

print _math.sin(0)   # raise a NameError
print math.sin(0)# raise a NameError



so the as syntax is also seful for hiding name, isn'it ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Use and usefulness of the as syntax

2011-11-17 Thread candide

Thanks to all




Le 12/11/2011 13:27, Chris Angelico a écrit :
> On Sat, Nov 12, 2011 at 10:56 PM, candide  wrote:
>> import foo as f
>>
>> equivalent to
>>
>> import foo
>> f = foo
>>
>
> Not quite, it's closer to:
>
> import foo
> f = foo
> del foo
>



Le 12/11/2011 13:43, Tim Chase a écrit :
> On 11/12/11 05:56, candide wrote:
>> First, could you confirm the following syntax
>>
>> import foo as f
>>
>> equivalent to
>>
>> import foo
>> f = foo
>
> and the issuing "del foo"
>




Correct, I missed this point : I didn't realize that importing is also 
binding.

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


Pragmatics of the standard is() function

2011-11-26 Thread candide
In which cases should we use the is() function ? The is() function 
compares identity of objects rather than values so I was wondering in 
which circumstances comparing identities of objects is really vital.


Examining well reputated Python source code, I realize that is() 
function is mainly used in the following set form :


spam is None

But how much "spam is None" is different from "spam == None" ?



is() function makes comparaison of (abstract representation of) adresses 
of objects in memory. Comparing addresses of objects is a low level 
feature performed by low level langages such as C but seldom needed in 
high level languages like Python, isn'it ?

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


Re: Pragmatics of the is operator

2011-11-26 Thread candide

Thanks to all for your response.


Le 27/11/2011 00:01, Steven D'Aprano a écrit :

On Sat, 26 Nov 2011 22:20:36 +0100, candide wrote:


In which cases should we use the is() function ? The is() function
compares identity of objects rather than values so I was wondering in
which circumstances comparing identities of objects is really vital.


`is` is not a function. It is a keyword and an operator.


oops exponent 10 !! I have in mind the id() function, very close to the 
is operator. An operator named "is" makes search of code snippets  very 
complicated because the verb "is" is always embedded in comments or 
documentation.





But how much "spam is None" is different from "spam == None" ?


Even if you can guarantee that your code base does not contain any object
which compares equal to None except for None itself (and how would you do
that? a full audit of every line of code in every library you use?), the
use of `is` should be preferred because it signals your intention much
better.


OK but tons of good code use "spam == None" ; for instance, many tests 
files in Python official code. A random example (from 
openshot/openshot/windows/MainGTK.py):


# ---

parent_name = item.parent
if parent_name == None:
match_iter = None

# Check for NO files
if mode == None and self.project.project_folder.items.__len__() 
== 0:
#switch to the detail view


if drop_track == None:
# keep old parent, if no track found


if self.new_clip_object == None:
self.item_detected = False

# ---





If your intention is to accept arbitrary objects which compare equal to
None, than by all means use == for your comparison. But normally the
intention is to accept None, and nothing else.



So, for the same reason, wouldn't it be better to use "if spam is True" 
against to "if spam == True"  (or better "if spam") ?




That is correct. You probably should rarely use `is`. Apart from testing
for None, use of `is` should be rare.



OK, thanks
--
http://mail.python.org/mailman/listinfo/python-list


Regexp : repeated group identification

2011-12-14 Thread candide

Consider the following code

# 
import re

z=re.match('(Spam\d)+', 'Spam4Spam2Spam7Spam8')
print z.group(0)
print z.group(1)
# 

outputting :


Spam4Spam2Spam7Spam8
Spam8


The '(Spam\d)+' regexp is tested against 'Spam4Spam2Spam7Spam8' and the 
regexp matches the string.


Group numbered one within the regex '(Spam\d)+' refers to Spam\d

The fours substrings

Spam4   Spam2   Spam7  and  Spam8

match the group numbered 1.

So I don't understand why z.group(1) gives the last substring (ie Spam8 
as the output shows), why not an another one, Spam4 for example ?

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


Re: Regexp : repeated group identification

2011-12-14 Thread candide

Le 14/12/2011 12:34, Vlastimil Brom a écrit :


"If a group is contained in a part of the pattern that matched
multiple times, the last match is returned."



I missed this point, your answer matches my question ;) thanks.



If you need to work with the content captured in the repeated group,
you may check the new regex implementation:
http://pypi.python.org/pypi/regex

Which has a special "captures" method of the match object for this
(beyond many other improvements):


import regex
m=regex.match('(Spam\d)+', 'Spam4Spam2Spam7Spam8')
m.captures(1)

['Spam4', 'Spam2', 'Spam7', 'Spam8']







Thanks for the reference and the example. I didn't know of this 
reimplementation, hoping it offers the Aho-Corasick algorithm allowing 
multiple keys search.

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


Type object returned by the re.compile function

2011-12-27 Thread candide

The Python 2.7 official documentation here:

http://docs.python.org/library/re.html#re.compile

doesn't specify the type object returned by the re.compiled function. 
According to the documentation, re.compile returns a "regular expression 
object".


A regular expression object seems to be an instance of the class 
RegexObject. The documentation mentions this class here :


http://docs.python.org/library/re.html#regular-expression-objects

but i don't see any existing class with this name :

>>> import re
>>> re.RegexObject
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'RegexObject'
>>>

Actually, a regular expression object doesn't seem to be a class object :

>>> import re
>>> reo = re.compile('')
>>> reo.__class__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: __class__
>>>

but has attributes :

>>> dir(reo)
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 
'search', 'split', 'sub', 'subn']

>>>


I have the same problem with the match object : the doc mentions a 
re.MatchObject class but this class doesn't exist :


>>> re.MatchObject
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'MatchObject'
>>>


Any clarification is welcome.
--
http://mail.python.org/mailman/listinfo/python-list


Repeating assertions in regular expression

2012-01-03 Thread candide
The regular expression HOWTO 
(http://docs.python.org/howto/regex.html#more-metacharacters) explains 
the following


# --
zero-width assertions should never be repeated, because if they match 
once at a given location, they can obviously be matched an infinite 
number of times.

# --


Why the wording is "should never" ? Repeating a zero-width assertion is 
not forbidden, for instance :


>>> import re
>>> re.compile("\\b\\b\w+\\b\\b")
<_sre.SRE_Pattern object at 0xb7831140>
>>>

Nevertheless, the following doesn't execute :

>>> re.compile("\\b{2}\w+\\b\\b")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.7/re.py", line 190, in compile
return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
>>>


\\b\\b and \\b{2} aren't equivalent ?


Surprisingly, the engine doesn't optimize repeated boundary assertions, 
for instance


# --
import re
import time

a=time.clock()
len("\\b\\b\\b"*10+"\w+")
b=time.clock()
print "CPU time : %.2f s" %(b - a)

a=time.clock()
re.compile("\\b\\b\\b"*10+"\w+")
b=time.clock()
print "CPU time : %.2f s" %(b - a)
# --

outputs:

# --
CPU time : 0.00 s
CPU time : 1.33 s
# --


Your comments are welcome!
--
http://mail.python.org/mailman/listinfo/python-list


Regular expression : non capturing groups are faster ?

2012-01-03 Thread candide
Excerpt from the Regular Expression HOWTO 
(http://docs.python.org/howto/regex.html#non-capturing-and-named-groups) :



---
It should be mentioned that there’s no performance difference in 
searching between capturing and non-capturing groups; neither form is 
any faster than the other.

---


Now from the Perl Regular Expression tutorial 
(http://perldoc.perl.org/perlretut.html#Non-capturing-groupings) :



---
Because there is no extraction, non-capturing groupings are faster than 
capturing groupings.

---


The second assertion sounds more likely. It seems very odd that Python 
and Perl implementations are divergent on this point. Any opinion ?



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


Re: Regular expression : non capturing groups are faster ?

2012-01-03 Thread candide

Le 03/01/2012 12:56, Devin Jeanpierre a écrit :

The second assertion sounds more likely. It seems very odd that Python and
Perl implementations are divergent on this point. Any opinion ?


The Python documentation oversimplifies.


You meant Perl Documentation, didn't you ?


It's a commun opinion that non-capturing groups have a price (minor), 
for instance Jan Goyvaerts, a well known regular expression guru, 
refering to Python code, tells :



non-capturing groups (...)  offer (slightly) better performance as the 
regex engine doesn't have to keep track of the text matched by 
non-capturing groups.



[link is there : 
http://stackoverflow.com/questions/2703029/why-regular-expressions-non-capturing-group-is-not-working]




It seems Javascript performs better respect to non-capturing groups : 
http://jsperf.com/regex-capture-vs-non-capture


The same for java : http://eyalsch.wordpress.com/2009/05/21/regex/
(no benchmarks).

For my part, Python tests didn't show any kind of significative penality.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is operator versus id() function

2013-04-05 Thread candide
Le vendredi 5 avril 2013 16:53:55 UTC+2, Arnaud Delobelle a écrit :
 

> 
> You've fallen victim to the fact that CPython is very quick to collect
> 
> garbage.  


OK, I get it but it's a fairly unexpected behavior. 
Thanks for the demonstrative snippet of code and the instructive answer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Not fully OO ?

2008-09-20 Thread candide

Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html :

"About Python: Python is a high level scripting language with object 
oriented features.

(...)
Python supports OOP and classes to an extent, but is not a full OOP 
language."



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


Redirecting stdin to a file

2009-12-04 Thread candide
How do I redirect stdin to a text file ? In C, this can be done with the
freopen() standard function, for instance

FILE *foo = freopen("in.txt", "r", stdin);


redirects stdin to the in.txt text file. Does anyone know a freopen()
Python equivalent ?

Notice that I'm not referring to shell redirection as the following
command line shows :

$ python myCode.py < in.txt

I need to hardcode the redirection inside the python source file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Redirecting stdin to a file

2009-12-04 Thread candide
@MRAB
@Lie Ryan

Thanks, it works fine !
-- 
http://mail.python.org/mailman/listinfo/python-list


Restarting IDLE without closing it

2009-09-29 Thread candide
Hi
I was wondering if there exists somme way to clear memory of all objects
created during a current IDLE session (with the same effect as if one
starts an IDLE session). Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restarting IDLE without closing it

2009-09-29 Thread candide
Scott David Daniels a écrit :

> Different than "Shell  /  Restart Shell (Ctrl+F6)" ?
> Of course this doesn't work if you started Idle ith the "-n" switch.
> 

Thanks for the info : by default on my Ubuntu distrib, IDLE is launched
with the -n option ;)  Now, all is clear !
-- 
http://mail.python.org/mailman/listinfo/python-list


Input redirection with IDLE

2009-10-13 Thread candide
Hi

Does  IDLE (the default GUI avalaible with the standard distribution)
support redirection from the standard input ? To be more precise, inside
a Windows or Linux shell I may redirect input data from a text file to
be executed by a python file. For instance suppose I have this python file


# foo.py
print int(raw_input())+int(raw_input())


and this data file

- data.txt BOF 
42
77
- data.txt EOF 

I may process the data in this way :

~$ python foo.py < data.txt

and the result is the following printing  :

119


Is IDLE able to provide the same service ?

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


Quoting quotes

2010-02-26 Thread candide
Suppose you have to put into a Python string the following sentence :

The play "All's Well That Ends Well" by Shakespeare

It's easy do it :

>>> print """The play "All's Well That Ends Well" by Shakespeare"""
The play "All's Well That Ends Well" by Shakespeare

Now, change the sentence to this one :

The play "All's Well That Ends Well"

Using triple single quotes works fine

>>> print '''The play "All's Well That Ends Well"'''
The play "All's Well That Ends Well"


But the first method doesn't run correctly :


>>> print """The play "All's Well That Ends Well
  File "", line 1
print """The play "All's Well That Ends Well
   ^
SyntaxError: EOL while scanning single-quoted string
>>>


Any comment ?


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


Re: Quoting quotes

2010-02-28 Thread candide
OK, now I see the point. I was mistaken because I was supposing  that
every quote strictly _inside_ the string have to match another quote od
the same type.

Thanks to all for yours responses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Starting Python from the terminal with no welcome message

2010-02-28 Thread candide
Hi,

Does exist some option I could send to the python interpreter during an
interactive session in order to avoid the printing of the  introductory
message just above the top prompt ?

In my case, the welcome message is the following :

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.



gdb has such an option (the so-called quiet option).


Compare this :

$ gdb
GNU gdb 6.8-debian
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later

This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
(gdb)

with that

$ gdb -q
(gdb)


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


Re: Starting Python from the terminal with no welcome message

2010-03-01 Thread candide
Tim Chase a écrit :

> 
>   bash$ python -ic ""
> 
> to get a python shell without the banner.
>


Works fine. thanks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Standard module implementation

2010-11-28 Thread candide
I was wondering if all the standard module are implemented in C. For 
instance, I can't find a C implementation for the minidom xml parser 
under Python 2.6.

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


Deleting more than one element from a list

2010-04-21 Thread candide
Is the del instruction able to remove _at the same_ time more than one 
element from a list ?



For instance, this seems to be correct :


>>> z=[45,12,96,33,66,'c',20,99]
>>> del z[2], z[6],z[0]
>>> z
[12, 33, 66, 'c', 20]
>>>


However, the following doesn't work :

>> z=[45,12,96,33,66,'c',20,99]
>>> del z[2], z[3],z[6]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list assignment index out of range
>>>


Does it mean the instruction

del z[2], z[3],z[6]

to be equivalent to the successive calls


del z[2]
del z[3]
del z[6]

?










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


Re: Deleting more than one element from a list

2010-04-21 Thread candide

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


a.extend(b) better than a+=b ?

2010-04-22 Thread candide

Suppose a and b are lists.

What is more efficient in order to extend the list a by appending all 
the items in the list b ?



I imagine a.extend(b)to be more efficient for only appendinding the 
items from b while a+=b creates a copy of a before appending, right ?

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


  1   2   >