Re: What is a function parameter =[] for?

2015-11-24 Thread Ned Batchelder
On Tuesday, November 24, 2015 at 9:34:36 AM UTC-5, Antoon Pardon wrote:
> Op 20-11-15 om 13:12 schreef Ned Batchelder:
> > On Friday, November 20, 2015 at 6:59:54 AM UTC-5, BartC wrote:
> >> On 20/11/2015 01:05, Steven D'Aprano wrote:
> >>> On Fri, 20 Nov 2015 04:30 am, BartC wrote:
> >>>
>  On 19/11/2015 16:01, Steven D'Aprano wrote:
> >>> [...]
> >>>
>  The whole concept of 'mutable' default is alien to me. A default is just
>  a convenient device to avoid having to write:
> 
>  fn(0) or fn("") or fn([])
> >>>
> >>> Says who?
> >>
> >> People who want to avoid having to write:
> >>
> >>   fn(0) or fn("") or fn([])
> > 
> > I think we all understand by now that you are unhappy with what happens
> > in Python with mutable defaults.  We get it.  You are not alone. Lots of
> > people are surprised by this.  But it is how Python works.
> 
> May be you should get this message through to the python tribe, so that
> they stop reacting as a stung horse each time someone finds something
> bizarre with the language.

I agree with you: Python experts shouldn't be surprised when people are
surprised by this behavior.

> 
> > I'm not sure what your goal is at this point.  Are you:
> > 
> >   1) still unsure what the behavior is, or 
> >   2) trying to understand why it behaves that way, or
> >   3) hoping to change Python, or
> >   4) trying to convince us that your language is better, or
> >   5) something else?
> 
> Maybe just have us recognize that some aspects of python indeed are bizarre.
> That there is nothing wrong with him thinking so. After that he will have
> to make up his mind whether this bizarre aspect is to big a hurdle for
> using the language or not, because it seems unlikely to change.

I also agree with you: there is nothing wrong with people thinking parts of
Python are bizarre.  What we ask is that people then try to understand
how Python works.  If people say, "This surprised me, Python is stupid!"
and then leave it there, the conversation is bound to go poorly.

Every language works differently, and every language has things that will
surprise new learners.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 1:43 AM, BartC  wrote:
> It comes from the use of file handles (what you get in some languages when
> you open or create a file) which everyone can understand:
>
> * If you copy handle F to G like in an assignment, it obviously doesn't copy
> the contents of the file, just the handle.
>
> * If I compare the contents of files F and H, they might be the same, but
> they are not necessarily the same file.
>
> * If F and G are the same handle, then if I update a file via F, I will see
> the same change via handle G.
>
> The main difference is that when F and G go out of scope and the handles
> disappear, the file hopefully still exists! (And ideally the file is first
> closed via one of the handles.)

I would recommend picking a different example, actually. An open file
(the resource) is different from the file that actually exists on the
disk. You can open a file for reading three times, and barring access
conflicts etc, you'll get three distinct open-file-objects (file
handles, etc), with separate read pointers, and advancing the file
pointer of one has no effect on the other two. Plus there are other
considerations like the notion of duplicating file handles,
force-duplicating file handles (sometimes called "dup2"), files that
no longer exist on disk but only in memory, files that exist on disk
but no longer have any file names, and so on. Files are way WAY more
complicated than you want to dig into here.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 23-11-15 om 14:58 schreef Steven D'Aprano:
> On Mon, 23 Nov 2015 09:40 pm, BartC wrote:
> 
>> On 23/11/2015 07:47, Steven D'Aprano wrote:
>>
>>> I think it would be cleaner and better if Python had dedicated syntax for
>>> declaring static local variables:
>>
>> Interesting. So why is it that when /I/ said:
>>
>>  > On Mon, 23 Nov 2015 12:21 am, BartC wrote:
>>  >
>>  >> But if it's used for static storage, then why not just use static
>>  >> storage?
>>
>> You replied with the insulting:
>>
>>  > /head-desk
>>
>> ?
>>
>> Maybe it's my turn to bang my head on the desk.
> 
> Let me steal^W borrow an idea from Galileo, and present the explanation in
> the form of a dialogue between two philosophers of computer science,
> Salviati and Simplicio, and a third, intelligent layman, Sagredo.
> 
> https://en.wikipedia.org/wiki/Dialogue_Concerning_the_Two_Chief_World_Systems
> 
> 
> Salviati: Function defaults can also be used for static storage.
> 
> Simplicio: If you want static storage, why not use static storage?
> 
> Salviati: Function defaults in Python *are* static storage.
> 
> Although they not the only way to get static storage, as closures can
> also be used for that purpose, they are surely the simplest way to get
> static storage in Python.
> 
> Sagredo: Simplest though it might be, surely a reasonable person would
> consider that using function parameters for static storage is abuse of the
> feature and a global variable would be better?
> 
> Salviati: Global variables have serious disadvantages. I will agree that
> using function parameters for static storage is something of a code smell,
> but good enough for rough and ready code. Nevertheless, it would be good if
> Python had dedicated syntax for static storage.
> 
> Simplicio: Ah-ha! Gotcha!
> 
> Salviati: No, perhaps you missed that I was referring to a hypothetical
> future addition to Python, not a current feature. But even if it did exist
> today, your statement misses the point that by using function defaults I
> *am* using static storage. In effect, you are telling me that rather than
> using static storage I should instead use static storage.

If you really want mutable static storage, you can simulate it more cleanly with
a closure than using a default argument.

def factory():

  static_dict = {}

  def myfunc(a, b):
mutate static_dict as much as you like

  return myfunc

myfunc = factory()

Or you can use a class of course.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 15:34 schreef Chris Angelico:
> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>  wrote:
>>> Start thinking of it as a constructor call rather than a literal, and
>>> you'll get past most of the confusion.
>>
>> That doesn't change the fact it does look like a literal and not like
>> a constructor.
> 
> Then explain how this is a literal:
> 
> squares = [x*x for x in range(int(input("How far? ")))]

So are you saying

  () isn't a literal

because

  (x * x for x in range(int(input("How far? " isn't a literal?

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 15:34 schreef Chris Angelico:
> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>  wrote:
>>> Start thinking of it as a constructor call rather than a literal, and
>>> you'll get past most of the confusion.
>>
>> That doesn't change the fact it does look like a literal and not like
>> a constructor.
> 
> Then explain how this is a literal:
> 
> squares = [x*x for x in range(int(input("How far? ")))]
> 
> Or even a simple example like this:
> 
> coords = (randrange(10), randrange(10))
> 
> Neither of them is a literal, even though one of them isn't even
> constructing a list. Tuples may be constant, but they still don't have
> a literal form. (Constant folding can make them function the same way
> literals do, though. If a tuple is constructed of nothing but
> immutable constants - including an empty tuple - then CPython will
> generally create a constant for the whole tuple and use that, rather
> than manually constructing one every time. But the same is true of
> other expressions involving nothing but constants.)
> 
> So if it (in your opinion) looks like a literal but isn't one, whose
> fault is it? Yours or the language's? Not a rhetorical question.
> 
> ChrisA
> 

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 15:18 schreef Ned Batchelder:

> 2) In Python, "value" means, what object does a name refer to, or what
> object did an evaluation produce.

I don't think this is correct because that would imply that objects don't
change values (since the value would be the object).

When a list is mutated, it's value has changed. That is how the word is
generally used in python.

-- 
Antoon.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 15:34 schreef Chris Angelico:
> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>  wrote:
>>> Start thinking of it as a constructor call rather than a literal, and
>>> you'll get past most of the confusion.
>>
>> That doesn't change the fact it does look like a literal and not like
>> a constructor.
> 
> Then explain how this is a literal:
> 
> squares = [x*x for x in range(int(input("How far? ")))]

Are you arguing that () isn't a literal because the following
is not a literal?

squares = (x*x for x in range(int(input("How far? "

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 2:03 AM, Antoon Pardon
 wrote:
> Op 24-11-15 om 15:34 schreef Chris Angelico:
>> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>>  wrote:
 Start thinking of it as a constructor call rather than a literal, and
 you'll get past most of the confusion.
>>>
>>> That doesn't change the fact it does look like a literal and not like
>>> a constructor.
>>
>> Then explain how this is a literal:
>>
>> squares = [x*x for x in range(int(input("How far? ")))]
>
> So are you saying
>
>   () isn't a literal
>
> because
>
>   (x * x for x in range(int(input("How far? " isn't a literal?

I'm pretty sure tuple/list/dict display predates comprehensions, and
was already not a literal syntax. Steven, you know the history better
than I do - confirm or deny?

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ned Batchelder
On Tuesday, November 24, 2015 at 10:10:51 AM UTC-5, Antoon Pardon wrote:
> Op 24-11-15 om 15:18 schreef Ned Batchelder:
> 
> > 2) In Python, "value" means, what object does a name refer to, or what
> > object did an evaluation produce.
> 
> I don't think this is correct because that would imply that objects don't
> change values (since the value would be the object).

Sorry, I should have been more precise.  Python documentation suffers from
this two-meaning world also.  There are places where "value" is used in
this second sense, perhaps more places than you realize.  I know when I
wrote "Python Names and Values", I meant it in this second sense.

When you think people's claims about values, or understanding of values
are incorrect, take a moment to decipher which of these two meanings they
are likely using, and see if it more sense.

> When a list is mutated, it's value has changed. That is how the word is
> generally used in python.

I don't know about "generally."  It's true that when a list is mutated, it
is the same referent, but now has a different evalue.  That's what it means
to be mutable.

It's also true that the Python docs, being written in English, will use the
"evalue" sense of the word, mixed together with the "referent" sense of the
word.

And yes, this can be confusing.

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


Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
Hi,

I have to run the asyncio.loop on a separated thread because the main
thread is running FUSE. Apparently fuse needs to run on the main
thread because it uses signal():


File "/usr/local/lib/python3.4/dist-packages/fuse.py", line 390, in __init__
old_handler = signal(SIGINT, SIG_DFL)
ValueError: signal only works in main thread


Anyway, when I exit the program it appears that i run into a deadlock
with the eventloop thread, strace is stuck with:


futex(0x7f7bac10, FUTEX_WAIT_PRIVATE, 0, NULL


I've tried to stop the event loop from the main thread but the
situation is exactly the same :(

loop_container = {}
handler = threading.Thread(target=run_loop, args=(loop_container,))
try:
   handler.start()
   FUSE(fs)
finally:
loop_container['loop'].stop()
# handler.join()

Any idea on how I can shutdown the hole thing? I have to manually kill
the program each time :(

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


Re: Bi-directional sub-process communication

2015-11-24 Thread israel

On 11/23/2015 20:29, Cameron Simpson wrote:

On 24Nov2015 16:25, Cameron Simpson  wrote:

Completely untested example code:

class ReturnEvent:
  def __init__(self):
self.event = Event()


With, of course:

   def wait(self):
 return self.event.wait()


Of course :-) Ah, the Event() object comes from the threading module. 
That makes sense. This should work perfectly. Thanks so much for taking 
the time to help me out!

-
Israel Brewster



Cheers,
Cameron Simpson 

Maintainer's Motto: If we can't fix it, it ain't broke.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 2:46 AM, Antoon Pardon
 wrote:
> What is your point? I say that [] looks like a literal. Because it
> sure resembles () which is a literal.
>
> That [] in fact isn't a literal doesn't contradict it looks like
> one.
>
> That you can come up with more complicated list expressions that
> are more easily recognizable as not being literals is beside the
> point because we have generator expressions that look similar to
> those list comprehensions and those generator expressions don't
> contradict that () is a literal.

() is not a literal either.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 16:17 schreef Chris Angelico:
> On Wed, Nov 25, 2015 at 2:03 AM, Antoon Pardon
>  wrote:
>> Op 24-11-15 om 15:34 schreef Chris Angelico:
>>> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>>>  wrote:
> Start thinking of it as a constructor call rather than a literal, and
> you'll get past most of the confusion.

 That doesn't change the fact it does look like a literal and not like
 a constructor.
>>>
>>> Then explain how this is a literal:
>>>
>>> squares = [x*x for x in range(int(input("How far? ")))]
>>
>> So are you saying
>>
>>   () isn't a literal
>>
>> because
>>
>>   (x * x for x in range(int(input("How far? " isn't a literal?
> 
> I'm pretty sure tuple/list/dict display predates comprehensions, and
> was already not a literal syntax. Steven, you know the history better
> than I do - confirm or deny?

What is your point? I say that [] looks like a literal. Because it
sure resembles () which is a literal.

That [] in fact isn't a literal doesn't contradict it looks like
one.

That you can come up with more complicated list expressions that
are more easily recognizable as not being literals is beside the
point because we have generator expressions that look similar to
those list comprehensions and those generator expressions don't
contradict that () is a literal.

-- 
Antoon.

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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
On Tue, Nov 24, 2015 at 4:29 PM, Marc Aymerich  wrote:
> Hi,
>
> I have to run the asyncio.loop on a separated thread because the main
> thread is running FUSE. Apparently fuse needs to run on the main
> thread because it uses signal():
>
> 
> File "/usr/local/lib/python3.4/dist-packages/fuse.py", line 390, in __init__
> old_handler = signal(SIGINT, SIG_DFL)
> ValueError: signal only works in main thread
>
>
> Anyway, when I exit the program it appears that i run into a deadlock
> with the eventloop thread, strace is stuck with:
>
> 
> futex(0x7f7bac10, FUTEX_WAIT_PRIVATE, 0, NULL
>
>
> I've tried to stop the event loop from the main thread but the
> situation is exactly the same :(
>
> loop_container = {}
> handler = threading.Thread(target=run_loop, args=(loop_container,))
> try:
>handler.start()
>FUSE(fs)
> finally:
> loop_container['loop'].stop()
> # handler.join()
>
> Any idea on how I can shutdown the hole thing? I have to manually kill
> the program each time :(


this can be reproduced with the following program:

import asyncio
import threading
import time

def run_loop(loop_container):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
coro = asyncio.start_server(lambda: 1, '0.0.0.0', , loop=loop)
server = loop.run_until_complete(coro)
loop_container['loop'] = loop
loop.run_forever()

if __name__ == '__main__':
loop_container = {}
handler = threading.Thread(target=run_loop, args=(loop_container, ))
handler.start()
try:
time.sleep(1)
finally:
loop_container['loop'].stop()


glic3@XPS13:/tmp$ python3 /tmp/eventtest.py
^CTraceback (most recent call last):
  File "/tmp/eventtest.py", line 22, in 
time.sleep(1)
KeyboardInterrupt
^CException ignored in: 
Traceback (most recent call last):
  File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown
t.join()
  File "/usr/lib/python3.4/threading.py", line 1060, in join
self._wait_for_tstate_lock()
  File "/usr/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock
elif lock.acquire(block, timeout):
KeyboardInterrupt

it is waiting for tstate_lock in the second ^C

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Tue, 24 Nov 2015 11:57 pm, Marko Rauhamaa wrote:

> Antoon Pardon :
> 
>> You then switching to talking about objects, just gives the impression
>> that object is a synonym for value.
> 
> It isn't?

No it isn't.

The definition of "object" -- well, I say "the" definition, but the nasty
truth is that there are many different definitions and nobody really agrees
on what an object is -- the definition of "object" is a software entity
with three fundamental attributes or qualities:

- the type of object;

- the value of the object;

- the identity of the object.

If we limit ourselves to Python, that definition works because Python has
been designed to work that way. Other languages may be different, but when
it comes to Python, it is true by definition that all objects have a type,
a value and an identity because that's what Guido did.

The type of the object is the class that it is an instance of:

py> type("hello")


The identity of the object is represented by the integer ID returned by the
id() function. But what it represents is the distinct existence of one
object as compared to another. In real life, the identity of *this* sheep
versus *that* sheep, or this instance of a book versus that instance of the
same book.

(Aside: those of a philosophical bent will quickly realise that we don't
really understand what identity *is*. See, for example, the paradox of my
gradfather's axe. And what distinguishes this electron from some other
electron? There's even a theory in physics that *all electrons are in fact
the one electron*, bouncing backwards and forwards in time repeatedly.)

The value of the object depends on its type -- the value of ints differ from
the value of strings, for example.

Immutable objects have a fixed value for their entire lifespan: the object 2
has the same numeric value, namely two, from the moment it is instantiated
to the moment it is garbage collected.

Mutable objects do not have such a fixed value:

py> L = []  # value is the empty list
py> L.append(None)  # value is now a singleton list containing None
py> L[:] = 'cat dog fox'.split()  # value is now a list containing strings
cat, dog, fox.
py> L
['cat', 'dog', 'fox']


It's the same list, the same object, but the value changes.




-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Random832
On 2015-11-24, Chris Angelico  wrote:
> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
> wrote:
>>> Start thinking of it as a constructor call rather than a literal, and
>>> you'll get past most of the confusion.
>>
>> That doesn't change the fact it does look like a literal and not like
>> a constructor.
>
> Neither of them is a literal, even though one of them isn't even
> constructing a list. Tuples may be constant, but they still don't have
> a literal form.

How do you define "literal form"? I define it as any syntax that
can participate in ast.literal_eval (And I consider [...] to be a
literal form regardless of whether the ... values are literals or
not). I don't think "Start thinking of it as a constructor call
rather than a literal" is helpful, since it just hides one's
confusion about what a literal is.

The Python documentation itself seems to assume that "literal"
should only be used for things that are a single token, though I
have no idea where this thinking comes from.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 3:28 AM, Random832  wrote:
> On 2015-11-24, Chris Angelico  wrote:
>> On Wed, Nov 25, 2015 at 1:24 AM, Antoon Pardon
>> wrote:
 Start thinking of it as a constructor call rather than a literal, and
 you'll get past most of the confusion.
>>>
>>> That doesn't change the fact it does look like a literal and not like
>>> a constructor.
>>
>> Neither of them is a literal, even though one of them isn't even
>> constructing a list. Tuples may be constant, but they still don't have
>> a literal form.
>
> How do you define "literal form"? I define it as any syntax that
> can participate in ast.literal_eval (And I consider [...] to be a
> literal form regardless of whether the ... values are literals or
> not). I don't think "Start thinking of it as a constructor call
> rather than a literal" is helpful, since it just hides one's
> confusion about what a literal is.

https://docs.python.org/3/reference/lexical_analysis.html#literals

ast.literal_eval can handle a number of things which are not literals,
as long as they use nothing but literals combined by a restricted set
of operators. For instance, Python has no complex literals, only
imaginary ones - but:

>>> ast.literal_eval("1+2j")
(1+2j)

And Python certainly doesn't have "expression literals", yet:

>>> ast.literal_eval("[1,1+1,3]")
[1, 2, 3]

Its support for list display equally doesn't make that into a literal.

> The Python documentation itself seems to assume that "literal"
> should only be used for things that are a single token, though I
> have no idea where this thinking comes from.

Probably the grammar. In other words, it's part of the language's very
definition.

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


Re: tuples in conditional assignment (Ben Finney)

2015-11-24 Thread George Trojan

Ben Finney writes:

Ben Finney 
Date:
11/24/2015 04:49 AM

To:
python-list@python.org


George Trojan  writes:


The following code has bitten me recently:


t=(0,1)
x,y=t if t else 8, 9
print(x, y)

(0, 1) 9

You can simplify this by taking assignment out of the picture::

 >>> t = (0, 1)
 >>> t if t else 8, 9
 ((0, 1), 9)

So that's an “expression list” containing a comma. The reference for
expressions tells us::

 An expression list containing at least one comma yields a tuple. The
 length of the tuple is the number of expressions in the list.

 https://docs.python.org/3/reference/expressions.html#expression-lists>


I was assuming that a comma has the highest order of evaluation

You were? The operator precedence rules don't even mention comma as an
operator, so why would you assume that?

 
https://docs.python.org/3/reference/expressions.html#operator-precedence>
What threw me  off was the right column in the table stating that 
binding or tuple display has the highest precedence. Somewhere else 
there is a statement that a comma makes a tuple, not the parentheses, so 
the parentheses on the left did not register with me.



that is the expression 8, 9 should make a tuple. Why this is not the
case?

I'm not sure why it's the case that you assumed that

My practical advice: I don't bother trying to remember the complete
operator precedence rules. My simplified precedence rules are:

* ‘+’, ‘-’ have the same precedence.
* ‘*’, ‘/’, ‘//’ have the same precedence.
* For anything else: Use parentheses to explicitly declare the
   precedence I want.

Related: When an expression has enough clauses that it's not *completely
obvious* what's going on, break it up by assigning some sub-parts to
temporary well-chosen descriptive names (not ‘t’).
t was just to illustrate my problem, not the actual code. My lesson is 
to use parentheses in all cases, maybe with an exception for an obvious 
y, x = x, y. In my new C code I always write


if (a) {
f();
}

instead of a valid 2-liner

if (a)
   f();

Too many times I added indented g() call, and since I do more Python 
than C, the error was not glaringly obvious.


-- \ “It is far better to grasp the universe as it really is than to | 
`\ persist in delusion, however satisfying and reassuring.” —Carl | 
_o__) Sagan | Ben Finney

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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
threading supports the 'daemon' option[1], when set to True and the
program is in *foreground* then the event-loop thread dies when
SIGTERM-ed, however, if the program is in the *background* it doesn't
work! still deadlocked :'''(

while I'm not finding a definitive solution I'll be doing a
os.kill(os.getpid(), signal.SIGKILL) inside the finally block.

[1] https://docs.python.org/3.5/library/threading.html#threading.Thread.daemon

On Tue, Nov 24, 2015 at 4:46 PM, Marc Aymerich  wrote:
> On Tue, Nov 24, 2015 at 4:29 PM, Marc Aymerich  wrote:
>> Hi,
>>
>> I have to run the asyncio.loop on a separated thread because the main
>> thread is running FUSE. Apparently fuse needs to run on the main
>> thread because it uses signal():
>>
>> 
>> File "/usr/local/lib/python3.4/dist-packages/fuse.py", line 390, in __init__
>> old_handler = signal(SIGINT, SIG_DFL)
>> ValueError: signal only works in main thread
>>
>>
>> Anyway, when I exit the program it appears that i run into a deadlock
>> with the eventloop thread, strace is stuck with:
>>
>> 
>> futex(0x7f7bac10, FUTEX_WAIT_PRIVATE, 0, NULL
>>
>>
>> I've tried to stop the event loop from the main thread but the
>> situation is exactly the same :(
>>
>> loop_container = {}
>> handler = threading.Thread(target=run_loop, args=(loop_container,))
>> try:
>>handler.start()
>>FUSE(fs)
>> finally:
>> loop_container['loop'].stop()
>> # handler.join()
>>
>> Any idea on how I can shutdown the hole thing? I have to manually kill
>> the program each time :(
>
>
> this can be reproduced with the following program:
>
> import asyncio
> import threading
> import time
>
> def run_loop(loop_container):
> loop = asyncio.new_event_loop()
> asyncio.set_event_loop(loop)
> coro = asyncio.start_server(lambda: 1, '0.0.0.0', , loop=loop)
> server = loop.run_until_complete(coro)
> loop_container['loop'] = loop
> loop.run_forever()
>
> if __name__ == '__main__':
> loop_container = {}
> handler = threading.Thread(target=run_loop, args=(loop_container, ))
> handler.start()
> try:
> time.sleep(1)
> finally:
> loop_container['loop'].stop()
>
>
> glic3@XPS13:/tmp$ python3 /tmp/eventtest.py
> ^CTraceback (most recent call last):
>   File "/tmp/eventtest.py", line 22, in 
> time.sleep(1)
> KeyboardInterrupt
> ^CException ignored in:  '/usr/lib/python3.4/threading.py'>
> Traceback (most recent call last):
>   File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown
> t.join()
>   File "/usr/lib/python3.4/threading.py", line 1060, in join
> self._wait_for_tstate_lock()
>   File "/usr/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock
> elif lock.acquire(block, timeout):
> KeyboardInterrupt
>
> it is waiting for tstate_lock in the second ^C
>
> --
> Marc



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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 16:48 schreef Chris Angelico:
> On Wed, Nov 25, 2015 at 2:46 AM, Antoon Pardon
>  wrote:
>> What is your point? I say that [] looks like a literal. Because it
>> sure resembles () which is a literal.
>>
>> That [] in fact isn't a literal doesn't contradict it looks like
>> one.
>>
>> That you can come up with more complicated list expressions that
>> are more easily recognizable as not being literals is beside the
>> point because we have generator expressions that look similar to
>> those list comprehensions and those generator expressions don't
>> contradict that () is a literal.
> 
> () is not a literal either.

The byte code sure suggests it is.

Take the following code:

import dis

def f():
  i = 42
  t = ()
  l = []

dis.dis(f)

That produces the following:


  4   0 LOAD_CONST   1 (42)
  3 STORE_FAST   0 (i)

  5   6 LOAD_CONST   2 (())
  9 STORE_FAST   1 (t)

  6  12 BUILD_LIST   0
 15 STORE_FAST   2 (l)
 18 LOAD_CONST   0 (None)
 21 RETURN_VALUE

So on what grounds would you argue that () is not a literal.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 9:41 AM, Antoon Pardon
 wrote:
> Op 24-11-15 om 16:48 schreef Chris Angelico:
>> () is not a literal either.
>
> The byte code sure suggests it is.
>
> Take the following code:
>
> import dis
>
> def f():
>   i = 42
>   t = ()
>   l = []
>
> dis.dis(f)
>
> That produces the following:
>
>
>   4   0 LOAD_CONST   1 (42)
>   3 STORE_FAST   0 (i)
>
>   5   6 LOAD_CONST   2 (())
>   9 STORE_FAST   1 (t)
>
>   6  12 BUILD_LIST   0
>  15 STORE_FAST   2 (l)
>  18 LOAD_CONST   0 (None)
>  21 RETURN_VALUE

I'm not sure what this is meant to prove. None is clearly an
identifier, not a literal, and it also gets treated as a constant in
the code above.

> So on what grounds would you argue that () is not a literal.

This enumerates exactly what literals are in Python:

https://docs.python.org/3/reference/lexical_analysis.html#literals

I think it's a rather pedantic point, though. How are nuances of the
grammar at all related to user expectations?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Returning a result from 3 items in a list

2015-11-24 Thread Ned Batchelder
On Tuesday, November 24, 2015 at 9:29:30 AM UTC-5, Mark Lawrence wrote:
> On 24/11/2015 14:07, Denis McMahon wrote:
> > On Tue, 24 Nov 2015 02:04:56 -0800, Cai Gengyang wrote:
> >
> >> Here's a dictionary with 3 values :
> >>
> >> results = {
> >>"gengyang": 14,
> >>"ensheng": 13, "jordan": 12
> >> }
> >>
> >> How do I define a function that takes the last of the 3 items in that
> >> list and returns Jordan's results i.e. (12) ?
> >
> > You open a web browser and google for "python dictionary"
> >
> 
> Ooh steady on old chap, surely you should have fitted the bib, done the 
> spoon feeding and then changed the nappy?  That appears to me the 
> preferred way of doing things nowadays on c.l.py, rather than bluntly 
> telling people not to be so bloody lazy.

Mark and Denis, if you are having a hard time with newcomers to this list,
perhaps you need to find another list to read?

Yes, Cai Gengyang could do more research before asking questions.  But
your response does nothing to improve the situation.  It's just snark
and bile, and does not exemplify the Python community's culture.

> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.

What you can do for our language is put a better foot forward.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Oscar Benjamin
On 24 November 2015 at 15:27, Ned Batchelder  wrote:
> On Tuesday, November 24, 2015 at 10:10:51 AM UTC-5, Antoon Pardon wrote:
>> Op 24-11-15 om 15:18 schreef Ned Batchelder:
>>
>> > 2) In Python, "value" means, what object does a name refer to, or what
>> > object did an evaluation produce.
>>
>> I don't think this is correct because that would imply that objects don't
>> change values (since the value would be the object).
>
> Sorry, I should have been more precise.  Python documentation suffers from
> this two-meaning world also.  There are places where "value" is used in
> this second sense, perhaps more places than you realize.  I know when I
> wrote "Python Names and Values", I meant it in this second sense.

Hi Ned, I read your talk on this subject which was linked to further
up in the thread and it is excellent so thanks for that. I forwarded
it to a colleague for inspiration in our own introductory programming
(with Python) teaching unit.

However when I read it and imagined explaining it to our students I
found myself wanting to adjust the terminology. I would not use the
word value in the way that you suggest. Rather I would want to
contrast "names" (or "references"), "objects" and "values". I think
that many things can be expressed more cleanly with these terms and I
think it corresponds more to the way in which I see Python programmers
use these terms.

So I would say that an object has a value. Immutable objects have
unchanging values but the value of mutable objects can change. The
expression "a is b" determines whether or not a and b are bound to the
same object whereas "a == b" determines if the objects bound to a and
b have the same value. To copy an object is to create a new object
having the same value as the copied object. To mutate an object is to
change its value etc.

Earlier in this thread you said:
"""
In Python, a default value expression
for a function argument is evaluated only once, when the function is defined.
That value (in this case, the actual list) is stored with the function. The
expression is not stored, the value of the expression is. That value (the
actual list) is supplied as the value of the argument if no other value is
supplied.  If you modify that value in the function, the value is modified,
and used again at the next function call.
"""
I think that's a good example of where it would be clearer to
distinguish between objects and values, rather than using the word
value for both. In particular what is stored with the function is the
*object* that results from the default value expression. The *value*
of that object may change if it is mutated but it will still be the
same object each time the function is called (without a corresponding
argument being passed).

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Tue, 24 Nov 2015 11:38 pm, Antoon Pardon wrote:

> Op 19-11-15 om 13:45 schreef Steven D'Aprano:
[...]
>> I don't mean that it isn't sometimes useful. Of course it is sometimes
>> useful, there's no doubt about that. But why would you expect the
>> language to default to the *slow*, *expensive*, *complicated* behaviour
>> instead of the *fast*, *cheap*, *simple* behaviour?
> 
> I would say because it is better understandable. 

I disagree that it (late-binding) is more understandable. 

Late-binding (or, "late evaluation" for those who prefer that term) is no
easier to understand than early binding. Earlier, I publicly screwed up
reasoning about late binding.

And so did BartC, whose personal language has precisely the late binding
semantics he wants, exactly as he designed it, and yet he was surprised by
its behaviour leading him to (wrongly) conclude that his language was more
dynamic than Python:

Quote:

"(Python returns 42; so that means my languages are more dynamic than 
Python? That's hard to believe!)"

See this thread, post from BartC dated Fri, 20 Nov 2015 08:21:24 am.


> The way default value 
> behave now, is just a little less surprising as when the following segment
> of code would print: [1]
> 
> a = []
> a.append(1)
> b = []
> print b

No, it really isn't anything like that at all. If you (generic you, not
specifically you personally) think that it is similar, you've misunderstood
what is going on.

If we want an analogy, this is a good one:

alist = []
for i in range(20):
alist.append(i)
print alist


Are you surprised that alist keeps growing? Contrast this to:


for i in range(20):
alist = []
alist.append(i)
print alist


Are you surprised that alist keeps getting re-set to the empty list?


Change the for-loop to a function declaration. If the binding of the list []
happens inside the indented block, it will happen every time the function
is called (just as it happens each time through the loop in the second
example above). If the binding happens outside of the body, it happens
once, not every time.

Folk like BartC want the function default to be re-evaluated every time the
function is called. I'm not blind to the usefulness of it: I write lots of
functions with late-binding semantics too. I just write them like this:

def func(a=None):
if a is None:
a = something()


Perhaps as more people start using function annotations, it will become more
obvious that function declarations aren't re-evaluated every single time
you call the function:

def func(a:some_expression=another_expression): ...

*Both* expressions, the annotation and the default, are evaluated once and
once only.


> Let us not forget that the tutorial talks about Default Argument *Values*.
> And also the language reference talks about precomputed *values*. What
> we really get is a precomputed object.

There is a distinction between value and object, but without seeing the
exact wording and context of the tutorial and language reference, I cannot
tell whether they are misleading or not. There's nothing wrong with talking
about default values. You just have to remember that some values can
change.


>> You already have one way to set the argument to a fresh list every time
>> you call the function: put the code you want executed inside the body of
>> the function. There's no need for a *second* way to get the same result.
> 
> Which is beside the point. The point is understandability.

Okay. Suppose for the sake of the argument I agree with you
that "understandability" is the most important factor here.

Then early binding is still the clear winner, because it has simple, easy to
understand semantics:

- the "def" line is executed once, and once only, including all parameter
defaults and annotations;

- the *body* of the function is executed when the function is called, not
the "def" function declaration.

Since the function defaults are part of the declaration, not the body, it is
far more understandable that it is executed once only.



>> But if you want the default value to be evaluated exactly once, and once
>> only, there is no real alternative to early binding. You could use a
>> global variable, of course, but that is no solution -- that's a problem
>> waiting to happen.
> 
> No more than the situation we have now. The situation we have now is a
> problem waiting to happen too. Which is confirmed again and again. You are
> stacking the deck by calling a possible alternative "a problem waiting to
> happen" while ignoring the problems that happen with the current
> situation.

Pardon me, I certainly am not ignoring anything of the sort. I do
acknowledge that the behaviour of mutable defaults can be surprising. I
even admitted that it surprised me. It's often not the behaviour that you
want, so you have to do something slightly different.

The bottom line is that there are good reasons for the way Python works with
function defaults, but they aren't good for everything. Neit

Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 17:56 schreef Ian Kelly:

> 
>> So on what grounds would you argue that () is not a literal.
> 
> This enumerates exactly what literals are in Python:
> 
> https://docs.python.org/3/reference/lexical_analysis.html#literals
> 
> I think it's a rather pedantic point, though. How are nuances of the
> grammar at all related to user expectations?
> 

I think that enumaration is too limited. The section starts with:

   Literals are notations for constant values of some built-in types.

() satisfies that definition, which is confirmed by the byte code
produced for it.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ned Batchelder
On Tuesday, November 24, 2015 at 12:25:54 PM UTC-5, Oscar Benjamin wrote:
> On 24 November 2015 at 15:27, Ned Batchelder  wrote:
> > On Tuesday, November 24, 2015 at 10:10:51 AM UTC-5, Antoon Pardon wrote:
> >> Op 24-11-15 om 15:18 schreef Ned Batchelder:
> >>
> >> > 2) In Python, "value" means, what object does a name refer to, or what
> >> > object did an evaluation produce.
> >>
> >> I don't think this is correct because that would imply that objects don't
> >> change values (since the value would be the object).
> >
> > Sorry, I should have been more precise.  Python documentation suffers from
> > this two-meaning world also.  There are places where "value" is used in
> > this second sense, perhaps more places than you realize.  I know when I
> > wrote "Python Names and Values", I meant it in this second sense.
> 
> Hi Ned, I read your talk on this subject which was linked to further
> up in the thread and it is excellent so thanks for that. I forwarded
> it to a colleague for inspiration in our own introductory programming
> (with Python) teaching unit.
> 
> However when I read it and imagined explaining it to our students I
> found myself wanting to adjust the terminology. I would not use the
> word value in the way that you suggest. Rather I would want to
> contrast "names" (or "references"), "objects" and "values". I think
> that many things can be expressed more cleanly with these terms and I
> think it corresponds more to the way in which I see Python programmers
> use these terms.
> 
> So I would say that an object has a value. Immutable objects have
> unchanging values but the value of mutable objects can change. The
> expression "a is b" determines whether or not a and b are bound to the
> same object whereas "a == b" determines if the objects bound to a and
> b have the same value. To copy an object is to create a new object
> having the same value as the copied object. To mutate an object is to
> change its value etc.
> 
> Earlier in this thread you said:
> """
> In Python, a default value expression
> for a function argument is evaluated only once, when the function is defined.
> That value (in this case, the actual list) is stored with the function. The
> expression is not stored, the value of the expression is. That value (the
> actual list) is supplied as the value of the argument if no other value is
> supplied.  If you modify that value in the function, the value is modified,
> and used again at the next function call.
> """
> I think that's a good example of where it would be clearer to
> distinguish between objects and values, rather than using the word
> value for both. In particular what is stored with the function is the
> *object* that results from the default value expression. The *value*
> of that object may change if it is mutated but it will still be the
> same object each time the function is called (without a corresponding
> argument being passed).
> 
> --
> Oscar

Oscar, thanks for the thoughtful comments. I agree that using "object" for
the result of an expression, and for the referent of a name, would go some
ways to clarifying things.

Perhaps the Python world uses "value" less to mean "object" than I am thinking.
But we do talk about "the value of an expression", and "what value does X
have," and so on.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Terry Reedy

On 11/24/2015 9:34 AM, Antoon Pardon wrote:

I agree that the tutorial should talk about default argument objects 
(which have values) instead of conflating 'object' with 'value'.



Op 20-11-15 om 13:12 schreef Ned Batchelder:



I'm not sure what your goal is at this point.  Are you:

   1) still unsure what the behavior is, or
   2) trying to understand why it behaves that way, or
   3) hoping to change Python, or
   4) trying to convince us that your language is better, or
   5) something else?


Maybe just have us recognize that some aspects of python indeed are bizarre.


The current behavior under discussion is: default argument expressions 
are evaluated once at function creation time to produce default argument 
objects that are bound to the function object.  I do not see this as 
bizarre.



That there is nothing wrong with him thinking so.


I do recognize that some would prefer that default argument expressions 
be treated differently, that


def f(a=expression): pass

be compiled to operate as the following does now

def f(a=None):
a = a if a is not None else expression

perhaps with None replaced with a hidden object() instance.

I find the continuing fuss over the choice that was made to be the 
bizarre thing here.


--
Terry Jan Reedy

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


Re: Finding scores from a list

2015-11-24 Thread John Gordon
In <277843f7-c898-4378-85ea-841b09a28...@googlegroups.com> Cai Gengyang 
 writes:


> results = [
> {"id": 1, "name": "ensheng", "score": 10},
> {"id": 2, "name": "gengyang", "score": 12},
> {"id": 3, "name": "jordan", "score": 5},
> ]

Okay, this is a list.

> I want to find gengyang's score. This is what I tried :

> >>> print((results["gengyang"])["score"])

> but I got an error message instead :

> Traceback (most recent call last):
>   File "", line 1, in 
> print((results["gengyang"])["score"])
> TypeError: list indices must be integers, not str

Lists are indexed by number, not by name.

You want something like this:

for result in results:
if result["name"] == "gengyang":
print result["score"]
break

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 10:32 AM, Antoon Pardon
 wrote:
> Op 24-11-15 om 17:56 schreef Ian Kelly:
>
>>
>>> So on what grounds would you argue that () is not a literal.
>>
>> This enumerates exactly what literals are in Python:
>>
>> https://docs.python.org/3/reference/lexical_analysis.html#literals
>>
>> I think it's a rather pedantic point, though. How are nuances of the
>> grammar at all related to user expectations?
>>
>
> I think that enumaration is too limited. The section starts with:
>
>Literals are notations for constant values of some built-in types.
>
> () satisfies that definition, which is confirmed by the byte code
> produced for it.

Literals are a type of lexical token. All of the literals shown in
that section are, indeed, tokens. Now I would point you to the grammar
specification:

https://docs.python.org/3/reference/grammar.html

And specifically the "atom" rule, which defines both list displays and
list comprehensions (as well as literals) as being atoms.
Specifically, it parses () as the token '(', followed by an optional
yield_expr or testlist_comp, followed by the token ')'. In no way is
that a single token, nor therefore a literal.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 02:17 am, Chris Angelico wrote:

> On Wed, Nov 25, 2015 at 2:03 AM, Antoon Pardon
>  wrote:

>> So are you saying
>>
>>   () isn't a literal
>>
>> because
>>
>>   (x * x for x in range(int(input("How far? " isn't a literal?
> 
> I'm pretty sure tuple/list/dict display predates comprehensions, and
> was already not a literal syntax. Steven, you know the history better
> than I do - confirm or deny?


I must admit that I'm often guilty of referring to [a, b, c] as a list
literal, but, no, () and related forms aren't literals[1], and yes,
tuple/list/dict displays predates list comprehensions by a long time.

Here's Python 1.5:

Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat
4.1.2-52)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import dis
>>> code = compile("(1, 2, 3)", "", "eval")
>>> dis.dis(code)
  0 SET_LINENO  0
  3 LOAD_CONST  0 (1)
  6 LOAD_CONST  1 (2)
  9 LOAD_CONST  2 (3)
 12 BUILD_TUPLE 3
 15 RETURN_VALUE


So you can see the tuple actually gets assembled at runtime. Even if the
tuple is empty, the same process occurs:

>>> code = compile("()", "", "eval")
>>> dis.dis(code)
  0 SET_LINENO  0
  3 BUILD_TUPLE 0
  6 RETURN_VALUE



In contrast, using an actual literal (even a big one) loads the literal as a
pre-existing constant:


>>> code = compile("42099L", "", "eval")
>>> dis.dis(code)
  0 SET_LINENO  0
  3 LOAD_CONST  0 (42099L)
  6 RETURN_VALUE




[1] Although with recent versions of Python, the peephole optimizer is
clever enough to treat tuples consisting of nothing but literals as if it
were itself a literal. E.g. in Python 3.3:

py> import dis
py> code = compile("(1, 2, 3)", "", "eval")
py> dis.dis(code)
  1   0 LOAD_CONST   3 ((1, 2, 3))
  3 RETURN_VALUE


But that is a recent optimization, and it relies on the facts that tuples
are immutable, and that the items within the tuple are themselves immutable
literals:


py> code = compile("(1, 2, [])", "", "eval")
py> dis.dis(code)
  1   0 LOAD_CONST   0 (1)
  3 LOAD_CONST   1 (2)
  6 BUILD_LIST   0
  9 BUILD_TUPLE  3
 12 RETURN_VALUE



-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 01:58 am, Antoon Pardon wrote:

> Op 23-11-15 om 14:58 schreef Steven D'Aprano:

> > ... closures can also be used for [static storage] ...

> If you really want mutable static storage, you can simulate it more
> cleanly with a closure than using a default argument.

You don't say. Thanks for letting me know what I already pointed out in the
very post you responded to. It's always nice to see that people read my
words with care and attention to detail.



-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 10:53 AM, Ian Kelly  wrote:
> On Tue, Nov 24, 2015 at 10:32 AM, Antoon Pardon
>  wrote:
>> Op 24-11-15 om 17:56 schreef Ian Kelly:
>>
>>>
 So on what grounds would you argue that () is not a literal.
>>>
>>> This enumerates exactly what literals are in Python:
>>>
>>> https://docs.python.org/3/reference/lexical_analysis.html#literals
>>>
>>> I think it's a rather pedantic point, though. How are nuances of the
>>> grammar at all related to user expectations?
>>>
>>
>> I think that enumaration is too limited. The section starts with:
>>
>>Literals are notations for constant values of some built-in types.
>>
>> () satisfies that definition, which is confirmed by the byte code
>> produced for it.
>
> Literals are a type of lexical token. All of the literals shown in
> that section are, indeed, tokens. Now I would point you to the grammar
> specification:
>
> https://docs.python.org/3/reference/grammar.html
>
> And specifically the "atom" rule, which defines both list displays and
> list comprehensions (as well as literals) as being atoms.
> Specifically, it parses () as the token '(', followed by an optional
> yield_expr or testlist_comp, followed by the token ')'. In no way is
> that a single token, nor therefore a literal.

In case reading the grammar doesn't convince, we can also get this
result from playing with the language:

>>> import tokenize
>>> from io import StringIO
>>> list(tokenize.generate_tokens(StringIO('()').readline))
[TokenInfo(type=52 (OP), string='(', start=(1, 0), end=(1, 1),
line='()'), TokenInfo(type=52 (OP), string=')', start=(1, 1), end=(1,
2), line='()'), TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0),
end=(2, 0), line='')]

Two separate tokens of the OP type.

>>> list(tokenize.generate_tokens(StringIO('42').readline))
[TokenInfo(type=2 (NUMBER), string='42', start=(1, 0), end=(1, 2),
line='42'), TokenInfo(type=0 (ENDMARKER), string='', start=(2, 0),
end=(2, 0), line='')]

One token, of a literal type.

>>> list(tokenize.generate_tokens(StringIO('(1,2,3)').readline))
[TokenInfo(type=52 (OP), string='(', start=(1, 0), end=(1, 1),
line='(1,2,3)'), TokenInfo(type=2 (NUMBER), string='1', start=(1, 1),
end=(1, 2), line='(1,2,3)'), TokenInfo(type=52 (OP), string=',',
start=(1, 2), end=(1, 3), line='(1,2,3)'), TokenInfo(type=2 (NUMBER),
string='2', start=(1, 3), end=(1, 4), line='(1,2,3)'),
TokenInfo(type=52 (OP), string=',', start=(1, 4), end=(1, 5),
line='(1,2,3)'), TokenInfo(type=2 (NUMBER), string='3', start=(1, 5),
end=(1, 6), line='(1,2,3)'), TokenInfo(type=52 (OP), string=')',
start=(1, 6), end=(1, 7), line='(1,2,3)'), TokenInfo(type=0
(ENDMARKER), string='', start=(2, 0), end=(2, 0), line='')]

Two tokens for the parentheses, plus three literal tokens for the
ints, plus two more tokens for the separating commas. Definitely not a
literal.

Credit to Steven for using this approach to make a similar point about
literals in a previous thread.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Zachary Ware
On Tue, Nov 24, 2015 at 9:46 AM, Marc Aymerich  wrote:
> if __name__ == '__main__':
> loop_container = {}
> handler = threading.Thread(target=run_loop, args=(loop_container, ))
> handler.start()
> try:
> time.sleep(1)
> finally:
> loop_container['loop'].stop()

loop.stop() must be called from the thread running the loop.  You can
do this by doing
`loop_container['loop'].call_soon_threadsafe(loop_container['loop'].stop)`
from the main thread (untested).

Hope this helps,
-- 
Zach
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Marko Rauhamaa
Ned Batchelder :

> Oscar, thanks for the thoughtful comments. I agree that using "object"
> for the result of an expression, and for the referent of a name, would
> go some ways to clarifying things.
>
> Perhaps the Python world uses "value" less to mean "object" than I am
> thinking. But we do talk about "the value of an expression", and "what
> value does X have," and so on.

There are all kinds of uses (Google: python "value of"):

  "How to get the value of a variable given its name in a string"

  "The value of some objects can change. Objects whose value can change
  are said to be mutable"

  "I'm taking the return value of one function and using it as the
  argument of another function"

  "Don't get confused — name on the left, value on the right"

  "We can print the current value of the dictionary in the usual way"

  "A return statement ends the execution of the function call and
  "returns" the result, i.e. the value of the expression following the
  return keyword, to the caller"

  "When we ask python what the value of x > 5 is, we get False"

  "To display the value of a variable, you can use a print statement"

  "Get a value of a specified key"


Personally, I don't like the "official" Python usage:

   Objects whose value can change are said to be mutable

I would prefer this wording:

   Objects whose inner state can change are said to be mutable


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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 18:46 schreef Terry Reedy:
> On 11/24/2015 9:34 AM, Antoon Pardon wrote:
> 
> I agree that the tutorial should talk about default argument objects (which 
> have values) instead of conflating 'object' with 'value'.
> 
>> Op 20-11-15 om 13:12 schreef Ned Batchelder:
> 
>>> I'm not sure what your goal is at this point.  Are you:
>>>
>>>1) still unsure what the behavior is, or
>>>2) trying to understand why it behaves that way, or
>>>3) hoping to change Python, or
>>>4) trying to convince us that your language is better, or
>>>5) something else?
>>
>> Maybe just have us recognize that some aspects of python indeed are bizarre.
> 
> The current behavior under discussion is: default argument expressions are 
> evaluated once at function creation
> time to produce default argument objects that are bound to the function 
> object.  I do not see this as bizarre.

I do. That a default can be mutated so that your default can have different 
values upon
different calls is IMO bizarre. I understand where it is coming from and I can 
live with
it, but I still find it bizarre.

>> That there is nothing wrong with him thinking so.
> 
> I do recognize that some would prefer that default argument expressions be 
> treated differently, that
> 
> def f(a=expression): pass
> 
> be compiled to operate as the following does now
> 
> def f(a=None):
> a = a if a is not None else expression
> 
> perhaps with None replaced with a hidden object() instance.

An other possibility could be compiling as the following

_tmp = expression
def f(a = None):
a = a if a is not None else _tmp.copy()

> 
> I find the continuing fuss over the choice that was made to be the bizarre 
> thing here.
> 

IMO that comes because the python tribe often enough can't handle differences of
appreciation. So what if BartC finds this behaviour bizarre? Why this need to
correct him of that notion? By absolutly wanting to argue that it is not bizarre
the most likely result was that BartC went on the defensive, while if people
would simply have acknowlegded that he is not the only one that finds that
behaviour bizarre and then focused on explaining what happens, a lot less fuss
would have been generated.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 05:13 am, Marko Rauhamaa wrote:

> Personally, I don't like the "official" Python usage:
> 
> Objects whose value can change are said to be mutable
> 
> I would prefer this wording:
> 
> Objects whose inner state can change are said to be mutable


I see your point, but "inner state" might not be related to the object's
externally visible value.

For example, dicts have an inner state which can vary, even when their value
remains the same:

# using Python 3.3

py> d = {-1: "a", -2: "b"}
py> e = {-2: "b", -1: "a"}
py> d == e
True
py> print(d, e)
{-2: 'b', -1: 'a'} {-1: 'a', -2: 'b'}

The two dicts have the same value, but their inner state is slightly
different, which is why they print in different order.

Likewise for lists:


py> a = []
py> for i in range(100):
... a.append(1)
...
py> b = [1]*100
py> a == b
True
py> sys.getsizeof(a) == sys.getsizeof(b)
False



-- 
Steven

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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
On Tue, Nov 24, 2015 at 7:11 PM, Zachary Ware
 wrote:
> On Tue, Nov 24, 2015 at 9:46 AM, Marc Aymerich  wrote:
>> if __name__ == '__main__':
>> loop_container = {}
>> handler = threading.Thread(target=run_loop, args=(loop_container, ))
>> handler.start()
>> try:
>> time.sleep(1)
>> finally:
>> loop_container['loop'].stop()
>
> loop.stop() must be called from the thread running the loop.  You can
> do this by doing
> `loop_container['loop'].call_soon_threadsafe(loop_container['loop'].stop)`
> from the main thread (untested).
>

Hi Zachary,
nice to know about call_soon_threadsafe!

still it appears to work only if the main thread is in the foreground
(as of calling Thread() with deamon=True), I don't get why it behaves
differently :( maybe it is waiting for other stuff, but no idea how to
confirm this with strace of other means.. i always see the same
'futex(0x7f9a7c10, FUTEX_WAIT_PRIVATE, 0, NULL'

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 18:53 schreef Ian Kelly:
> On Tue, Nov 24, 2015 at 10:32 AM, Antoon Pardon
>  wrote:
>> Op 24-11-15 om 17:56 schreef Ian Kelly:
>>
>>>
 So on what grounds would you argue that () is not a literal.
>>>
>>> This enumerates exactly what literals are in Python:
>>>
>>> https://docs.python.org/3/reference/lexical_analysis.html#literals
>>>
>>> I think it's a rather pedantic point, though. How are nuances of the
>>> grammar at all related to user expectations?
>>>
>>
>> I think that enumaration is too limited. The section starts with:
>>
>>Literals are notations for constant values of some built-in types.
>>
>> () satisfies that definition, which is confirmed by the byte code
>> produced for it.
> 
> Literals are a type of lexical token. All of the literals shown in
> that section are, indeed, tokens. Now I would point you to the grammar
> specification:
> 
> https://docs.python.org/3/reference/grammar.html
> 
> And specifically the "atom" rule, which defines both list displays and
> list comprehensions (as well as literals) as being atoms.
> Specifically, it parses () as the token '(', followed by an optional
> yield_expr or testlist_comp, followed by the token ')'. In no way is
> that a single token, nor therefore a literal.

I think limiting literals to lexical tokens is too limited. Sure we
can define them like that in the context of the python grammar, but
I don't see why we should limit ourselves to such a definition outside
that context.

I see nothing wrong with regarding -42 as a literal while according
to the python grammar it isn't.

There is nothing wrong with the notion that a literal can be a
compounded value.

But no matter what you want to call it. The dis module shows that
-42 is treated in exactly the same way as 42, which is treated
exactly the same way as () or as (5, 8, 13) which is treated
differently from [] or [5, 8, 13].

Whether you want to call it literals or something else, the fact
remains that (3, 5, 8) is treated like -42 by the CPython interpreter
and [3, 5, 8] is not.

-- 
Antoon.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ned Batchelder
On Tuesday, November 24, 2015 at 1:45:34 PM UTC-5, Antoon Pardon wrote:
> Whether you want to call it literals or something else, the fact
> remains that (3, 5, 8) is treated like -42 by the CPython interpreter
> and [3, 5, 8] is not.

Maybe I've lost the original point in all this minutia about what is a
literal and what is not.  Isn't the key point here that some objects
are mutable (lists), and some are not (tuples, ints)?

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Random832
On 2015-11-24, Chris Angelico  wrote:
> Probably the grammar. In other words, it's part of the language's very
> definition.

Then the definition is wrong. I think "literal" is a word whose meaning is
generally agreed on, rather than something each language's spec can invent from
whole cloth for itself. It's not a python term, it's a programming term.

And the documentation doesn't even use it consistently; it calls {} a literal.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 11:45 AM, Antoon Pardon
 wrote:
> I think limiting literals to lexical tokens is too limited. Sure we
> can define them like that in the context of the python grammar, but
> I don't see why we should limit ourselves to such a definition outside
> that context.
>
> I see nothing wrong with regarding -42 as a literal while according
> to the python grammar it isn't.
>
> There is nothing wrong with the notion that a literal can be a
> compounded value.

I'm somewhat inclined to agree with this. Taking an example from
another language, if you use Javascript you'll hear all the time about
"object literals" or "object literal notation". If you read the
ECMAScript spec, however, you won't find the phrase "object literal"
in there once. It seems that the common usage of "literal" is not the
same as the way it's used in formal writing of language
specifications.

> But no matter what you want to call it. The dis module shows that
> -42 is treated in exactly the same way as 42, which is treated
> exactly the same way as () or as (5, 8, 13) which is treated
> differently from [] or [5, 8, 13].

This is an implementation detail. The compiler would also be free to
compile -42 into byte code as the negation of the constant 42. That 42
is a literal, on the other hand, is part of the language
specification.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 12:00 PM, Random832  wrote:
> On 2015-11-24, Chris Angelico  wrote:
>> Probably the grammar. In other words, it's part of the language's very
>> definition.
>
> Then the definition is wrong. I think "literal" is a word whose meaning is
> generally agreed on, rather than something each language's spec can invent 
> from
> whole cloth for itself. It's not a python term, it's a programming term.

The Python language spec uses the word the same way that other
language specs do. Is it the spec's usage that is wrong, or the common
understanding of it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Marko Rauhamaa
Steven D'Aprano :

> On Wed, 25 Nov 2015 05:13 am, Marko Rauhamaa wrote:
>> I would prefer this wording:
>> 
>> Objects whose inner state can change are said to be mutable
>
> I see your point, but "inner state" might not be related to the
> object's externally visible value.

The inner state is indeed inaccessible. We cannot determine immutability
by testing, but we *can* determine mutability (if we're lucky).

> For example, dicts have an inner state which can vary, even when their value
> remains the same:
>
> # using Python 3.3
>
> py> d = {-1: "a", -2: "b"}
> py> e = {-2: "b", -1: "a"}
> py> d == e
> True
> py> print(d, e)
> {-2: 'b', -1: 'a'} {-1: 'a', -2: 'b'}
>
> The two dicts have the same value, but their inner state is slightly
> different, which is why they print in different order.

I'd say an object o is mutable (at least) if it has got a method m such
that:

before = o.m()
# any intervening code that does not reassign o
after = o.m()
before == after
=> False


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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Zachary Ware
On Tue, Nov 24, 2015 at 12:37 PM, Marc Aymerich  wrote:
> still it appears to work only if the main thread is in the foreground
> (as of calling Thread() with deamon=True), I don't get why it behaves
> differently :( maybe it is waiting for other stuff, but no idea how to
> confirm this with strace of other means.. i always see the same
> 'futex(0x7f9a7c10, FUTEX_WAIT_PRIVATE, 0, NULL'

What's your exact version of Python?  asyncio is still evolving
rapidly, and may behave differently between patch releases (say,
between 3.4.1 and 3.4.3).

I have tried out your reproducer with my fix, and I can't provoke a
hang using Python 3.4.3 on either OSX or Ubuntu Trusty.  Can you give
some more specific directions to reproduce?

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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
On Tue, Nov 24, 2015 at 8:41 PM, Zachary Ware
 wrote:
> On Tue, Nov 24, 2015 at 12:37 PM, Marc Aymerich  wrote:
>> still it appears to work only if the main thread is in the foreground
>> (as of calling Thread() with deamon=True), I don't get why it behaves
>> differently :( maybe it is waiting for other stuff, but no idea how to
>> confirm this with strace of other means.. i always see the same
>> 'futex(0x7f9a7c10, FUTEX_WAIT_PRIVATE, 0, NULL'
>
> What's your exact version of Python?  asyncio is still evolving
> rapidly, and may behave differently between patch releases (say,
> between 3.4.1 and 3.4.3).
>
> I have tried out your reproducer with my fix, and I can't provoke a
> hang using Python 3.4.3 on either OSX or Ubuntu Trusty.  Can you give
> some more specific directions to reproduce?
>
> --
> Zach
> --
> https://mail.python.org/mailman/listinfo/python-list


Yep, I'm a bit lost about how fuse implements going into background...
so the only way I have to reproduce this so far is by using fuse :(

# pip3 install fusepy
import asyncio
import threading
import time
import os
import sys
from fuse import FUSE, Operations

def run_loop(loop_container):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
coro = asyncio.start_server(lambda: 1, '0.0.0.0', , loop=loop)
server = loop.run_until_complete(coro)
loop_container['loop'] = loop
loop.run_forever()

if __name__ == '__main__':
mountpoint = sys.argv[1]
loop_container = {}
handler = threading.Thread(target=run_loop, args=(loop_container,))
handler.start()
try:
# with foreground=True works
FUSE(Operations(), mountpoint, foreground=False)
finally:
loop_container['loop'].call_soon_threadsafe(loop_container['loop'].stop)


$ mkdir /tmp/
$ python3.5 /tmp/eventtest.py /tmp/

# Another terminal
$ ps aux | grep python3.5
glic319983  0.5  0.1 215540 10772 ?Ssl  21:05   0:00
python3.5 me.py /tmp/
$ sudo strace -p 19983
Process 19983 attached - interrupt to quit
futex(0x7fff42affca0, FUTEX_WAIT_PRIVATE, 0, NULL) = 0

# Here i fire
$ fusermount -u /tmp/

tgkill(19983, 19985, SIGRTMIN)  = 0
futex(0x7fff42affc30, FUTEX_WAKE_PRIVATE, 1) = 0
futex(0x7f9840afc9d0, FUTEX_WAIT, 19984, NULL


I've just tried with python3.5 and the same behavior. The thing is
that with foreground=True it just works.
thank you for your time!

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


Re: Futex hang when running event loop on a separated thread

2015-11-24 Thread Marc Aymerich
On Tue, Nov 24, 2015 at 9:17 PM, Marc Aymerich  wrote:
> On Tue, Nov 24, 2015 at 8:41 PM, Zachary Ware
>  wrote:
>> On Tue, Nov 24, 2015 at 12:37 PM, Marc Aymerich  wrote:
>>> still it appears to work only if the main thread is in the foreground
>>> (as of calling Thread() with deamon=True), I don't get why it behaves
>>> differently :( maybe it is waiting for other stuff, but no idea how to
>>> confirm this with strace of other means.. i always see the same
>>> 'futex(0x7f9a7c10, FUTEX_WAIT_PRIVATE, 0, NULL'
>>
>> What's your exact version of Python?  asyncio is still evolving
>> rapidly, and may behave differently between patch releases (say,
>> between 3.4.1 and 3.4.3).
>>
>> I have tried out your reproducer with my fix, and I can't provoke a
>> hang using Python 3.4.3 on either OSX or Ubuntu Trusty.  Can you give
>> some more specific directions to reproduce?
>>
>> --
>> Zach
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>
>
> Yep, I'm a bit lost about how fuse implements going into background...
> so the only way I have to reproduce this so far is by using fuse :(
>
> # pip3 install fusepy
> import asyncio
> import threading
> import time
> import os
> import sys
> from fuse import FUSE, Operations
>
> def run_loop(loop_container):
> loop = asyncio.new_event_loop()
> asyncio.set_event_loop(loop)
> coro = asyncio.start_server(lambda: 1, '0.0.0.0', , loop=loop)
> server = loop.run_until_complete(coro)
> loop_container['loop'] = loop
> loop.run_forever()
>
> if __name__ == '__main__':
> mountpoint = sys.argv[1]
> loop_container = {}
> handler = threading.Thread(target=run_loop, args=(loop_container,))
> handler.start()
> try:
> # with foreground=True works
> FUSE(Operations(), mountpoint, foreground=False)
> finally:
> 
> loop_container['loop'].call_soon_threadsafe(loop_container['loop'].stop)
>
>
> $ mkdir /tmp/
> $ python3.5 /tmp/eventtest.py /tmp/
>
> # Another terminal
> $ ps aux | grep python3.5
> glic319983  0.5  0.1 215540 10772 ?Ssl  21:05   0:00
> python3.5 me.py /tmp/
> $ sudo strace -p 19983
> Process 19983 attached - interrupt to quit
> futex(0x7fff42affca0, FUTEX_WAIT_PRIVATE, 0, NULL) = 0
>
> # Here i fire
> $ fusermount -u /tmp/
>
> tgkill(19983, 19985, SIGRTMIN)  = 0
> futex(0x7fff42affc30, FUTEX_WAKE_PRIVATE, 1) = 0
> futex(0x7f9840afc9d0, FUTEX_WAIT, 19984, NULL
>
>
> I've just tried with python3.5 and the same behavior. The thing is
> that with foreground=True it just works.
> thank you for your time!


In case this could be of some use:
strace using foreground=True

$ sudo strace -p 20326
Process 20326 attached - interrupt to quit
futex(0x7fffd9b8e5a0, FUTEX_WAIT_PRIVATE, 0, NULL
# Here umount command
) = 0
tgkill(20326, 20334, SIGRTMIN)  = 0
tgkill(20326, 20335, SIGRTMIN)  = 0
futex(0x7fffd9b8e530, FUTEX_WAKE_PRIVATE, 1) = 0
rt_sigaction(SIGHUP, NULL, {0x7fb60d850540, [], SA_RESTORER,
0x7fb61106ccb0}, 8) = 0
rt_sigaction(SIGINT, NULL, {0x7fb60d850540, [], SA_RESTORER,
0x7fb61106ccb0}, 8) = 0
rt_sigaction(SIGTERM, NULL, {0x7fb60d850540, [], SA_RESTORER,
0x7fb61106ccb0}, 8) = 0
rt_sigaction(SIGPIPE, NULL, {SIG_IGN, [], SA_RESTORER, 0x7fb61106ccb0}, 8) = 0
poll([{fd=5, events=0}], 1, 0)  = 1 ([{fd=5, revents=POLLERR}])
close(5)= 0
brk(0x126d000)  = 0x126d000
rt_sigaction(SIGINT, {0x50b380, [], SA_RESTORER, 0x7fb61106ccb0},
{0x7fb60d850540, [], SA_RESTORER, 0x7fb61106ccb0}, 8) = 0
sendto(8, "\0", 1, 0, NULL, 0)  = 1
futex(0x7fb61740, FUTEX_WAKE_PRIVATE, 1) = 1
futex(0x9d3204, FUTEX_WAKE_OP_PRIVATE, 1, 1, 0x9d3200, {FUTEX_OP_SET,
0, FUTEX_OP_CMP_GT, 1}) = 1
futex(0x9d31c0, FUTEX_WAKE_PRIVATE, 1)  = 1
futex(0x7fb60c10, FUTEX_WAIT_PRIVATE, 0, NULL) = 0
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7fb61106ccb0},
{0x50b380, [], SA_RESTORER, 0x7fb61106ccb0}, 8) = 0
epoll_ctl(4, EPOLL_CTL_DEL, 7,
{EPOLLWRBAND|EPOLLMSG|EPOLLERR|0xdea9800, {u32=32694,
u64=23586238107778998}}) = 0
close(7)= 0
close(8)= 0
close(4)= 0
getsockname(6, {sa_family=AF_INET, sin_port=htons(),
sin_addr=inet_addr("0.0.0.0")}, [16]) = 0
getpeername(6, 0x7fffd9b8dc70, [16])= -1 ENOTCONN (Transport
endpoint is not connected)
close(6)= 0
madvise(0x7fb600033000, 8192, MADV_DONTNEED) = 0
close(3)= 0
exit_group(0)   = ?
Process 20326 detached



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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 20:15 schreef Ian Kelly:

>> But no matter what you want to call it. The dis module shows that
>> -42 is treated in exactly the same way as 42, which is treated
>> exactly the same way as () or as (5, 8, 13) which is treated
>> differently from [] or [5, 8, 13].
> 
> This is an implementation detail. The compiler would also be free to
> compile -42 into byte code as the negation of the constant 42. That 42
> is a literal, on the other hand, is part of the language
> specification.

I think you are picking nits. Sure the byte code could compile -42 into
a byte code for 42 and a negation. Just as it could compile 42 into byte
code for adding 32, 8 and 2.

The point is, that the reverse isn't true. It couldn't compile [5, 8, 13]
into a LOAD_CONST.

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


import logging raise NotImplementedError

2015-11-24 Thread c.buhtz
I using 'logging' for some month.
But today I have strange problem. When importing it it fails.

Python 3.4.3 (default, Oct 14 2015, 20:33:09)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging  
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2237, in _find_and_load
  File "", line , in
_find_and_load_unlocked File "", line
2164, in _find_spec File "", line 1940, in
find_spec File "", line 1916, in _get_spec
  File "", line 1897, in _legacy_get_spec
  File "", line 863, in spec_from_loader
  File "", line 904, in
spec_from_file_location File
"/usr/local/lib/python3.4/dist-packages/logging-0.4.9.6-py3.4.egg/logging/__init__.py",
line 618 raise NotImplementedError, 'emit must be implemented '\ ^
SyntaxError: invalid syntax

Any idea about it?

I am not sure if there where an update in the background or something
changed.

The current situation make each "logging" using Python application
unable to run.

The problem happens with Python3 because "logging" is in the default
installation. In Python2 it is not installed. I installed it with
   sudo python2 -m pip install logging -U

This works without problems. Importing in Python2 works, too.
-- 
GnuPGP-Key ID 0751A8EC
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread BartC

On 24/11/2015 20:54, Antoon Pardon wrote:

Op 24-11-15 om 20:15 schreef Ian Kelly:


But no matter what you want to call it. The dis module shows that
-42 is treated in exactly the same way as 42, which is treated
exactly the same way as () or as (5, 8, 13) which is treated
differently from [] or [5, 8, 13].


This is an implementation detail. The compiler would also be free to
compile -42 into byte code as the negation of the constant 42. That 42
is a literal, on the other hand, is part of the language
specification.


I think you are picking nits. Sure the byte code could compile -42 into
a byte code for 42 and a negation. Just as it could compile 42 into byte
code for adding 32, 8 and 2.

The point is, that the reverse isn't true. It couldn't compile [5, 8, 13]
into a LOAD_CONST.


I think it can, with a couple of extra instructions:

LOAD_GLOBAL 0 (list)
LOAD_CONST  1 ((5, 8, 13))
CALL_FUNCTION

ie. by converting a tuple to a list, but it can also be done with a 
special byte-code. The effect is a that a constant list can be 
constructed without having to evalate each element at runtime, which I 
assume would be less efficient if the list is big enough (perhaps not 
for just 3 elements).


--
Bartc



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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 22:14 schreef BartC:
> On 24/11/2015 20:54, Antoon Pardon wrote:
>> Op 24-11-15 om 20:15 schreef Ian Kelly:
>>
 But no matter what you want to call it. The dis module shows that
 -42 is treated in exactly the same way as 42, which is treated
 exactly the same way as () or as (5, 8, 13) which is treated
 differently from [] or [5, 8, 13].
>>>
>>> This is an implementation detail. The compiler would also be free to
>>> compile -42 into byte code as the negation of the constant 42. That 42
>>> is a literal, on the other hand, is part of the language
>>> specification.
>>
>> I think you are picking nits. Sure the byte code could compile -42 into
>> a byte code for 42 and a negation. Just as it could compile 42 into byte
>> code for adding 32, 8 and 2.
>>
>> The point is, that the reverse isn't true. It couldn't compile [5, 8, 13]
>> into a LOAD_CONST.
> 
> I think it can, with a couple of extra instructions:

Sure it can with a couple of extra instructions. With extra instructions
you can always use constants to build a mutable. The point is that a
tuple can just be loaded as a constant without needing something extra.

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


Re: Bi-directional sub-process communication

2015-11-24 Thread Cameron Simpson

On 24Nov2015 06:33, israel  wrote:

On 11/23/2015 20:29, Cameron Simpson wrote:

On 24Nov2015 16:25, Cameron Simpson  wrote:

Completely untested example code:

class ReturnEvent:
 def __init__(self):
   self.event = Event()


With, of course:

  def wait(self):
return self.event.wait()


Of course :-) Ah, the Event() object comes from the threading module. 
That makes sense. This should work perfectly. Thanks so much for 
taking the time to help me out!


Glad to be of service,
Cameron Simpson 

All the doors in this ship have nice sunny dispositions. It is their pleasure 
to open for you, and their satisfaction to close with the knowledge of a job 
well done. - Marvin _The Hitchhiker's Guide to the Galaxy_

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Ian Kelly
On Tue, Nov 24, 2015 at 1:54 PM, Antoon Pardon
 wrote:
> Op 24-11-15 om 20:15 schreef Ian Kelly:
>
>>> But no matter what you want to call it. The dis module shows that
>>> -42 is treated in exactly the same way as 42, which is treated
>>> exactly the same way as () or as (5, 8, 13) which is treated
>>> differently from [] or [5, 8, 13].
>>
>> This is an implementation detail. The compiler would also be free to
>> compile -42 into byte code as the negation of the constant 42. That 42
>> is a literal, on the other hand, is part of the language
>> specification.
>
> I think you are picking nits.

Yes. This entire subtopic about literals is picking nits. :-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bi-directional sub-process communication

2015-11-24 Thread Ian Kelly
On Mon, Nov 23, 2015 at 10:25 PM, Cameron Simpson  wrote:
> Then #3. I would have a common function/method for submitting a request to
> go to the subprocess, and have that method return an Event on which to wait.
> Then caller then just waits for the Event and collects the data. Obviously,
> the method does not just return the Event, but an Event and something to
> receive the return data. I've got a class called a Result for this kind of
> thing; make a small class containing an Event and which will have a .result
> attribute for the return information; the submitting method allocates one of
> these and returns it. The response handler gets the instance (by looking it
> up from the tag), sets the .result attribute and fires the Event. Your
> caller wakes up from waiting on the Event and consults the .result
> attribute.

Your Result sounds suspiciously like a Future. ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: import logging raise NotImplementedError

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 7:27 AM,   wrote:
> The problem happens with Python3 because "logging" is in the default
> installation. In Python2 it is not installed. I installed it with
>sudo python2 -m pip install logging -U
>
> This works without problems. Importing in Python2 works, too.

You appear to have installed it into your Python 3.4's package
directory, so I suspect you didn't just use the command given. But
don't bother installing it in Py2 either - the docs say it's "New in
version 2.3", so unless you're supporting Python 2.2, you shouldn't
need to worry about this.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 6:00 AM, Random832  wrote:
> On 2015-11-24, Chris Angelico  wrote:
>> Probably the grammar. In other words, it's part of the language's very
>> definition.
>
> Then the definition is wrong. I think "literal" is a word whose meaning is
> generally agreed on, rather than something each language's spec can invent 
> from
> whole cloth for itself. It's not a python term, it's a programming term.
>
> And the documentation doesn't even use it consistently; it calls {} a literal.

Can you link to that, please? Maybe there's something that can be
improved. (Or maybe not.)

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


Re: Bi-directional sub-process communication

2015-11-24 Thread Cameron Simpson

On 24Nov2015 14:53, Ian Kelly  wrote:

On Mon, Nov 23, 2015 at 10:25 PM, Cameron Simpson  wrote:

Then #3. I would have a common function/method for submitting a request to
go to the subprocess, and have that method return an Event on which to wait.
Then caller then just waits for the Event and collects the data. Obviously,
the method does not just return the Event, but an Event and something to
receive the return data. I've got a class called a Result for this kind of
thing; make a small class containing an Event and which will have a .result
attribute for the return information; the submitting method allocates one of
these and returns it. The response handler gets the instance (by looking it
up from the tag), sets the .result attribute and fires the Event. Your
caller wakes up from waiting on the Event and consults the .result
attribute.


Your Result sounds suspiciously like a Future. ;-)


Yeah. I already had this stuff when the futures module was released, with some 
additional stuff futures didn't have (eg my dispatch queue is a priority queue, 
which is handy for some kinds of workflows; default dispatch is FIFO).


My commonest use case/instance is a LateFunction, returned from my Later class.  
Use:


 L = Later()
 LF = L.defer(cllable, *a, *kw)
 ...
 result = LF()

When you call a LateFunction you get the function result, blocking if it has 
not yet been run. It also raises if the deferred function raised. It has 
additional methods, but that is the core use: make it look like a function.


You can do other easy things like:

 L.after(LFs, callable, *a, **kw)

to have a function dispatched after the completion of other LateFunctions or:

 with L.ready():
   ... suite ...

to block until the Later has a slot, then run the suite.

My Result and LateFunctions are subclasses of an Asynchron base class, which 
lets you wait for the result to arrive and has the common methods (wait, etc).  
The Result class supports this:


 R = Result()

 # caller, blocks until value received
 value = R.result

 # worker: deliver result
 R.result = func(blah)

This makes thread cooperation far far more friendly.

Cheers,
Cameron Simpson 

Ride with a llama and you never ride alone.
- Jeff Earls, DoD #0530, 
--
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 06:00 am, Random832 wrote:

> On 2015-11-24, Chris Angelico  wrote:
>> Probably the grammar. In other words, it's part of the language's very
>> definition.
> 
> Then the definition is wrong. I think "literal" is a word whose meaning is
> generally agreed on, rather than something each language's spec can invent
> from whole cloth for itself. It's not a python term, it's a programming
> term.

Well, I don't know about that. According to you, and Ruby, this is a
literal:

[x+1, y+2*x, func(arg), MyClass(a, b)]

http://ruby-doc.org/core-2.1.1/doc/syntax/literals_rdoc.html#label-Arrays

which seems like an abuse of the term to me. How can it be a *literal* when
it contains non-literal expressions which aren't known until runtime?

Although I note that the actual examples of Array literals and Hash literals
in the Ruby docs punt on the issue by only showing expressions that could
be replaced by constants by a peephole optimizer.


Lua refers to *string literals* but *table constructors*:

http://www.lua.org/manual/5.1/manual.html

Apart from strings, the above manual avoids the use of "literal".



> And the documentation doesn't even use it consistently; it calls {} a
> literal.

Citation required.


-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 08:25 am, Antoon Pardon wrote:

> The point is that a
> tuple can just be loaded as a constant without needing something extra.


How would one load this tuple as a constant?

(myfile.read(), "%.5f" % sin(x or y))


The point is that *in general*, tuple so-called "literals" (what the docs
call displays) cannot be loaded as constants. If, and only if, the tuple
contains nothing but immutable constants e.g.

(1, 2.0, None, "spam")

then a sufficiently smart compiler may be able to treat that specific tuple
as a constant/literal. But that's a special case, and cannot be generalised
to all tuple displays.

All tuple so-called "literals" e.g. (), (1, 2), (x, y, z) etc. are
fundamentally expressions that *may* have to be built at runtime. Hence the
word "literal" is inappropriate.



-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Steven D'Aprano
On Wed, 25 Nov 2015 01:18 am, Ned Batchelder wrote:

> In English, "value" means something like, what is this equal to? 
> There isn't another good word to use in place of "value" here.

There are many different meanings for the English noun "value" (Websters
1913 dictionary includes ten), but I think that the only one that is
relevant is:

"Any particular quantitative determination".

although since we're not just talking about numbers even that needs to be
modified to allow qualitative as well as quantitative determination. E.g.
the value of a particular str object is the string "foobarbaz".


> 2) In Python, "value" means, what object does a name refer to, or what
> object did an evaluation produce.

I don't think that is correct.

The Docs clearly say that "value" is an attribute or quality of objects, not
a synonym for "object":

Quote: "Every object has an identity, a type and a value."

https://docs.python.org/2/reference/datamodel.html#objects-values-and-types

If the docs are a bit inconsistent in ensuring that "value" means something
that objects *have* rather than something that objects *are*, that may be
something to fix.



> The confusion over mutable default arguments arises because the
> defaulted argument always gets the same referent, but it might not
> always be the same evalue.


I'm not sure what value [ha, see what I did there?!] there is in inventing
two new words for things that we already have standard terms for.

"Referent" is just a funny way of saying "object", and "evalue" is just a
misspelling of "value".




-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Laura Creighton
In a message of Wed, 25 Nov 2015 11:39:54 +1100, "Steven D'Aprano" writes:
>I'm not sure what value [ha, see what I did there?!] there is in inventing
>two new words for things that we already have standard terms for.

Done correctly, you can get clarity.

>"Referent" is just a funny way of saying "object", and "evalue" is just a
>misspelling of "value".

If I had a time machine, I would go back to early days of Python and
ban the use of the term 'assignment' and 'value' both.  I would insist
that the term 'binding' be used instead, though if you want to use the
verb refer, to be synonymous with bind, well, I think that would work.
(If not, next trip with the time machine, I ban that one as well.)
Then you make it perfectly clear that what are bound are _objects_
not values (or evalues).  The object has an evalue, but it is the
object that is bound.

It is crystal clear than people on this list mean very different
things when they use the term 'value', and every one of them thinks
that Python agrees with them.  Cutting this knot may require a new
word.

Laura

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 11:36 AM, Steven D'Aprano  wrote:
> If, and only if, the tuple
> contains nothing but immutable constants e.g.
>
> (1, 2.0, None, "spam")
>
> then a sufficiently smart compiler may be able to treat that specific tuple
> as a constant/literal. But that's a special case, and cannot be generalised
> to all tuple displays.

In which case it's simply an example of constant-folding. It's the
same as (1+2j) being called up with LOAD_CONST, despite being an
expression. Recent CPythons are even willing to change what data type
something is, to make it a constant:

>>> dis.dis(lambda x: x in ["a","b","c","d","e"])
  1   0 LOAD_FAST0 (x)
  3 LOAD_CONST   6 (('a', 'b', 'c', 'd', 'e'))
  6 COMPARE_OP   6 (in)
  9 RETURN_VALUE
>>> dis.dis(lambda x: x in {"a","b","c","d","e"})
  1   0 LOAD_FAST0 (x)
  3 LOAD_CONST   6 (frozenset({'d', 'c', 'a',
'e', 'b'}))
  6 COMPARE_OP   6 (in)
  9 RETURN_VALUE

Lists and sets are definitely not constants. Tuples and frozensets
aren't literals, but they can be constant. This is the optimizer
talking, though, not language semantics.

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


ANN: released psutil 3.3.0 with OpenBSD support

2015-11-24 Thread Giampaolo Rodola'
Full story here:
http://grodola.blogspot.com/2015/11/openbsd-support-for-psutil.html

-- 
Giampaolo - http://grodola.blogspot.com
-- 
https://mail.python.org/mailman/listinfo/python-list


A name refers to an object, an object has a value, equality compares values (was: What is a function parameter =[] for?)

2015-11-24 Thread Ben Finney
Laura Creighton  writes:

> If I had a time machine, I would go back to early days of Python and
> ban the use of the term 'assignment' and 'value' both. I would insist
> that the term 'binding' be used instead, though if you want to use the
> verb refer, to be synonymous with bind, well, I think that would work.

+1

> (If not, next trip with the time machine, I ban that one as well.)

I've never been able to remember where the keys are kept; I'm sure they
keep being moved by previous drivers.

> It is crystal clear than people on this list mean very different
> things when they use the term 'value', and every one of them thinks
> that Python agrees with them. Cutting this knot may require a new
> word.

Indeed, in the past I used the term “value” as synonymous (in Python
context) with the term “object”. I have become convinced through this
discussion that I should no longer use the terms that way.

Instead, an object *has* a value at a point in time; if the object's
value can change, we say the object is mutable.

The syntax for literals describe a value, but the object once created
may change its value.

Typically, ‘is’ compares object identity; ‘==’ compares object value.

The concepts are distinct, so I apologise for misleadingly conflating
them in my terminology.

-- 
 \ “Skepticism is the highest duty and blind faith the one |
  `\   unpardonable sin.” —Thomas Henry Huxley, _Essays on |
_o__)   Controversial Questions_, 1889 |
Ben Finney

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


Reading files from .ar / .deb archives

2015-11-24 Thread Кисик Мурысик
Hello!
I'm new to Python, so I decided to learn it and write simple apt alternative 
(apt is somewhat broken for me).
But I can't decide - can I read just one file (/DEBIAN/control) from archive 
without unpacking it, or do I need to unpack? And what module I can use to 
handle .ar files? (I read in Wikipedia that .deb is just .ar archive with 
specific structure)

Sincerely, ヴ。
Sent from my Windows Phone
-- 
https://mail.python.org/mailman/listinfo/python-list


list slice and generators

2015-11-24 Thread Pavlos Parissis
Hi,

Do you see any possible dangerous hidden bug in the below code(using
python2.7 and python3.4)?

My goal is to avoid go through the metrics list twice. But, I don't
know if there will be a problem with doing in place replace of list
elements using 2 generators.

# metrics = ['', '0', '10']
metrics = [x.metric(name) for x in self._server_per_proc]
metrics[:] = (converter(x) for x in metrics)
metrics[:] = (x for x in metrics if x is not None)

return calculate(name, metrics)


def calculate(name, metrics):
 if not metrics:
return None

if name in METRICS_SUM:
return sum(metrics)
elif name in METRICS_AVG:
return int(sum(metrics)/len(metrics))
else:
raise ValueError("Unknown type of calculation for {}".format(name))


def converter(value):
try:
return int(float(value))
except ValueError:
return value.strip() or None
except TypeError:
return None


Cheers,
Pavlos



signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Istalling python

2015-11-24 Thread ARONA KANAGARATHNA via Python-list
I tried to install this software python 3.4.3 to my pc which run windows Xp 32. 
i could installed but it doesnot run.it gives this message 
"python35-32/python.exe isnot a valid win32 app.Please help me to get solved 
this problem
Thanks
Aruna
-- 
https://mail.python.org/mailman/listinfo/python-list


if else python

2015-11-24 Thread Scott Montreuil
Hi,

I have an if statement which seems to run both commands and I cannot figure out 
why. (just learning so I may be missing something obvious) Any ideas?

while True:
global latit,longt,jlatit,jlongt,mlongt,mlatit
response = urllib.urlopen(url)
data = json.loads(response.read())
latit = data['Data'][0]['Latitude']
longt = data['Data'][0]['Longitude']
jlatit = data['Data'][1]['Latitude']
jlongt = data['Data'][1]['Longitude']
mlatit = data['Data'][2]['Latitude']
mlongt = data['Data'][2]['Longitude']
for i in user1locat:
if float(i[2]) <= float(latit) <= float(i[3]) and float(i[4]) 
>= float(longt) >= float(i[5]):
newlocation = int(i[1])
   screen.addstr(7, 40, "%s at %s" %(user1, i[0]))
motor1thread = threading.Thread(target=motor1)
motor1thread.start()
screen.refresh()
else:
screen.addstr(5, 40, "%s is at an unknown location %f 
%f\n" % (user1, latit, longt))
newlocation = 200
motor1thread = threading.Thread(target=motor1)
motor1thread.start()
screen.refresh()
time.sleep(10)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Istalling python

2015-11-24 Thread Chris Angelico
On Wed, Nov 25, 2015 at 3:22 PM, ARONA KANAGARATHNA via Python-list
 wrote:
> I tried to install this software python 3.4.3 to my pc which run windows Xp 
> 32. i could installed but it doesnot run.it gives this message 
> "python35-32/python.exe isnot a valid win32 app.Please help me to get solved 
> this problem

It looks like you actually installed Python 3.5, not 3.4. If you get
3.4 installed successfully, it should work correctly. Better still,
upgrade to Windows 7, 8, or 10, or make the jump to a free operating
system, and start using something that's actually supported; XP is
going to become increasingly problematic as time goes on.

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


Re: A name refers to an object, an object has a value, equality compares values

2015-11-24 Thread Marko Rauhamaa
Ben Finney :

> Indeed, in the past I used the term “value” as synonymous (in Python
> context) with the term “object”. I have become convinced through this
> discussion that I should no longer use the terms that way.
>
> [...]
>
> The concepts are distinct, so I apologise for misleadingly conflating
> them in my terminology.

I don't think the meaning of the word "value" can be restricted in that
way. Let's try to "refactor" the examples I had found in the wild:

  "How to get the value of a variable given its name in a string"
  => How to get the object a variable is bound to given the name of the
 variable in a string

  "The value of some objects can change. Objects whose value can change
  are said to be mutable"
  [no change]

  "I'm taking the return value of one function and using it as the
  argument of another function"
  => I'm taking the return object of one function and using it as the
 argument of another function

  "Don't get confused — name on the left, value on the right"
  => Don't get confused — name on the left, object on the right

  "We can print the current value of the dictionary in the usual way"
  [no change]

  "A return statement ends the execution of the function call and
  "returns" the result, i.e. the value of the expression following the
  return keyword, to the caller"
  => A return statement ends the execution of the function call and
 "returns" the result, i.e. the resulting object of the expression
 following the return keyword, to the caller

  "When we ask python what the value of x > 5 is, we get False"
  => When we ask python what the resulting object of x > 5 is, we get
 False

  "To display the value of a variable, you can use a print statement"
  => To display the value of the object a variable is bound to, you can
 use a print statement

  "Get a value of a specified key"
  => Get an image object of a specified key

In a word, it's a lost cause.

It is actually somewhat comical how Python documentation tries, but
fails, to maintain terminological orthodoxy:

  A mapping object maps hashable values to arbitrary objects. [...]

  A dictionary’s keys are almost arbitrary values. Values that are not
  hashable, that is, values containing lists, dictionaries or other
  mutable types (that are compared by value rather than by object
  identity) may not be used as keys.

  [...]

  Dictionaries can be created by placing a comma-separated list of
  key: value pairs within braces

  [...]

  The first object of each item becomes a key in the new dictionary, and
  the second object the corresponding value. If a key occurs more than
  once, the last value for that key becomes the corresponding value in
  the new dictionary.

  [...]

  d[key] = value
Set d[key] to value.

  [...]

  values()
Return a new view of the dictionary’s values.

  https://docs.python.org/3/library/stdtypes.html?highlig
  ht=value#mapping-types-dict>


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


Re: Reading files from .ar / .deb archives

2015-11-24 Thread Ben Finney
Кисик Мурысик  writes:

> Hello!
> I'm new to Python, so I decided to learn it

Congratulations! Python is a fine language to learn, and this is the
place to discuss general Python topics.

You may also want to join the ‘tutor’ forum
https://mail.python.org/mailman/listinfo/tutor>, which is
specifically focussed on collaborative mentoring of Python newcomers.

> and write simple apt alternative (apt is somewhat broken for me).
> But I can't decide - can I read just one file (/DEBIAN/control) from
> archive without unpacking it, or do I need to unpack? And what module
> I can use to handle .ar files? (I read in Wikipedia that .deb is just
> .ar archive with specific structure)

You're right. The ‘ar’ archive format was IIUC chosen by the early
Debian project because it is very simple.

Unfortunately it is not widely supported; there is no standard library
support in Python for ‘ar’ archives.

You can use the third-party ‘python-debian’ library for reading Debian
archive files https://pypi.python.org/pypi/python-debian/>.

-- 
 \ “I know when I'm going to die, because my birth certificate has |
  `\   an expiration date.” —Steven Wright |
_o__)  |
Ben Finney

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


readline and TAB-completion?

2015-11-24 Thread Ulli Horlacher
I need an input function with GNU readline support. So far I have:

import readline
readline.parse_and_bind("tab: complete")

file = raw_input('File to send: ')


Cursor keys are working, but TAB-completion works only in the current
directory. Example:


File to send: [TAB][TAB]
argv.py  error.py md5b64.pyx.py
Python_Cookbook.pdf  bookmarksfexit.py murksigkeiten
_.py compile.py   https.py wcp

File to send: /tmp/[TAB][TAB]
argv.py  error.py md5b64.pyx.py
Python_Cookbook.pdf  bookmarksfexit.py murksigkeiten
_.py compile.py   https.py wcp


Is there a way to make TAB-completion work for other directories, too?

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [argparse] optional parameter without --switch

2015-11-24 Thread Peter Otten
c.bu...@posteo.jp wrote:

> I want to call (on bash) a Python script in this two ways without any
> error.
> 
> ./arg.py
> ./arg.py TEST
> 
> It means that the parameter (here with the value `TEST`) should be
> optional. With argparse I only know a way to create optional paramters
> when they have a switch (like `--name`).

$ cat tmp.py
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", nargs="?")
print("name =", parser.parse_args().name)
$ ./tmp.py
name = None
$ ./tmp.py 42
name = 42

https://docs.python.org/dev/library/argparse.html#nargs

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


Re: Problem to read from array

2015-11-24 Thread Crane Ugly
It is nothing more but naming convention. This code was part of the function.
Actually, in the final version I removed that "f" and changed some names of 
variables to shorter versions.
It is all about your own preferences towards readability of the code and 
ability of visual capture of the code. I always try to have code that easy to 
read. At least for myself.

CU

> What is the significance of prefixing all your variables with "f"?  I've 
> frequently seen people use it to > signify the variable is a float, but 
> you're using it for things that aren't floats.
-- 
https://mail.python.org/mailman/listinfo/python-list


Persistent api-ms-win-crt-runtime-i1-1-0.dll start up error

2015-11-24 Thread Tolga . Karabiyikoglu

Hi all;

Yesterday just downloaded python-3.5.0-amd64 on windows10 running 
laptop- running flawless.


But my trouble is with my office desktop Windows Vista. Considering the 
processor diference, this time, downloaded the python-3.5.0 (32 bit) 
version.
The question is i am receiving 'api-ms-win-crt-runtime-i1-1-0.dll is 
missing' error on the start up. I think i did update my Visual C++ 
Redistributable gear downloading and running vcredist_x86.exe (32 bit)  
but could not get rid off the error.


Do you have any other recipe for me
--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem to read from array

2015-11-24 Thread Peter Otten
Crane Ugly wrote:

> I always try to have code that easy to read. 

That's laudable, code is a means of communication.

> At least for myself.

and only for yourself, unfortunately.

Recommended read:

https://www.python.org/dev/peps/pep-0008/


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


Re: Persistent api-ms-win-crt-runtime-i1-1-0.dll start up error

2015-11-24 Thread Laura Creighton
In a message of Tue, 24 Nov 2015 10:56:32 +0200, tolga.karabiyiko...@ankara.edu
.tr writes:
>Hi all;
>
>Yesterday just downloaded python-3.5.0-amd64 on windows10 running 
>laptop- running flawless.
>
>But my trouble is with my office desktop Windows Vista. Considering the 
>processor diference, this time, downloaded the python-3.5.0 (32 bit) 
>version.
>The question is i am receiving 'api-ms-win-crt-runtime-i1-1-0.dll is 
>missing' error on the start up. I think i did update my Visual C++ 
>Redistributable gear downloading and running vcredist_x86.exe (32 bit)  
>but could not get rid off the error.
>
>Do you have any other recipe for me
>-- 
>https://mail.python.org/mailman/listinfo/python-list

Yes.

You appear to have this problem.

https://bugs.python.org/issue25223

Installing http://www.microsoft.com/en-us/download/details.aspx?id=48234
directly seems to fix it.

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


Returning a result from 3 items in a list

2015-11-24 Thread Cai Gengyang
Here's a dictionary with 3 values : 

results = {
  "gengyang": 14,
  "ensheng": 13,
  "jordan": 12
}

How do I define a function that takes the last of the 3 items in that list and 
returns Jordan's results i.e. (12) ?

Thanks a lot !

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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Chris Angelico
On Tue, Nov 24, 2015 at 9:04 PM, Cai Gengyang  wrote:
> Here's a dictionary with 3 values :
>
> results = {
>   "gengyang": 14,
>   "ensheng": 13,
>   "jordan": 12
> }
>
> How do I define a function that takes the last of the 3 items in that list 
> and returns Jordan's results i.e. (12) ?
>
> Thanks a lot !

If you want Jordan's result, that's easy:

result["jordan"]

But there's no concept of "the last" entry in a dict. They don't have
an order. Do you mean "the entry with the greatest key"? That could be
written thus:

result[max(result)]

because max(result) is the string "jordan".

Does either of those make sense for what you're doing?

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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Cai Gengyang
Strange, it gives me an error message when i type result["jordan"] or 
result[max(result)] though :

>>> results = { 
  "gengyang": 14, 
  "ensheng": 13, 
  "jordan": 12 
} 

>>> result["jordan"]
Traceback (most recent call last):
  File "", line 1, in 
result["jordan"]
NameError: name 'result' is not defined

>>> result[max(result)]
Traceback (most recent call last):
  File "", line 1, in 
result[max(result)]
NameError: name 'result' is not defined
>>> 


On Tuesday, November 24, 2015 at 6:14:43 PM UTC+8, Chris Angelico wrote:
> On Tue, Nov 24, 2015 at 9:04 PM, Cai Gengyang  wrote:
> > Here's a dictionary with 3 values :
> >
> > results = {
> >   "gengyang": 14,
> >   "ensheng": 13,
> >   "jordan": 12
> > }
> >
> > How do I define a function that takes the last of the 3 items in that list 
> > and returns Jordan's results i.e. (12) ?
> >
> > Thanks a lot !
> 
> If you want Jordan's result, that's easy:
> 
> result["jordan"]
> 
> But there's no concept of "the last" entry in a dict. They don't have
> an order. Do you mean "the entry with the greatest key"? That could be
> written thus:
> 
> result[max(result)]
> 
> because max(result) is the string "jordan".
> 
> Does either of those make sense for what you're doing?
> 
> ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Returning a result from 3 items in a list

2015-11-24 Thread Peter Otten
Cai Gengyang wrote:

> Here's a dictionary with 3 values :
> 
> results = {
>   "gengyang": 14,
>   "ensheng": 13,
>   "jordan": 12
> }
> 
> How do I define a function that takes the last of the 3 items in that list
> and returns Jordan's results i.e. (12) ?
> 
> Thanks a lot !

You can access the last item in a *list* with items[-1]:

>>> results = [
... ("gengyang", 14),
... ("ensheng", 13),
... ("jordan", 12)
... ]
>>> results[-1]
('jordan', 12)

A *dict* is unordered (the order is undefined, to be exact), so there is no 
"last" item. For the rare case when you need both order and fast lookup 
there's collections.OrderedDict:

>>> results = collections.OrderedDict([
... ("gengyang", 14),
... ("ensheng", 13),
... ("jordan", 12)
... ])

Get the last value non-destructively:

>>> results[next(reversed(results))] # is there a less tedious way?
12

Get the last pair, removing it from the dictionary:

>>> results.popitem(last=True)
('jordan', 12)
>>> "jordan" in results
False


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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Peter Otten
Cai Gengyang wrote:

> Strange, it gives me an error message when i type result["jordan"] or
> result[max(result)] though :
> 
 results = {
>   "gengyang": 14,
>   "ensheng": 13,
>   "jordan": 12
> }
> 
 result["jordan"]
> Traceback (most recent call last):
>   File "", line 1, in 
> result["jordan"]
> NameError: name 'result' is not defined

Yeah, the error message really should be

"NameError: name 'result' is not defined; did you mean 'results'?"

;)

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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Cai Gengyang
Yup, thanks a lot ... it works now !

>>> results = {
  "gengyang": 14,
  "ensheng": 13,
  "jordan": 12
  }
>>> results["jordan"]
12


On Tuesday, November 24, 2015 at 6:40:26 PM UTC+8, Peter Otten wrote:
> Cai Gengyang wrote:
> 
> > Strange, it gives me an error message when i type result["jordan"] or
> > result[max(result)] though :
> > 
>  results = {
> >   "gengyang": 14,
> >   "ensheng": 13,
> >   "jordan": 12
> > }
> > 
>  result["jordan"]
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > result["jordan"]
> > NameError: name 'result' is not defined
> 
> Yeah, the error message really should be
> 
> "NameError: name 'result' is not defined; did you mean 'results'?"
> 
> ;)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Persistent api-ms-win-crt-runtime-i1-1-0.dll start up error

2015-11-24 Thread eryksun
On Tue, Nov 24, 2015 at 3:54 AM, Laura Creighton  wrote:
> In a message of Tue, 24 Nov 2015 10:56:32 +0200, 
> tolga.karabiyiko...@ankara.edu
>
>>The question is i am receiving 'api-ms-win-crt-runtime-i1-1-0.dll is
>>missing' error on the start up.
>
> You appear to have this problem.
>
> https://bugs.python.org/issue25223
>
> Installing http://www.microsoft.com/en-us/download/details.aspx?id=48234
> directly seems to fix it.

For Vista the Universal CRT update requires service pack 2:

http://windows.microsoft.com/en-US/windows-vista/Learn-how-to-install-Windows-Vista-Service-Pack-2-SP2
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Cai Gengyang
results = {
  "gengyang": { "maths": 10, "english": 15},
  "ensheng": {"maths": 12, "english": 10},
  "jordan": {"maths": 9, "english": 13}
  }

How do you get gengyang's maths scores ?

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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Chris Angelico
On Tue, Nov 24, 2015 at 9:35 PM, Peter Otten <__pete...@web.de> wrote:
> Yeah, the error message really should be
>
> "NameError: name 'result' is not defined; did you mean 'results'?"
>
> ;)

Heh. Yes, that was my fault. Sorry Cai! it should have been
results["jordan"], as you figured out.

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


Re: Returning a result from 3 items in a list

2015-11-24 Thread Cai Gengyang
Its cool ... No problem 

On Tuesday, November 24, 2015 at 7:05:25 PM UTC+8, Chris Angelico wrote:
> On Tue, Nov 24, 2015 at 9:35 PM, Peter Otten <__pete...@web.de> wrote:
> > Yeah, the error message really should be
> >
> > "NameError: name 'result' is not defined; did you mean 'results'?"
> >
> > ;)
> 
> Heh. Yes, that was my fault. Sorry Cai! it should have been
> results["jordan"], as you figured out.
> 
> ChrisA

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


Re: tuples in conditional assignment

2015-11-24 Thread Steven D'Aprano
On Tue, 24 Nov 2015 02:25 pm, George Trojan wrote:

> The following code has bitten me recently:
> 
>  >>> t=(0,1)
>  >>> x,y=t if t else 8, 9
>  >>> print(x, y)
> (0, 1) 9
> 
> I was assuming that a comma has the highest order of evaluation, that is
> the expression 8, 9 should make a tuple. Why this is not the case?

I'm not sure what sort of answer you are looking for. Why does anything have
the precedence it has?

Making assumptions about the comma's precedence in that way seems unsafe to
me. Consider that function(a, b, c, d) is a function call with four
arguments, NOT a single 4-tuple argument. And:

py> 1, 2, 3 * 2  # expecting (1, 2, 3, 1, 2, 3)
(1, 2, 6)

So there's plenty of evidence that the comma has a very low order of
evaluation, not the highest, and it seems remarkably unsafe to assume the
opposite. Fortunately, it is very simple to test these things out at the
interactive interpreter. I cannot imagine doing any Python programming
without having a Python shell open and ready for me to try out code
snippets.



-- 
Steven

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


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Steven D'Aprano
On Tue, 24 Nov 2015 10:04 pm, Cai Gengyang wrote:

> results = {
>   "gengyang": { "maths": 10, "english": 15},
>   "ensheng": {"maths": 12, "english": 10},
>   "jordan": {"maths": 9, "english": 13}
>   }
> 
> How do you get gengyang's maths scores ?

Break the problem into two steps:

- get Gengyang's scores;

- then get the maths score:

scores = results['gengyang']
maths_score = scores['maths']


Now you can simplify the process:

maths_score = results['gengyang']['maths']



-- 
Steven

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 19-11-15 om 00:22 schreef Chris Angelico:
> On Thu, Nov 19, 2015 at 10:14 AM, BartC  wrote:
>> On 18/11/2015 22:11, Ian Kelly wrote:
>>>
>>> On Wed, Nov 18, 2015 at 2:08 PM, fl  wrote:

 Hi,

 I have tried the below function and find that it can remember the
 previous
 setting value to 'val'. I think the second parameter has something on
 this
 effect, but I don't know the name and function of '=[]' in this
 application.

 Could you explain a little to me?
 Thanks,


 def eList(val, list0=[]):
  list0.append(val)
  return list0
 list1 = eList(12)
 list1 = eList('a')
>>>
>>>
>>> The list0 parameter has a default value, which is [], an initially
>>> empty list. The default value is evaluated when the function is
>>> defined, not when it is called, so the same list object is used each
>>> time and changes to the list are consequently retained between calls.
>>
>>
>> That is really bizarre behaviour.
>>
>> So, looking at some source code, a default value for certain types is only
>> certain to be that value for the very first call of that function?
> 
> On the contrary, it is certain always to be that exact object.

No, he is talking about the value. Since the object can be mutated
and thus have an other value, his statement seems correct.

-- 
Antoon.

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


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Arie van Wingerden
print((results["gengyang"])["maths"])

2015-11-24 12:04 GMT+01:00 Cai Gengyang :

> results = {
>   "gengyang": { "maths": 10, "english": 15},
>   "ensheng": {"maths": 12, "english": 10},
>   "jordan": {"maths": 9, "english": 13}
>   }
>
> How do you get gengyang's maths scores ?
>
> Thank you ...
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Cai Gengyang
Great, it works! Thanks a lot ..

>>> results = {
  "gengyang": { "maths": 10, "english": 15},
  "ensheng": {"maths": 12, "english": 10},
  "jordan": {"maths": 9, "english": 13}
  }

>>> print((results["gengyang"])["maths"])
10

On Tue, Nov 24, 2015 at 7:10 PM, Arie van Wingerden 
wrote:

> print((results["gengyang"])["maths"])
>
> 2015-11-24 12:04 GMT+01:00 Cai Gengyang :
>
>> results = {
>>   "gengyang": { "maths": 10, "english": 15},
>>   "ensheng": {"maths": 12, "english": 10},
>>   "jordan": {"maths": 9, "english": 13}
>>   }
>>
>> How do you get gengyang's maths scores ?
>>
>> Thank you ...
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Chris Angelico
On Tue, Nov 24, 2015 at 10:36 PM, Antoon Pardon
 wrote:
>>> So, looking at some source code, a default value for certain types is only
>>> certain to be that value for the very first call of that function?
>>
>> On the contrary, it is certain always to be that exact object.
>
> No, he is talking about the value. Since the object can be mutated
> and thus have an other value, his statement seems correct.

With mutable objects, you can *never* depend on their values. Any time
ANY byte code gets executed, the value could change. That's why I have
never said anything about *values* of arg defaults - what you're
promised is that the *object* will be the same (so, I'm looking at its
identity, rather than its value). So it's not even certain to be that
value even for the first call:

def create_user(name, email, creation_time=datetime.datetime.now()):

Looks perfectly reasonable, right? And with late binding, sure! But
with early binding, this will probably NEVER be what you want. But
what if you have an object that always stringifies the current time?

class Now:
def __init__(self, fmt):
self.fmt = fmt
def __repr__(self):
return datetime.datetime.now().strftime(self.fmt)

def create_user(name, email, creation_time=Now("%Y%m%d%H%M%S")):

Voila! An object whose value dynamically represents the notion of
"Now", but where it makes fine sense to have the same object used
every time. Since the value changes every second, it (probably) won't
even have that value for the first call, yet the behaviour will be
correct.

His statement is still incorrect, in that the value is NEVER certain,
but the identity is ALWAYS certain. It happens to be the case for the
one example of lists that get mutated only in the function. It's about
as accurate as the statement that Python is pass-by-value for integers
but pass-by-reference for dictionaries.

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


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Mark Lawrence

On 24/11/2015 11:04, Cai Gengyang wrote:

results = {
   "gengyang": { "maths": 10, "english": 15},
   "ensheng": {"maths": 12, "english": 10},
   "jordan": {"maths": 9, "english": 13}
   }

How do you get gengyang's maths scores ?

Thank you ...



One way is to delete the scores for ensheng and jordan, only leaving 
those for gengyang, then extract the maths score.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Arie van Wingerden
Hi Mark, what use would that have? Please show your code ...

2015-11-24 13:15 GMT+01:00 Mark Lawrence :

> On 24/11/2015 11:04, Cai Gengyang wrote:
>
>> results = {
>>"gengyang": { "maths": 10, "english": 15},
>>"ensheng": {"maths": 12, "english": 10},
>>"jordan": {"maths": 9, "english": 13}
>>}
>>
>> How do you get gengyang's maths scores ?
>>
>> Thank you ...
>>
>>
> One way is to delete the scores for ensheng and jordan, only leaving those
> for gengyang, then extract the maths score.
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 19-11-15 om 13:45 schreef Steven D'Aprano:
> On Thu, 19 Nov 2015 10:41 pm, BartC wrote:
> 
> 
>> I expect the version with the default argument to be
>> exactly the same as the last lot of calls, namely for:
>>
>> fn()
>> fn()
>> fn()
>>
>> to be equivalent to:
>>
>> temp=[]
>> fn(temp)
>> temp=[]
>> fn(temp)
>> temp=[]
>> fn(temp)
> 
> Why on earth would you expect that?
> 
> I don't mean that it isn't sometimes useful. Of course it is sometimes
> useful, there's no doubt about that. But why would you expect the language
> to default to the *slow*, *expensive*, *complicated* behaviour instead of
> the *fast*, *cheap*, *simple* behaviour?

I would say because it is better understandable. The way default value
behave now, is just a little less surprising as when the following segment
of code would print: [1]

a = []
a.append(1)
b = []
print b

Let us not forget that the tutorial talks about Default Argument *Values*.
And also the language reference talks about precomputed *values*. What
we really get is a precomputed object.

> You already have one way to set the argument to a fresh list every time you
> call the function: put the code you want executed inside the body of the
> function. There's no need for a *second* way to get the same result.

Which is beside the point. The point is understandability.

> But if you want the default value to be evaluated exactly once, and once
> only, there is no real alternative to early binding. You could use a global
> variable, of course, but that is no solution -- that's a problem waiting to
> happen.

No more than the situation we have now. The situation we have now is a problem
waiting to happen too. Which is confirmed again and again. You are stacking
the deck by calling a possible alternative "a problem waiting to happen" while
ignoring the problems that happen with the current situation.


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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 24-11-15 om 13:07 schreef Chris Angelico:
> On Tue, Nov 24, 2015 at 10:36 PM, Antoon Pardon
>  wrote:
 So, looking at some source code, a default value for certain types is only
 certain to be that value for the very first call of that function?
>>>
>>> On the contrary, it is certain always to be that exact object.
>>
>> No, he is talking about the value. Since the object can be mutated
>> and thus have an other value, his statement seems correct.
> 
> With mutable objects, you can *never* depend on their values. Any time
> ANY byte code gets executed, the value could change. That's why I have
> never said anything about *values* of arg defaults.

Yes you have. You haven't mentioned them yourself. But when you contradict
the statement of someone and that person talked about values, then in
contradicting that statement you said something about values.

You then switching to talking about objects, just gives the impression
that object is a synonym for value.

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Marko Rauhamaa
Antoon Pardon :

> You then switching to talking about objects, just gives the impression
> that object is a synonym for value.

It isn't?


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


Finding scores from a list

2015-11-24 Thread Cai Gengyang

results = [
{"id": 1, "name": "ensheng", "score": 10},
{"id": 2, "name": "gengyang", "score": 12},
{"id": 3, "name": "jordan", "score": 5},
]

I want to find gengyang's score. This is what I tried :

>>> print((results["gengyang"])["score"])

but I got an error message instead :

Traceback (most recent call last):
  File "", line 1, in 
print((results["gengyang"])["score"])
TypeError: list indices must be integers, not str

Any ideas how to solve this? Thank you ..
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting math scores (Dictionary inside dictionary)

2015-11-24 Thread Mark Lawrence

On 24/11/2015 12:23, Arie van Wingerden wrote:

Hi Mark, what use would that have? Please show your code ...

2015-11-24 13:15 GMT+01:00 Mark Lawrence :


On 24/11/2015 11:04, Cai Gengyang wrote:


results = {
"gengyang": { "maths": 10, "english": 15},
"ensheng": {"maths": 12, "english": 10},
"jordan": {"maths": 9, "english": 13}
}

How do you get gengyang's maths scores ?

Thank you ...



One way is to delete the scores for ensheng and jordan, only leaving those
for gengyang, then extract the maths score.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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



1) I was being facetious.
2) How many times do people have to be asked not to top post here before 
they stop top posting?

3) I only have two things to say so this is superfluous.

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: What is a function parameter =[] for?

2015-11-24 Thread Antoon Pardon
Op 20-11-15 om 01:27 schreef Ned Batchelder:
> On Thursday, November 19, 2015 at 7:11:52 PM UTC-5, BartC wrote:
>> On 19/11/2015 22:55, Michael Torrie wrote:
>>> On 11/19/2015 02:21 PM, BartC wrote:
 (Python returns 42; so that means my languages are more dynamic than
 Python? That's hard to believe!)
>>>
>>> It tells me your language does late binding for default arguments, which
>>> does mean the default argument can dynamically change at call time,
>>> which would surprise me if I didn't know about it.  Either form of
>>> binding is acceptable, and I don't think it makes a language more or
>>> less dynamic.
>>
>> You get the expression that is specified, which can give different 
>> values at different times unless it involves only constants.
>>
>> It can't be exactly the same as writing an identical expression in place 
>> of the missing argument, as apparently different scopes come into play 
>> if names are involved.
>>
>> However I mainly use them for constant values. And [] is a constant 
>> value in my opinion.
>>
>> -- 
>> Bartc
> 
> You are not alone in being surprised by how mutable default values work.
> It is a topic that comes up in every "What's Bad About Python" discussion,
> and is a common question from new users of the language.
> 
> I can understand how you would view [] as a constant value.  It's true that
> it is an expression that produces a consistent value each time it is
> evaluated.  But that value is a list, and lists are mutable.  The examples
> here all use the .append() method on that value, which changes it.

I think that part of the problem is, that [] is not a constant object. So
that when you see a line like

ls = []

It behaves more lke

ls = [].copy()

than what you would expect with the normal python semantics.

-- 
Antoon

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


  1   2   >