Re: Useless expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Steven D'Aprano
On Monday 28 March 2016 23:18, BartC wrote:

> On 28/03/2016 02:24, Steven D'Aprano wrote:

>> Don't think about floats and ints and strings. Think of complex objects
>> with operator overloading. You're probably thinking of `x + y`. Instead,
>> think of things like:
>>
>> graph + node
>> database + table
> 
> There's theory, and there's practice.
[...]
> So no matter how many potentially useful counter-examples you can dig
> up, non-function-call expressions are still going to be highly unusual.
> And suspect.

Sure. If you want to call it a "code smell", no problem. It's not 
necessarily bad, but it's worth a second look.


> That's why it's not going to be much loss to disallow them /in that form/.

When you design your own language :-) feel free to design it that way. 
Python is designed differently. You don't have to agree with the decision, 
but that is the decision. The Python interpreter will accept any legal 
expression, and not try to guess which ones do and don't have side-effects, 
or which ones might be in error. Expressions include single names, so even 
they are allowed.

If you want stricter rules, use a linter.

 
> (There are also docstrings, but until yesterday I didn't even know they
> were also expressions. Wikipedia says this:
> 
> "Python docstrings appear as a string literal (not an expression) as the
> first statement following the definition of functions..."
> 
> so their status is a little unclear. 

I think what Wikipedia means is that you cannot use an expression that 
evaluates to a string as a docstring:


py> def f():
... "A string %s" % 23
... 
py> f.__doc__ is None
True


It must be a string literal.



-- 
Steve

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


Re: Useless expressions

2016-03-29 Thread Ben Finney
Steven D'Aprano  writes:

> On Monday 28 March 2016 23:18, BartC wrote:
>
> > (There are also docstrings, but until yesterday I didn't even know
> > they were also expressions. Wikipedia says this:
> > 
> > "Python docstrings appear as a string literal (not an expression) as
> > the first statement following the definition of functions..."
> > 
> > so their status is a little unclear.

Thanks for raising this, Bart.

> I think what Wikipedia means is that you cannot use an expression that
> evaluates to a string as a docstring

I agree. I have edited that section of the article, hopefully it is now
clearer:

Python

The common practice, of documenting a code object at the head of its
definition, is captured by the addition of docstring syntax in the
Python language.

The docstring for a Python code object (a module, class, or
function) is the first statement of that code object, immediately
following the definition (the 'def' or 'class' statement). The
statement must be a bare string literal, not any other kind of
expression. The docstring for the code object is available on that
code object's '__doc__' attribute.

[…]

https://en.wikipedia.org/wiki/Docstring#Python>

-- 
 \ “True greatness is measured by how much freedom you give to |
  `\  others, not by how much you can coerce others to do what you |
_o__)   want.” —Larry Wall |
Ben Finney

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


Re: Re-using TCL code from python over network

2016-03-29 Thread Karim



On 29/03/2016 07:20, [email protected] wrote:

Hi

We've a test automation framework written in TCL (including the automated test 
cases). We are evaluating shifting to Python and have a test framework in 
Python (including the automated test cases). Python provides a lot more 3rd 
party libraries that we'd like to make use of.

We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD and we've 
compiled it in-house. Compiling it to 64 bit or moving to a newer version is a 
massive task (since we've a lot of libraries - written in C and compiled as 
well as pure tcl).

Also, we are evaluating having this Python infrastructure on Linux (CentOS).

I've explored Python's Tkinter but it won't suit our case as it points to 
system installed TCL. I've also explored Python's subprocess (launch an 
interactive TCL shell remotely) and pexpect but none of them worked well for me 
to allow me to use TCL code interactively from Python.

I'd like to gather any ideas/experience around this. If anyone has tried a 
similar stuff before and can share his/her experience, I'd appreciate it.

Regards
Sharad


You can find below a partial example where I launch a python process 
from a tcl program to get data from python
which reads a database. You just have to get and compile tclpython 
(google is your best friend) which is a C interface
bridging python and tcl and allow to launch at most 5 python interpreter 
processes if I remember correctly. I used it during 4
years but I now I migrated all the TCL code to python one indeed I don't 
need it anymore. But it is useful to do the transition.


#!/usr/bin/env tclsh8.4

lappend auto_path $env(TCLPYTHON_PKG_PATH)
package require tclpython 4.1

namespace eval ops {
  namespace export initPython
  namespace export exitPython
...
  namespace export getDeviceDescription


}

proc ops::initPython {} {
# 
# @goal: Create the interpreter process and import python needed modules.
# @arg:  
# @return: 
# 
  variable interpreter
  set interpreter [python::interp new]
  $interpreter exec {from ops.tcl.pythontcl import to_string, 
to_list, to_dict, to_bool}

  
  $interpreter exec "opsdb = None"
  $interpreter exec "input_structure = dict()"
}

proc ops::exitPython {} {
# 
# @goal: Close the interpreter process.
# @arg:  
# @return: 
# 
  variable interpreter
  python::interp delete $interpreter
}

proc ops::getDeviceDescription { libName deviceName } {
# 
# @goal: get
# @arg:  
# @return:
# 
  variable interpreter
  $interpreter exec "d_s = to_string(getDeviceDescription(opsdb, 
'$libName', '$deviceName'))"


  eval "set value [$interpreter eval {d_s}]"
  return $value
}

Karim


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


Re: Meta Data

2016-03-29 Thread Nick
I did find a couple of patterns in Effective Python: 59 Specific Ways to Write 
Better Python (Effective Software Development).

Registering classes and a field example.

Thanks

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


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Steven D'Aprano
On Monday 28 March 2016 12:40, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> if condition:
>> print(1)
>> print(2)
>> else:
>> print(3)
>> print(4)
>> what value should it return? Justify your choice.
> 
> It could whatever value that the last call to print() returns.  Lisp
> has worked like that since the 1950's.

"Lisp did it" isn't much of a justification.

The point is that sticking a return value onto a conditional branch with two 
blocks is rather arbitrary. Why return the last value rather than the first? 
Why not return a list of all the values generated in the block? Or 
True/False depending on which branch was taken?

Or for that matter, a random number?

The point is that there's nothing intrinsically obvious or right about 
"return the value of the last statement in the block". 


>> What should be the return value of this statement?
>>
>> while True:
>> x += 1
>> if condition: break
> 
> It could return None, or break(val) could return val.

Another arbitrary choice. It *could* return anything. But what *should* it 
return?

An expression naturally and intrinsically should return the value the 
expression calculates. This is such a no-brainer that I feel stupid even 
writing it: "x+1" should return "x+1". It would be crazy to pick something 
else.

But a statement is a statement because it doesn't have a return value. To 
give it one, we have to more-or-less arbitrarily force it to have one, but 
that doesn't make it terribly natural.

del x

Should it return None? The string 'x'? How about the value that x had just 
before it was deleted? True if that allowed the value to be garbage 
collected, False if it wasn't? Or the other way around? None of these 
suggests feel either useful or obviously right.


>> I don't think that "every statement is an expression" is conceptually
>> simpler at all. I think it is more difficult to understand.
> 
> It hasn't been a problem in Lisp or its descendants, Erlang, Haskell,
> etc.  I don't know about Ruby or Javascript.

Maybe, maybe not. But certain statements, at least, are definitely a problem 
in C/C++ :

int war = false; if(war = true) { launchnuke(); }


The way I see it, all expressions are meaningful as statements (although 
possibly not terribly useful if they don't have side-effects) but not all 
statements are meaningful as expressions.

If other languages choose differently, well, that's their right to do so, 
but I don't agree with their choice. On the other hand, I am tempted by the 
thought of a language where all statements return 42.



>> But it is even harder to understand what it might mean for a while
>> loop to be a value, and the benefit of doing so seems significantly
>> less than compelling.
> 
> It means that you get to use an incredibly simple and beautiful
> evaluation model.  Have you ever used Lisp or Scheme?  Give it a try
> sometime.  Excellent free book:
>   https://mitpress.mit.edu/sicp/full-text/book/book.html

I've tried to get into Lisp a couple of times, and it doesn't speak to me. 
If you want my opinion, Forth has a more natural evaluation model.



-- 
Steve

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


Help me

2016-03-29 Thread Smith

https://github.com/githubdavide/ip-pubblico-send/blob/master/ip-pubblico.py
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re-using TCL code from python over network

2016-03-29 Thread sharad1087
@Christian: Thanks!
@Karim: Thanks. My requirement is to run tcl code from python. tclpython allows 
executing python code from tcl. "but I now I migrated all the TCL code to 
python one indeed" - did you re-write the TCL code in Python?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: repeat items in a list

2016-03-29 Thread Antonio Caminero Garcia
On Monday, March 28, 2016 at 11:26:08 PM UTC+2, Chris Angelico wrote:
> On Tue, Mar 29, 2016 at 4:30 AM, Rob Gaddi
>  wrote:
> > [email protected] wrote:
> >
> >> On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote:
> >>>
> >>> Or, if you want to "import operator" first, you can use 'operator.add'
> >>> instead of the lambda (but you _did_ ask for a one-liner ;)).
> >>>
> >>> Out of interest, why the fascination with one-liners?
> >>
> >> Thanks for your reply. Sometimes when I program in Python I think I am not 
> >> using the full capabilities of the language, so I want to know if there are
> >> more concise ways of doing things.
> >
> > Concise is only worth so much.  PEP20 tells us "Explicit is better than
> > implicit", "Simple is better than complex" and "If the implementation is
> > hard to explain, it's a bad idea".
> >
> > Python is a beautifully expressive language.  Your goal should not be to
> > write the minimum number of lines of code to accomplish the task.
> > Your goal should be to write the code such that your grandmother can
> > understand it.  That way, when you screw it up, you'll be able to easily
> > figure out where and how you did so.  Or failing that, you can get
> > grangran to show you.
> 
> Just out of interest, did you (generic you) happen to notice Mark's
> suggestion? It's a one-liner that nicely expresses the intention and
> accomplishes the goal:
> 
> yy = [aa for aa in xx for _ in range(nrep)]
> 
> It quietly went through without fanfare, but I would say this is the
> perfect solution to the original problem.
> 
> ChrisA

Of course that's definitely the most pythonic sol to this prob :)! Just wanted 
to point out the use of the operator "*" in lists.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Paul Rubin
Steven D'Aprano  writes:
> The point is that there's nothing intrinsically obvious or right about 
> "return the value of the last statement in the block". 

Strictly speaking it returns the value of the block itself.  The block
is usually evaluated by PROG which returns the last value of the block,
but you could also use PROG1 which uses the first value, or PROG2 which
uses the second value.

> I've tried to get into Lisp a couple of times, and it doesn't speak to me. 
> If you want my opinion, Forth has a more natural evaluation model.

You might like Factor then, www.factorcode.org .
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Chris Angelico
On Tue, Mar 29, 2016 at 7:26 PM, Steven D'Aprano
 wrote:
> del x
>
> Should it return None? The string 'x'? How about the value that x had just
> before it was deleted? True if that allowed the value to be garbage
> collected, False if it wasn't? Or the other way around? None of these
> suggests feel either useful or obviously right.

Returning the value x had just before being deleted is certainly
useful - consider the case where x is not a simple name but a
subscripting, which makes this into a destructive lookup. Saying
whether the object was garbage collected or not could also be useful,
but feels very low level.

But if Python were to make 'del' into an expression, the only
semantics needed would be for simple names. For everything else, the
value of 'del x[y]' or 'del x.y' would simply be 'whatever
__delitem__/__delattr__ returns'. And even for simple names, the
semantics could be defined by the enclosing scope's dictionary. It'd
be like Python's operators; yes, you normally expect "x < y" to return
a truthy or falsy value, and for most built-in types it'll return
either True or False, but you can return anything at all - including a
lazy evaluation object for a DSL. Someone could, for instance, make
"del User[42]" return a Query object which, when executed, deletes the
user with primary key 42.

(Note: I am not advocating this. Just saying what would, IMO, be
consistent with the rest of Python.)

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


Re: Re-using TCL code from python over network

2016-03-29 Thread Sharad Singla
Thanks. This is more of invoking python code from TCL. I am looking for the
other way round.

Curious, did you rewrite all your TCL code in python?

Regards
Sharad
On Mar 29, 2016 1:10 PM, "Karim"  wrote:

>
>
> On 29/03/2016 07:20, [email protected] wrote:
>
>> Hi
>>
>> We've a test automation framework written in TCL (including the automated
>> test cases). We are evaluating shifting to Python and have a test framework
>> in Python (including the automated test cases). Python provides a lot more
>> 3rd party libraries that we'd like to make use of.
>>
>> We use a pretty old version of TCL (8.4.5, 32 bit). It's on FreeBSD and
>> we've compiled it in-house. Compiling it to 64 bit or moving to a newer
>> version is a massive task (since we've a lot of libraries - written in C
>> and compiled as well as pure tcl).
>>
>> Also, we are evaluating having this Python infrastructure on Linux
>> (CentOS).
>>
>> I've explored Python's Tkinter but it won't suit our case as it points to
>> system installed TCL. I've also explored Python's subprocess (launch an
>> interactive TCL shell remotely) and pexpect but none of them worked well
>> for me to allow me to use TCL code interactively from Python.
>>
>> I'd like to gather any ideas/experience around this. If anyone has tried
>> a similar stuff before and can share his/her experience, I'd appreciate it.
>>
>> Regards
>> Sharad
>>
>
> You can find below a partial example where I launch a python process from
> a tcl program to get data from python
> which reads a database. You just have to get and compile tclpython (google
> is your best friend) which is a C interface
> bridging python and tcl and allow to launch at most 5 python interpreter
> processes if I remember correctly. I used it during 4
> years but I now I migrated all the TCL code to python one indeed I don't
> need it anymore. But it is useful to do the transition.
>
> #!/usr/bin/env tclsh8.4
>
> lappend auto_path $env(TCLPYTHON_PKG_PATH)
> package require tclpython 4.1
>
> namespace eval ops {
>   namespace export initPython
>   namespace export exitPython
> ...
>   namespace export getDeviceDescription
>
> 
> }
>
> proc ops::initPython {} {
> # 
> # @goal: Create the interpreter process and import python needed modules.
> # @arg:  
> # @return: 
> # 
>   variable interpreter
>   set interpreter [python::interp new]
>   $interpreter exec {from ops.tcl.pythontcl import to_string,
> to_list, to_dict, to_bool}
>   
>   $interpreter exec "opsdb = None"
>   $interpreter exec "input_structure = dict()"
> }
>
> proc ops::exitPython {} {
> # 
> # @goal: Close the interpreter process.
> # @arg:  
> # @return: 
> # 
>   variable interpreter
>   python::interp delete $interpreter
> }
>
> proc ops::getDeviceDescription { libName deviceName } {
> # 
> # @goal: get
> # @arg:  
> # @return:
> # 
>   variable interpreter
>   $interpreter exec "d_s = to_string(getDeviceDescription(opsdb,
> '$libName', '$deviceName'))"
>
>   eval "set value [$interpreter eval {d_s}]"
>   return $value
> }
>
> Karim
>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help me

2016-03-29 Thread Ben Finney
Smith  writes:

> [a URL]

You'll get better help if you:

* Summarise the problem briefly in the Subject field.

* Actually say anything useful in the message body.

-- 
 \ “My house is on the median strip of a highway. You don't really |
  `\notice, except I have to leave the driveway doing 60 MPH.” |
_o__)   —Steven Wright |
Ben Finney

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


error installing scipy on python 3.5, win 10 64 bit

2016-03-29 Thread Sinay Goldberg
   Please help
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Marko Rauhamaa
Steven D'Aprano :

> On Monday 28 March 2016 12:40, Paul Rubin wrote:
>
>> Steven D'Aprano  writes:
>>> if condition:
>>> print(1)
>>> print(2)
>>> else:
>>> print(3)
>>> print(4)
>>> what value should it return? Justify your choice.
>> 
>> It could whatever value that the last call to print() returns. Lisp
>> has worked like that since the 1950's.
>
> "Lisp did it" isn't much of a justification.

Actually, it would be in my books.

However, Scheme (a Lisp dialect) also has statements that don't return
any particular value. The (if) happens to be an example. Thus,

   (set! x (if #f 3))

Assigns *some* value to x, but the language leaves it open what that
value might be.

Guile (a Scheme implementation) actually provides a distinct
"unspecified" value, which it uses in cases where the language standard
leaves the value unspecified.

> The point is that there's nothing intrinsically obvious or right about
> "return the value of the last statement in the block".

No, but the semantics of a functional language become simpler when you
can assume that every continuation operates on a value.

Consequently, every function in Python returns a value as does every
function in Perl and every command in bash.

> I've tried to get into Lisp a couple of times, and it doesn't speak to
> me. If you want my opinion, Forth has a more natural evaluation model.

Forth, too, has nice, simple semantics. Forth has nothing but statements
that operate on the stack and occasionally cause some side effects.

Here's an example of how Python benefits from the functional model:
decorators. You can use the same decorators both for proper functions
and for procedures that ostensibly don't return a value. Python has
defined "None" to be the default return value for procedures so it is
legal to say,

a = f()

even if f doesn't return a value.

Unfortunately, Python made a bit of a bad choice in the default return
value. Now Python cannot perform effective tail recursion elimination.
If Python had left the default unspecified, tail recursion elimination
would be simple.

Python's choice benefits the interactive console, which doesn't print
out None values.


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


Re: Which are best, well-tested ways to create REST services, with Json, in Python?

2016-03-29 Thread Sven R. Kunze
Not heard of any but I can recommend django-restframework. We've got 
good experience with that.


On 28.03.2016 23:06, David Shi via Python-list wrote:

Has anyone done a recent reviews of creating REST services, in Python?
Regards.
David


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


[OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Peter Otten
Steven D'Aprano wrote:

> http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/

I was about to post that in a few years' time C# will acquire enough 
features to make code that follows the functional paradigm feasible in that 
language.

Then I noted that this was the 10th anniversary repost ;)

My question to those who know a bit of C#: what is the state-of-the-art 
equivalent to

"\n".join(foo.description() for foo in mylist
 if foo.description() != "")

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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze



On 29.03.2016 06:13, Michael Torrie wrote:

On 03/28/2016 06:44 PM, Steven D'Aprano wrote:

http://lukeplant.me.uk/blog/posts/why-learning-haskell-python-makes-you-a-worse-programmer/

I have the same problem as the writer.  Working in Python makes me
really dislike working in any other language!



Python = English


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


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 11:39, Peter Otten wrote:

My question to those who know a bit of C#: what is the state-of-the-art
equivalent to

"\n".join(foo.description() for foo in mylist
  if foo.description() != "")



Using LINQ, I suppose: 
https://en.wikipedia.org/wiki/Language_Integrated_Query

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


Re: newbie question

2016-03-29 Thread Sven R. Kunze



On 28.03.2016 17:34, ast wrote:


"Matt Wheeler"  a écrit dans le message de 
news:[email protected]...

On Thu, 24 Mar 2016 11:10 Sven R. Kunze,  wrote:


On 24.03.2016 11:57, Matt Wheeler wrote:
 import ast
 s = "(1, 2, 3, 4)"
 t = ast.literal_eval(s)
 t
> (1, 2, 3, 4)

I suppose that's the better solution in terms of safety.



It has the added advantage that the enquirer gets to import a module 
that

shares their name ;)



I had a look at that "ast" module doc, but I must admit that
I didn't understood a lot of things.


If there were a module "srkunze", I think, I would be equally surprised. ;)

Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re-using TCL code from python over network

2016-03-29 Thread Karim



On 29/03/2016 10:29, Sharad Singla wrote:


Thanks. This is more of invoking python code from TCL. I am looking 
for the other way round.


Curious, did you rewrite all your TCL code in python?

Regards
Sharad

On Mar 29, 2016 1:10 PM, "Karim" > wrote:




On 29/03/2016 07:20, [email protected]
 wrote:

Hi

We've a test automation framework written in TCL (including
the automated test cases). We are evaluating shifting to
Python and have a test framework in Python (including the
automated test cases). Python provides a lot more 3rd party
libraries that we'd like to make use of.

We use a pretty old version of TCL (8.4.5, 32 bit). It's on
FreeBSD and we've compiled it in-house. Compiling it to 64 bit
or moving to a newer version is a massive task (since we've a
lot of libraries - written in C and compiled as well as pure tcl).

Also, we are evaluating having this Python infrastructure on
Linux (CentOS).

I've explored Python's Tkinter but it won't suit our case as
it points to system installed TCL. I've also explored Python's
subprocess (launch an interactive TCL shell remotely) and
pexpect but none of them worked well for me to allow me to use
TCL code interactively from Python.

I'd like to gather any ideas/experience around this. If anyone
has tried a similar stuff before and can share his/her
experience, I'd appreciate it.

Regards
Sharad


You can find below a partial example where I launch a python
process from a tcl program to get data from python
which reads a database. You just have to get and compile tclpython
(google is your best friend) which is a C interface
bridging python and tcl and allow to launch at most 5 python
interpreter processes if I remember correctly. I used it during 4
years but I now I migrated all the TCL code to python one indeed I
don't need it anymore. But it is useful to do the transition.

#!/usr/bin/env tclsh8.4

lappend auto_path $env(TCLPYTHON_PKG_PATH)
package require tclpython 4.1

namespace eval ops {
  namespace export initPython
  namespace export exitPython
...
  namespace export getDeviceDescription


}

proc ops::initPython {} {
# 
# @goal: Create the interpreter process and import python needed
modules.
# @arg:  
# @return: 
# 
  variable interpreter
  set interpreter [python::interp new]
  $interpreter exec {from ops.tcl.pythontcl import
to_string, to_list, to_dict, to_bool}
  
  $interpreter exec "opsdb = None"
  $interpreter exec "input_structure = dict()"
}

proc ops::exitPython {} {
# 
# @goal: Close the interpreter process.
# @arg:  
# @return: 
# 
  variable interpreter
  python::interp delete $interpreter
}

proc ops::getDeviceDescription { libName deviceName } {
# 
# @goal: get
# @arg:  
# @return:
# 
  variable interpreter
  $interpreter exec "d_s = to_string(getDeviceDescription(opsdb,
'$libName', '$deviceName'))"

  eval "set value [$interpreter eval {d_s}]"
  return $value
}

Karim




Yes, part by part. In fact it was faster than expected thanks to python 
syntax.

TCL coding is heavier than python equivalent. I say that by experience.
My project involved 2 developers one pro TCL and myself pro Python.
We found the best deal for both. Now I am alone. This is the reason 
everything is now python.


But it was a good experience to learn TCL (weaknesses).

Karim

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


Re: Threading is foobared?

2016-03-29 Thread Sven R. Kunze

On 27.03.2016 05:01, Steven D'Aprano wrote:

Am I the only one who has noticed that threading of posts here is severely
broken? It's always been the case that there have been a few posts here and
there that break threading, but now it seems to be much more common.


I agree. Didn't we both already have a conversation about this? I 
thought it is my thunderbird messing things up.


Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re-using TCL code from python over network

2016-03-29 Thread Christian Gollwitzer

Am 29.03.16 um 09:40 schrieb Karim:

You can find below a partial example where I launch a python process
from a tcl program to get data from python
which reads a database. You just have to get and compile tclpython
(google is your best friend) which is a C interface
bridging python and tcl and allow to launch at most 5 python interpreter
processes if I remember correctly.


tclpython embeds a Python interpreter into Tcl as a module. Therefire, 
this will only work, if Tcl and Python use the same machine language 
(i.e. 32bit or 64bit) and run on the same machine. I understood from the 
OP, that he wants to run Tcl in 32 bit mode, and connect to it from 
Python running 64 bit on a different machine. Therefore, only a true 
networked solution will work. However if he can manage to get both into 
the same process, this will be a lot easier, as outlined by your solution.


Christian

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


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread BartC

On 29/03/2016 09:26, Steven D'Aprano wrote:

On Monday 28 March 2016 12:40, Paul Rubin wrote:




The point is that there's nothing intrinsically obvious or right about
"return the value of the last statement in the block".


But that's exactly what happens inside a typical function: you have 
linear sequence of statements, then you a have return statement: at the 
end. It's a common pattern.



while True:
 x += 1
 if condition: break


It could return None, or break(val) could return val.


Another arbitrary choice. It *could* return anything. But what *should* it
return?


It's up to you. Write it like this (not valid Python):

  while True: x+=1; if c: break; y

Now this is two statement, the loop, and 'y'. We now have a block, and 
because of the block rule, the value is y.




An expression naturally and intrinsically should return the value the
expression calculates. This is such a no-brainer that I feel stupid even
writing it: "x+1" should return "x+1". It would be crazy to pick something
else.


(This is in contradiction to what you say elsewhere, where:

  graph + node

may be procedural.)


But a statement is a statement because it doesn't have a return value.


Isn't an expression technically a statement in Python? Therefore a 
statement could have a value. But take this example:


 if cond1:   x=a1
 elif cond2: x=a2
 elif cond3: x=a3
 else:   x=a4

Clearly this would be better expressed as (not valid Python):

  x = if cond1:   a1
  elif cond2: a2
  elif cond3: a3
  else:   a4

So some kinds of statements could conceivably yield a useful value. (And 
each a1, a2 here could be a block or other statement yielding a value.)



To
give it one, we have to more-or-less arbitrarily force it to have one, but
that doesn't make it terribly natural.

del x

Should it return None? The string 'x'? How about the value that x had just
before it was deleted?


(Actually 'del is a rather odd language feature. And I can't figure out 
how it's implemented; how does it manage 'del x[i]'? Anyway that's 
another matter.)



True if that allowed the value to be garbage
collected, False if it wasn't? Or the other way around? None of these
suggests feel either useful or obviously right.


It doesn't need to give a useful value. Its 'value' lies in being able 
to have it in a sequence or block:


  z = del x; y


The way I see it, all expressions are meaningful as statements (although
possibly not terribly useful if they don't have side-effects) but not all
statements are meaningful as expressions.


Yes. But some are. To list a few statements that could return values 
(some are not part of Python):


- If-elif-else

- Switch and case select statements

- Block

- Increment

- Subroutine call

- Assignment

The rest can still usefully appear in a block. Python has a version of 
if-else that appears in an expression, but it has function-call. But why 
stop there?


Anyway this is all hypothetical, in case anyone thinks I'm pushing for a 
change in the language. I thought such a language was cool in the 1980s, 
but now will settle for a more conservative one even if it's not so elegant.


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


DSL design (was DSLs in perl and python)

2016-03-29 Thread Rustom Mody
On Saturday, March 19, 2016 at 7:37:52 AM UTC+5:30, Rustom Mody wrote:
> On Friday, March 18, 2016 at 6:52:53 PM UTC+5:30, Peter Otten wrote:
> > Rustom Mody wrote:
> > 
> > > On Friday, March 18, 2016 at 4:17:06 AM UTC+5:30, MRAB wrote:
> > >> Stick an "x" on the end of the regex: /something/x or s/old/new/x.
> > > 
> > > Thanks!
> > > 
> > > Is there somewhere a regexp 'introspection' API/capability available?
> > > 
> > > ie if the re looks like
> > > rexp = r"""
> > > # DSL (instantiation) for describing NYSE symbology
> > > ^
> > > (?P [A-Z]*) # The base scrip
> > > (?P   [.+-])? # Series type char
> > > (?P[A-Z])? # Series
> > > (?P   [#])?   # issued char indicator
> > > $  # Thats all (there should be!)
> > > """
> > > 
> > > I would like to know that the named-groups are
> > > {scrip, serchar, series, issued}
> > > without doing match/search etc
> > 
> > Is that a Perl or a Python question? If the latter:
> > 
> > >>> r = re.compile(rexp, re.VERBOSE)
> > >>> r.groupindex
> > {'serchar': 2, 'issuedc': 4, 'scrip': 1, 'series': 3}
> 
> Neat Thanks (and Jussi)

Thanks once again to Peter and Jussi.
With that groupindex pointer, this tiny dsl for re's is here
https://github.com/rusimody/redsl
[How BTW did you folks go about unearth that groupindex?? Dont see it in docs]

Comments welcome.
If people have comments on the python thats fine -- specifically if something
does not work, is unclear etc.

I am however more specifically interested in the DSL-design --
Can one clean/spruce that up?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: DSL design (was DSLs in perl and python)

2016-03-29 Thread Chris Angelico
On Wed, Mar 30, 2016 at 12:28 AM, Rustom Mody  wrote:
> Thanks once again to Peter and Jussi.
> With that groupindex pointer, this tiny dsl for re's is here
> https://github.com/rusimody/redsl
> [How BTW did you folks go about unearth that groupindex?? Dont see it in docs]

Depending on your version:

https://docs.python.org/2/library/re.html#re.RegexObject.groupindex
https://docs.python.org/3/library/re.html#re.regex.groupindex

You can find that by searching the docs for "?P", the syntax used in
the RE itself.

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


Re: Exclude every nth element from list?

2016-03-29 Thread Sven R. Kunze

On 26.03.2016 18:06, Peter Otten wrote:

beliavsky--- via Python-list wrote:


I can use x[::n] to select every nth element of a list. Is there a
one-liner to get a list that excludes every nth element?

del x[::n]

;)


Actually quite nice.
--
https://mail.python.org/mailman/listinfo/python-list


Re: DSL design (was DSLs in perl and python)

2016-03-29 Thread Jussi Piitulainen
Rustom Mody writes:

> [How BTW did you folks go about unearth that groupindex?? Dont see it
> in docs]

The following reveal its existence:

dir(re.compile(""))
help(re.compile(""))

But help only lists it as one of "data descriptors defined here" (in
Python 3.4.3). I think I just guessed from its name that it might be
relevant, and trying it out didn't immediately contradict the guess :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Finding methods, was Re: DSL design (was DSLs in perl and python)

2016-03-29 Thread Peter Otten
Rustom Mody wrote:

> [How BTW did you folks go about unearth that groupindex?? Dont see it in
> [docs]

While it's there

https://docs.python.org/dev/library/re.html#re.regex.groupindex

my personal search algorithm for this category of questions is mostly "I saw 
something like that before", then dir(some_obj) to find the candidates, then 
try the candidates in order of likelihood. If that fails use the source.

While you learn things you weren't looking for the disadvantage of that 
approach is that you sometimes miss the "obvious, first hit given by the 
search engine" answer.

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


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Antoon Pardon
Op 28-03-16 om 03:05 schreef Steven D'Aprano:
> On Mon, 28 Mar 2016 05:01 am, Marco S. wrote:
>
>> Steven D'Aprano wrote:
>>
>>> The point you might have missed is that treating lists as if they were
>>> mappings violates at least one critical property of mappings: that the
>>> relationship between keys and values are stable.
>>
>> This is true for immutable maps, but for mutable ones, you can simply do
> No, it is true for mutable maps too.
>
> When you add a new key:value to a dict, the other key:value pairs don't
> change. That is the whole point of a mapping! Of course you can
> deliberately change the value by re-assignment:
>
> map[key] = new_value
>
> but that's not what I'm talking about. When you add a NEW key, the OTHER
> keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which
> lacks that property is not a mapping.

I'm not sure I agree with that.

> The relationship between the index of a value and the value in a sequence is
> not stable. Inserting a new value can change the "key"(actually index) of
> some or all of the existing values.

Which is not simply adding a key. Inserting a new value is IMO more like
doing an update.

>  The whole point of sequences is that
> the position of values is NOT stable: they are intended to move around.

I find that language too strong. The lists I use are generally stable.
Does that mean I'm using lists in a way not intended.

>  You
> can sort them, reverse them, delete them, insert new values, and the others
> will move around to make room. If you think of the index as a key, this is
> completely the opposite behaviour of mappings.

Not really. IMO a mapping is just a surjective function and sometimes a
list is a perfectly fine way to implement such a function.

The point I think the OP tries to make is that sometimes you need to write
a function that takes a surjective function as argument and produces some
result, but you just don't care whether this function is implemented as
a map or as a sequence.

Suppose you want to know how many times each value occurs and want to
map that. As it is you have to write something like the following.

def count(l):
counted = defaultdict(int)
try:
itr = l.values()
except AttributeError:
itr = iter(l)
for v in itr:
counted[v] += 1
return counted

What would be the big problem if a values method would be available
on a list which returned the iterator and if an items method would
be like calling enumerate?

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


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Chris Angelico
On Wed, Mar 30, 2016 at 1:08 AM, Antoon Pardon
 wrote:
> Op 28-03-16 om 03:05 schreef Steven D'Aprano:
>> When you add a new key:value to a dict, the other key:value pairs don't
>> change. That is the whole point of a mapping! Of course you can
>> deliberately change the value by re-assignment:
>>
>> map[key] = new_value
>>
>> but that's not what I'm talking about. When you add a NEW key, the OTHER
>> keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which
>> lacks that property is not a mapping.
>
> I'm not sure I agree with that.

I am. The similarity between "mapping with integers as keys" and
"sequence" is that both of them can be subscripted. And that's fine;
Python lets you define __getitem__ in any way you like. OrderedDict is
somewhere between "sequence with associated keys" and "mapping with
inherent order", and there's no problem with that.

But the definition of a sequence, and likewise the definition of a
mapping, goes deeper than that. A sequence has *relative* stability;
if one item is at a lower index than another, it will continue to be
at a lower index, until you change one of those two items. Changes
elsewhere in the sequence might bring them closer together or push
them further apart, but one of them is still earlier in the sequence
than the other. A mapping, on the other hand, has *absolute*
stability. Any given key->value relationship is stable in and of
itself. If you stuff a thing into a dict under a particular key, you
expect to be able to get it back using that key, not some other.

Sure, you can use a tuple to represent an immutable mapping between
dense integers and values. And there are times when that's perfectly
acceptable - here's two ways of depicting the month lengths in a
non-leap year in the Gregorian calendar:

mapping = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9:
30, 10: 31, 11: 30, 12: 31}
sequence = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

Both of them let you look up 6 and get back that June has 30 days. The
sequence is forced to start from zero, but that's a small matter (and
if you number your months 0-11 instead of 1-12, no difference at all).
But the only operation these two data types truly share is
subscripting. If you want to be able to iterate over these in calendar
order, you don't switch out the dict for an OrderedDict - you use the
tuple. If you want to be able to use month names instead of numbers,
you don't mess around with the tuple - you use the dict.

The whole idea of making sequences and mappings more similar is highly
distasteful to me, and I've figured out why. It's the exact problem
with the PHP array - it's not sure whether to act as a mapping or a
sequence, and standard library functions can behave oddly in the
presence of all-numeric keys that aren't intended to be a sequence.
The two types are fundamentally different, and you almost never want
to treat them identically - at best, you want to have one specific
function that handles either type, and that's most cleanly handled
inside that function, not by adding mapping-like features to sequences
or vice versa.

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


Re: Re-using TCL code from python over network

2016-03-29 Thread sharad1087
Thanks Christian. You are right. Our TCL is 32 bit and runs on FreeBSD. We are 
planning to use Python (64 bit) on CentOS.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 12:18, Sven R. Kunze wrote:

On 29.03.2016 11:39, Peter Otten wrote:

My question to those who know a bit of C#: what is the state-of-the-art
equivalent to

"\n".join(foo.description() for foo in mylist
  if foo.description() != "")



Using LINQ, I suppose: 
https://en.wikipedia.org/wiki/Language_Integrated_Query


Friend of mine told me something like this:

String.Join("\n", mylist.Where(foo => 
!String.IsNullOrEmpty(foo.description)).Select(foo => foo.description))


[untested, but from what I know of quite correct]

Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Simple, fast responsive, secure way of creating REST services

2016-03-29 Thread David Shi via Python-list
Hello, Justin,
What you said is very interesting and useful.
I just wonder whether there are much simpler alternatives for fast, responsive, 
secure REST services.  Python at server-side.  It provides REST services.  Data 
exchange with the web--page.  Formatted XML or Json.
Ideally, it uses the least code.
Perhaps, some folks in this group have made great achievement for doing so, and 
would like to share with us.   Or, any excellent literature describes this?  I 
like articles which give insight into the nitty-gritty.
Looking forward to hearing from you.
Regards.
David
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Peter Otten
Sven R. Kunze wrote:

> On 29.03.2016 12:18, Sven R. Kunze wrote:
>> On 29.03.2016 11:39, Peter Otten wrote:
>>> My question to those who know a bit of C#: what is the state-of-the-art
>>> equivalent to
>>>
>>> "\n".join(foo.description() for foo in mylist
>>>   if foo.description() != "")
>>>
>>
>> Using LINQ, I suppose:
>> https://en.wikipedia.org/wiki/Language_Integrated_Query
> 
> Friend of mine told me something like this:
> 
> String.Join("\n", mylist.Where(foo =>
> !String.IsNullOrEmpty(foo.description)).Select(foo => foo.description))
> 
> [untested, but from what I know of quite correct]

Reformatting it a bit

String.Join(
"\n", 
mylist.Where(
foo => !String.IsNullOrEmpty(foo.description)
).Select(
foo => foo.description))

this looks like a variant of Python's

str.join(
   "\n",
   map(lambda foo: foo.description,
   filter(lambda foo: foo.description, mylist)))

Assuming it's type-safe and can perhaps reshuffle the where and select part 
into something optimised there is definitely progress.

But still, Python's generator expressions are cool..

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


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Sven R. Kunze

On 29.03.2016 18:05, Peter Otten wrote:

Reformatting it a bit

String.Join(
 "\n",
 mylist.Where(
 foo => !String.IsNullOrEmpty(foo.description)
 ).Select(
 foo => foo.description))

this looks like a variant of Python's

str.join(
"\n",
map(lambda foo: foo.description,
filter(lambda foo: foo.description, mylist)))

Assuming it's type-safe and can perhaps reshuffle the where and select part
into something optimised there is definitely progress.

But still, Python's generator expressions are cool..


Haha, sure. But don't get stuck there. Learn something new from time to 
time; even a new language.



Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: error installing scipy on python 3.5, win 10 64 bit

2016-03-29 Thread Rob Gaddi
Sinay Goldberg wrote:

>Please help

Alright, let's try making this an exercise for the student.  You're
asking a bunch of strangers on the Internet to take time out of their
day to fix your problems.  Is there, perhaps, any way that you could
make their task easier so as to reduce the size of your ask?  Some
snippets of information that you may have that might narrow down the
scope of "error" so that folks don't have to guess?

Don't get me wrong, "Please help" is super informative.  But maybe,
just maybe, you may be able to increase your contribution to this
conversation.  Think long and hard on it.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [stdlib-sig] Can imaplib be improved?

2016-03-29 Thread Random832
I'd posted this to [email protected] without realizing that that
list is mostly dead.

On Thu, Mar 24, 2016, at 22:33, Random832 wrote:
> I assume that everyone who has ever used imaplib is familiar with how
> painful its output format is to deal with. I am wondering if anyone else
> has any ideas on ways it can be extended in a backward-compatible way to
> provide options for better parsing, handling unilateral data from the
> server, processing data as it comes in, etc.

Anyone have any thoughts?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [stdlib-sig] Can imaplib be improved?

2016-03-29 Thread Grant Edwards
On 2016-03-29, Random832  wrote:
> I'd posted this to [email protected] without realizing that that
> list is mostly dead.
>
> On Thu, Mar 24, 2016, at 22:33, Random832 wrote:
>> I assume that everyone who has ever used imaplib is familiar with how
>> painful its output format is to deal with.

Yes.  Been there, done that, still have bald patches where I tore my
hair out.

>> I am wondering if anyone else has any ideas on ways it can be
>> extended in a backward-compatible way to provide options for better
>> parsing, handling unilateral data from the server, processing data
>> as it comes in, etc.

I think giving up on backwards compatiblity and starting from scratch
is the best idea.

I like imaplib2

https://pypi.python.org/pypi/imaplib2
https://github.com/bcoe/imaplib2
https://sourceforge.net/projects/imaplib2/

imapclient is pretty nice to work with:

 https://pypi.python.org/pypi/IMAPClient
 https://bitbucket.org/mjs0/imapclient
 http://freshfoo.com/presentations/imapclient-intro/#/

Perhaps it (or something like it) could be added to the std library
alongside the current imaplib.

-- 
Grant Edwards   grant.b.edwardsYow! I'm reporting for duty
  at   as a modern person.  I want
  gmail.comto do the Latin Hustle now!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [stdlib-sig] Can imaplib be improved?

2016-03-29 Thread Random832
On Tue, Mar 29, 2016, at 14:45, Grant Edwards wrote:
> I think giving up on backwards compatiblity and starting from scratch
> is the best idea.
> 
> I like imaplib2
> 
> https://pypi.python.org/pypi/imaplib2
> https://github.com/bcoe/imaplib2
> https://sourceforge.net/projects/imaplib2/
> 
> imapclient is pretty nice to work with:
> 
>  https://pypi.python.org/pypi/IMAPClient
>  https://bitbucket.org/mjs0/imapclient
>  http://freshfoo.com/presentations/imapclient-intro/#/
> 
> Perhaps it (or something like it) could be added to the std library
> alongside the current imaplib.

I couldn't get imapclient to install; I got some kind of error (I can't
remember, and can't reproduce now because it "thinks" it was successful)
from pip installing some crypto dependency, and a runtime error not
finding a SSLContext class. I haven't tried imaplib2 yet; by the time I
discovered it my scripts were already mature enough that I just finished
with what I had.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re-using TCL code from python over network

2016-03-29 Thread blacksqr
On Tuesday, March 29, 2016 at 5:24:37 AM UTC-5, Karim wrote:

> But it was a good experience to learn TCL (weaknesses).
> 
> Karim

I would be interested to know what you consider to be the top weaknesses of Tcl 
compared to Python which prompted your decision to switch.
-- 
https://mail.python.org/mailman/listinfo/python-list


Help with python code

2016-03-29 Thread okdk
This is my code
import random
import time

pizzatype = [3.50,4.20,5.20,5.80,5.60]
drinktype = [0.90,0.80,0.90]
topping = [0.50,0.50,0.50,0.50]

def Total_cost_cal (pt ,dt ,t):
total = pt + dt + t
return total

print ("Welcome to Pizza Shed!")

order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." )

tablenum = input ("Enter table number from 1-25 \n ")
while tablenum>25 or tablenum <=0:
tablenum = input ("Enter the correct table number, there are only 25 tables 
")

#Pizza menu with prices

print ("-")

print ("Let me help you with your order!")

print ("-")

order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." )

print ("Menu")

print (
"1 = cheese and tomato: 3.50, "
"2 = ham and pineapple: 4.20, "
"3 = vegetarian: 5.20, "
"4 = meat feast: 5.80, "
"5 = seafood: 5.60 " )

menu = input("Enter the type of pizza that you want to order from 1-5 \n")
while menu>5 or menu <=0:
menu = input ("Enter the right number ")
pizza_cost = pizzatype[menu]

print ("--")

pizza_amount = input ("Enter the amount of Pizzas that you want to order ")
while pizza_amount > 10 or pizza_amount <=0:
pizza_amount = input ("Maximum amount is 10, Please enter again ")

print ("")

#base

print ("Base")

print (
"1 = thin and crispy,"
"2 = traditional" )

base = input ("Select a base from 1-2 \n")
while base>2 or base<=0:
base = input ("There are only 2 types, Please enter again ")

print ("---")

#extra toppings

print ("Extra Toppings")

toppings = input ("Enter a number for your choice of extra topping \n Enter 1 
for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple 
\n Enter 4 for extra peppers \n" )
while toppings >4 or toppings < 0:
toppings = input ("There are only 4 types of extra toppings, Please try 
again " )
topping_cost = topping[toppings]

print ("-")

#drink

print ("Drink")

print (
"1 = Cola: 0.90, "
"2 = Lemonande: 0.80, "
"3 = Fizzy Orange: 0.90 "
)

drink = input ("Enter a number for your choice of drinks " )
while drink>3 or drink<0:
drink = input ("Choices start from 0 to 3 " )
drink_cost = drinktype[drink]
drink_amount = input ("Enter the amount of drinks")
while drink_amount >10 or drink_amount<0:
drink_amount = input (" You can only have upto 10 drinks, Please try again")


print ("")

pizzatotal = pizza_cost*pizza_amount
drinktotal = drink_cost*drink_amount

total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost)

print ("")
print ("Calculating bill")
print ("")
print ("")

print ("Thank You for ordering at Pizza Shed! ")


Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont know 
what to do, as I'm less than average at this.
it comes up as IndexError: list index out of range at line42

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


Re: Help with python code

2016-03-29 Thread BartC

On 29/03/2016 22:00, okdk wrote:


pizzatype = [3.50,4.20,5.20,5.80,5.60]
drinktype = [0.90,0.80,0.90]
topping = [0.50,0.50,0.50,0.50]



total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost)

print ("")
print ("Calculating bill")
print ("")
print ("")

print ("Thank You for ordering at Pizza Shed! ")


Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont know 
what to do, as I'm less than average at this.
it comes up as IndexError: list index out of range at line42


Those lists you define are indexed from 0, not 1 as you seem to assume. 
(So you get an index error if choosing pizza type 5).


You might try inserting a dummy 0 at the start (so the rest are indexed 
from 1), but better to change the logic.


Also total_cost_cal() is not defined anywhere. (And the user interface 
is generally untidy with poor error checking, but this can be cleaned up 
later.)


(I also found I was obliged to choose an extra topping. Suppose I don't 
want one? There is no option for that. Perhaps you can use option 0 for 
some of these, and that might help solve the indexing problem.)


--
Bartc


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


Re: Help with python code

2016-03-29 Thread Rob Gaddi
okdk wrote:

> This is my code
> import random
> import time
>
> pizzatype = [3.50,4.20,5.20,5.80,5.60]
> drinktype = [0.90,0.80,0.90]
> topping = [0.50,0.50,0.50,0.50]
>
> def Total_cost_cal (pt ,dt ,t):
> total = pt + dt + t
> return total
>
> print ("Welcome to Pizza Shed!")
>
> order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." )
>
> tablenum = input ("Enter table number from 1-25 \n ")
> while tablenum>25 or tablenum <=0:
> tablenum = input ("Enter the correct table number, there are only 25 
> tables ")
> 
> #Pizza menu with prices
>
> print ("-")
>
> print ("Let me help you with your order!")
>
> print ("-")
>
> order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." )
>
> print ("Menu")
>
> print (
> "1 = cheese and tomato: 3.50, "
> "2 = ham and pineapple: 4.20, "
> "3 = vegetarian: 5.20, "
> "4 = meat feast: 5.80, "
> "5 = seafood: 5.60 " )
>
> menu = input("Enter the type of pizza that you want to order from 1-5 \n")
> while menu>5 or menu <=0:
> menu = input ("Enter the right number ")
> pizza_cost = pizzatype[menu]
> 
> print ("--")
>
> pizza_amount = input ("Enter the amount of Pizzas that you want to order ")
> while pizza_amount > 10 or pizza_amount <=0:
> pizza_amount = input ("Maximum amount is 10, Please enter again ")
>
> print ("")
>
> #base
>
> print ("Base")
>
> print (
> "1 = thin and crispy,"
> "2 = traditional" )
>
> base = input ("Select a base from 1-2 \n")
> while base>2 or base<=0:
> base = input ("There are only 2 types, Please enter again ")
>
> print ("---")
>
> #extra toppings
>
> print ("Extra Toppings")
>
> toppings = input ("Enter a number for your choice of extra topping \n Enter 1 
> for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra 
> pineapple \n Enter 4 for extra peppers \n" )
> while toppings >4 or toppings < 0:
> toppings = input ("There are only 4 types of extra toppings, Please try 
> again " )
> topping_cost = topping[toppings]
>
> print ("-")
>
> #drink
>
> print ("Drink")
>
> print (
> "1 = Cola: 0.90, "
> "2 = Lemonande: 0.80, "
> "3 = Fizzy Orange: 0.90 "
> )
>
> drink = input ("Enter a number for your choice of drinks " )
> while drink>3 or drink<0:
> drink = input ("Choices start from 0 to 3 " )
> drink_cost = drinktype[drink]
> drink_amount = input ("Enter the amount of drinks")
> while drink_amount >10 or drink_amount<0:
> drink_amount = input (" You can only have upto 10 drinks, Please try 
> again")
> 
>
> print ("")
>
> pizzatotal = pizza_cost*pizza_amount
> drinktotal = drink_cost*drink_amount
>
> total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost)
>
> print ("")
> print ("Calculating bill")
> print ("")
> print ("")
>
> print ("Thank You for ordering at Pizza Shed! ")
>
>
> Howeve, it doesnt seem to be working. It doesnt calculate the bill. I dont 
> know what to do, as I'm less than average at this.
> it comes up as IndexError: list index out of range at line42
>
> Please help

Don't know which one is line 42; but I'd bet your problem is there.
As a rough guess, it might be the line that says:
  pizza_cost = pizzatype[menu]

You're bounding that to the range 1-5.  A Python list of length 5 has
indices 0-4.

But the error message is telling you everything you need to know; you're
trying to get a list index that's out of range in line 42. Find line
42, figure out what index you're asking it for, and you'll have your
answer. If you don't have an editor that shows you line numbers then
your editor is fundamentally terrible and you should not use it (I
personally like Notepad++ for Windows or Geany for Linux).

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: repeat items in a list

2016-03-29 Thread Vito De Tullio
Random832 wrote:

> How do you turn ['a', 'c', 'b'] into ['a', 'a', 'a', 'c', 'c', 'c', 'b',
> 'b', 'b']?

>>> sum([[e]*3 for e in ['a', 'c', 'b']], [])
['a', 'a', 'a', 'c', 'c', 'c', 'b', 'b', 'b']


-- 
By ZeD

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


Re: Help with python code

2016-03-29 Thread Yum Di
import random
import time

pizzatype = [3.50,4.20,5.20,5.80,5.60]
drinktype = [0.90,0.80,0.90]
topping = [0.50,0.50,0.50,0.50]

def Total_cost_cal (pt ,dt ,t):
total = pt + dt + t
return total

print ("Welcome to Pizza Shed!")

order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." )

tablenum = input ("Enter table number from 1-25 \n ")
while tablenum>25 or tablenum <=0:
tablenum = input ("Enter the correct table number, there are only 25 tables 
")

#Pizza menu with prices

print ("-")

print ("Let me help you with your order!")

print ("-")

order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." )

print ("Menu")

print (
"1 = cheese and tomato: 3.50, "
"2 = ham and pineapple: 4.20, "
"3 = vegetarian: 5.20, "
"4 = meat feast: 5.80, "
"5 = seafood: 5.60 " )

menu = input("Enter the type of pizza that you want to order from 1-5 \n")
while menu>5 or menu <=1:
menu = input ("Enter the right number ")
pizza_cost = pizzatype[menu]

print ("--")

pizza_amount = input ("Enter the amount of Pizzas that you want to order ")
while pizza_amount > 10 or pizza_amount <=0:
pizza_amount = input ("Maximum amount is 10, Please enter again ")

print ("")

#base

print ("Base")

print (
"1 = thin and crispy,"
"2 = traditional" )

base = input ("Select a base from 1-2 \n")
while base>2 or base<=1:
base = input ("There are only 2 types, Please enter again ")

if base_type == 1:
print "You have chosen thin and crispy"
elif base_type == 2:
print ("You have chosen traditional")

print ("---")

#extra toppings

print ("Extra Toppings")

toppings = input ("Enter a number for your choice of extra topping \n Enter 1 
for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple 
\n Enter 4 for extra peppers \n" )
while toppings >4 or toppings < 0:
toppings = input ("There are only 4 types of extra toppings, Please try 
again " )
topping_cost = topping[toppings]

print ("-")

#drink

print ("Drink")

print (
"1 = Cola: 0.90, "
"2 = Lemonande: 0.80, "
"3 = Fizzy Orange: 0.90 "
)

drink = input ("Enter a number for your choice of drinks " )
while drink>3 or drink<0:
drink = input ("Choices start from 0 to 3 " )
drink_cost = drinktype[drink]
drink_amount = input ("Enter the amount of drinks")
while drink_amount >10 or drink_amount<1:
drink_amount = input (" You can only have upto 10 drinks, Please try again")


print ("")

pizzatotal = pizza_cost*pizza_amount
drinktotal = drink_cost*drink_amount

total_cost = total_cost_cal(pizzatotal, drinktotal, topping_cost)

print ("")
print ("Calculating bill")
print ("")
print ("")

print ("Thank You for ordering at Pizza Shed! ")

I still don't get it.. Sorry, I'm still quite new to this
I've have made few minor changes, but it still doesn't work
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OT] C# -- sharp or carp? was Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Vito De Tullio
Sven R. Kunze wrote:

>>> My question to those who know a bit of C#: what is the state-of-the-art
>>> equivalent to
>>>
>>> "\n".join(foo.description() for foo in mylist
>>>   if foo.description() != "")

> Friend of mine told me something like this:
> 
> String.Join("\n", mylist.Where(foo =>
> !String.IsNullOrEmpty(foo.description)).Select(foo => foo.description))


I don't know if is "better" or not, but I find more readable using the 
"sql"-like syntax


string.Join("\n", from foo in mylist
  where !string.IsNullOrEmpty(foo.description())
  select foo.description());

which is relatively similar to the python's comprehension.


-- 
By ZeD

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


Re: Help with python code

2016-03-29 Thread Rob Gaddi
Yum Di wrote:

> I still don't get it.. Sorry, I'm still quite new to this
> I've have made few minor changes, but it still doesn't work

Then try entering one line at a time of your program into the
interactive interpreter.  Copy and paste is fine, but use the
interpreter to look at the actual values of variables that you're
creating.

Also, as a mailing list/Usenet etiquette note: You get to have one name
you go by.  Going around changing the name you're posting under in the
middle of the thread is a guaranteed way to piss folks off.  You didn't
know.  You now do.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Calculate Bill

2016-03-29 Thread Yum Di
import random
import time

print ("Welcome to Pizza Shed!")

order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." )

tablenum = input ("Enter table number from 1-25 \n ")
while tablenum>25 or tablenum <=0:
tablenum = input ("Enter the correct table number, there are only 25 tables 
")

#Pizza menu with prices

print ("-")

print ("Let me help you with your order!")

print ("-")

order = raw_input ("\n\nPLEASE PRESS ENTER TO SELECT YOUR PIZZA." )

print ("Menu")

print (
"1 = cheese and tomato: 3.50, "
"2 = ham and pineapple: 4.20, "
"3 = vegetarian: 5.20, "
"4 = meat feast: 5.80, "
"5 = seafood: 5.60 " )

pizza_choice = input("Enter the type of pizza that you want to order from 1-5 
\n")
while pizza_choice>5 or pizza_choice <=1:
pizza_choice = input ("Enter the right number ")

print ("--")

pizza_amount = input ("Enter the amount of Pizzas that you want to order ")
while pizza_amount > 10 or pizza_amount <=0:
pizza_amount = input ("Maximum amount is 10, Please enter again ")

print ("")

#base

print ("Base")

print (
"1 = thin and crispy,"
"2 = traditional" )

base = input ("Select a base from 1-2 \n")
while base>2 or base<=1:
base = input ("There are only 2 types, Please enter again ")

if base == 1:
print "You have chosen thin and crispy"
elif base == 2:
print ("You have chosen traditional")

print ("---")

#extra toppings

print ("Extra Toppings")

toppings = input ("Enter a number for your choice of extra topping \n Enter 1 
for extra cheese \n Enter 2 for extra pepperoni \n Enter 3 for extra pineapple 
\n Enter 4 for extra peppers \n" )
while toppings >4 or toppings < 0:
toppings = input ("There are only 4 types of extra toppings, Please try 
again " )

if toppings == 1:
print "You have chosen extra cheese"
elif toppings == 2:
print ("You have chosen pepperoni")
elif toppings == 3:
print ("You have chosen pineapple")
elif toppings == 4:
print ("You have chosen peppers")

print ("-")

#drink

print ("Drink")

print (
"1 = Cola: 0.90, "
"2 = Lemonande: 0.80, "
"3 = Fizzy Orange: 0.90 "
)

drink = input ("Enter a number for your choice of drinks " )
while drink>3 or drink<0:
drink = input ("Choices start from 0 to 3 " )
drink_amount = input ("Enter the amount of drinks")
while drink_amount >10 or drink_amount<1:
drink_amount = input (" You can only have upto 10 drinks, Please try again")

if drink == 1:
print "You have chosen Cola"
elif drink == 2:
print ("You have chosen Lemonande")
elif drink == 3:
print ("You have chosen Fizzy Orange")

print ("")
print ("Calculating bill")
print ("")
print ("")

print ("Thank You for ordering at Pizza Shed! ")

Hey.. this code works. However, i need it to calculate the total cost.
I dont know how to do that. Can someone help me..
thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Marco Sulla via Python-list
On 29 March 2016 at 16:31, Chris Angelico  wrote:
> But the definition of a sequence, and likewise the definition of a
> mapping, goes deeper than that. A sequence has *relative* stability;
> if one item is at a lower index than another, it will continue to be
> at a lower index, until you change one of those two items. Changes
> elsewhere in the sequence might bring them closer together or push
> them further apart, but one of them is still earlier in the sequence
> than the other. A mapping, on the other hand, has *absolute*
> stability. Any given key->value relationship is stable in and of
> itself. If you stuff a thing into a dict under a particular key, you
> expect to be able to get it back using that key, not some other.

It's the same arguments of Steven D'Aprano. Let me counter these
arguments with this example:

>>> class StrangeDict(dict):
... def insert(self, k, v):
... if k in self:
... for key in [x for x in sorted(self.keys()) if x >= k]:
... v_next = self[key]
... self[key] = v
... v = v_next
...
... self[key+1] = v
...
>>> a = StrangeDict({0:5, 1:7, 2: 14})
>>> a.insert(1, 5)
>>> a
{0: 5, 1: 5, 2: 7, 3: 14}

Yes, it's a terrible class and lacks a lot of safety checks, but I
don't think at all it violates the map contract. You can continue and
add some constraint at __init__() about key types and their
contiguity, some other methods and voila', you'll get a list-like
class.

Let me add that an items() and keys() for sequences will be also
useful for day-by-day programming, since they will be a shortcut for
enumerate(seq) and range(len(seq))

> The whole idea of making sequences and mappings more similar is highly
> distasteful to me, and I've figured out why. It's the exact problem
> with the PHP array - it's not sure whether to act as a mapping or a
> sequence

This is a good point. This is not true for mutable sequences (lists),
since they will have a lot of methods (append, pop etc) that allows
you to distinguish them, but immutable sequences like tuples will be
not easily distinguishable using duck typing.

I think the main problem is in __getitem__. __getitem__ can be used as
slice method checking if its parameter is a slice. If the slice method
was a separated method, this problem will not arise.


On 27 March 2016 at 21:24, Mark Lawrence  wrote:
> Why do you need a new interace if all you're trying to do is create a
> vdict class that has "iter(d) == iter(d.values()), and should also
> have a count() method, like sequence types"?

Since simply adding get(), items(), keys(), values() to existing
sequence interface will likely break existing code, I would try also
to write new sequence types, using a common interface with maps. This
is my idea.
-- 
https://mail.python.org/mailman/listinfo/python-list


IPython and Jupyter

2016-03-29 Thread David Shi via Python-list
Ipython-4.1.2
I thought that I installed Ipython.
I typed in ipython notebook.
But a WARNING came up, saying Subcommand 'ipython notebook is deprecated and 
will be removed in future versions.
Then Jupyter turned up.
How can I make available both Ipython notebook and Jupyter?, so that I can 
switch between the twowhenever required.
Regards.
David
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with python code

2016-03-29 Thread Wildman via Python-list
On Tue, 29 Mar 2016 21:19:05 +, Rob Gaddi wrote:

>> menu = input("Enter the type of pizza that you want to order from 1-5 \n")
>> while menu>5 or menu <=0:
>> menu = input ("Enter the right number ")
>> pizza_cost = pizzatype[menu]

As it has already been pointed out, a Python list starts with an index
of 0.  Change the last line in the above code to this...

pizza_cost = pizzatype[menu - 1]

Anywhere else that your code references a list index you may need to
make the same change.

-- 
 GNU/Linux user #557453
May the Source be with you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Calculate Bill

2016-03-29 Thread Chris Angelico
On Wed, Mar 30, 2016 at 9:33 AM, Yum Di  wrote:
> Hey.. this code works. However, i need it to calculate the total cost.
> I dont know how to do that. Can someone help me..
> thanks

It does indeed appear to work. And thank you for posting your current
code. However...

> print ("Welcome to Pizza Shed!")
>
> order = raw_input ("\n\nPLEASE PRESS ENTER TO ORDER." )
>
> tablenum = input ("Enter table number from 1-25 \n ")

This should never be done. Do not do this. Your use of raw_input
proves that you're using Python 2, and in Python 2, never ever ever
use input(). There are two solutions:

1) Use raw_input everywhere
2) Use Python 3, and add parentheses to the few print() calls that
don't have them.

Either way, the correct fix also involves accepting *strings* from the
keyboard, and then converting them. The problem with input() is that
it automatically converts what the user types, according to the rules
of source code; you almost never want this. For example, entering 08
will result in an error, but 08.50 is the same as 8.50.

After that, you can start looking at the totals. But I'm not going to
write the code for you; you can start writing code, and when you get
stuck, come and ask for help.

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


Re: Learning Python (or Haskell) makes you a worse programmer

2016-03-29 Thread Eric S. Johansson



On 3/29/2016 6:05 AM, Sven R. Kunze wrote:


Python = English

As someone who writes English text and code using speech recognition, I 
can assure you that Python is not English. :-)

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


Re: Threading is foobared?

2016-03-29 Thread Steven D'Aprano
On Tue, 29 Mar 2016 09:26 pm, Sven R. Kunze wrote:

> On 27.03.2016 05:01, Steven D'Aprano wrote:
>> Am I the only one who has noticed that threading of posts here is
>> severely broken? It's always been the case that there have been a few
>> posts here and there that break threading, but now it seems to be much
>> more common.
> 
> I agree. Didn't we both already have a conversation about this? I
> thought it is my thunderbird messing things up.

I'm not using Thunderbird, so whatever the cause of the problem, it is not
specific to Thunderbird.



-- 
Steven

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


Re: Threading is foobared?

2016-03-29 Thread Rob Gaddi
Steven D'Aprano wrote:

> Am I the only one who has noticed that threading of posts here is severely
> broken? It's always been the case that there have been a few posts here and
> there that break threading, but now it seems to be much more common.
>
> For instance, I see Jerry Martens' post "help with program". According to my
> newsreader, KNode, there are no replies to that thread. But I see a reply
> from Chris A. Chris' reply has a header line:
>
> In-Reply-To: <[email protected]>
>
> but Jerry's original has:
>
> References:
> <[email protected]>
>
> Notice the difference? Here the two values lined up:
>
> <[email protected]>
> <[email protected]>
>

Just read on Usenet instead of through the mailing list.  That way
you can accept broken threading as a given rather than wonder why it's
happening in a particular case.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Steven D'Aprano
On Tue, 29 Mar 2016 10:31 pm, BartC wrote:

> On 29/03/2016 09:26, Steven D'Aprano wrote:
>> On Monday 28 March 2016 12:40, Paul Rubin wrote:
> 
> 
>> The point is that there's nothing intrinsically obvious or right about
>> "return the value of the last statement in the block".
> 
> But that's exactly what happens inside a typical function: you have
> linear sequence of statements, then you a have return statement: at the
> end. It's a common pattern.

But return is an *explicit* exit. And not all languages work that way.


{My Pascal syntax may be a bit rusty...}
function demo(int x): int;
begin
  demo := x + 1;  {sets the return value}
  writeln('x has the value', x);
  writeln('returning now...');
end;


[...]
>> An expression naturally and intrinsically should return the value the
>> expression calculates. This is such a no-brainer that I feel stupid even
>> writing it: "x+1" should return "x+1". It would be crazy to pick
>> something else.
> 
> (This is in contradiction to what you say elsewhere, where:
> 
>graph + node
> 
> may be procedural.)

Not at all. With operator overloading, the plus operator + ends up as a
method call __add__ or __radd__. This method call can have side-effects,
and it can return anything it likes, including None. That return value can
be ignored, but it is still the return value of the expression:

graph + node  # returns None, use this expression for the side-effects only


Just like print(a, b, c) returns None, and we use if for the side-effects.
It's still an expression ("call the print function with these arguments"),
it does something (prints) and then returns None.


>> But a statement is a statement because it doesn't have a return value.
> 
> Isn't an expression technically a statement in Python? 

I mean statements which are not legal expressions, like:

del x
import module
from module import name
for x in seq: block
while condition: block
try ... except ... else ... finally

etc. I'm sorry that I wasn't pedantic enough to specify "statements (apart
from expressions)" each time I contrasted statements and expressions. Can
you possibly forgive me for my informal use of language?



> Therefore a 
> statement could have a value. But take this example:
> 
>   if cond1:   x=a1
>   elif cond2: x=a2
>   elif cond3: x=a3
>   else:   x=a4
> 
> Clearly this would be better expressed as (not valid Python):
> 
>x = if cond1:   a1
>elif cond2: a2
>elif cond3: a3
>else:   a4


x = a1 if cond1 else a2 if cond2 else a3 if cond3 else a4

We can split it over multiple lines too:

x = (
 a1 if cond1 else 
 a2 if cond2 else 
 a3 if cond3 else
 a4
 )


> (Actually 'del is a rather odd language feature. And I can't figure out
> how it's implemented; how does it manage 'del x[i]'? Anyway that's
> another matter.)


del x[i] calls x.__delitem__(i)



>> True if that allowed the value to be garbage
>> collected, False if it wasn't? Or the other way around? None of these
>> suggests feel either useful or obviously right.
> 
> It doesn't need to give a useful value.

Hence my suggestion that all statements (apart from expressions) return 42.


> Its 'value' lies in being able to have it in a sequence or block:
> 
>z = del x; y

In a hypothetical Python where `del x` returns None, that would set z to
None and then evaluate y, doing nothing with the result.




-- 
Steven

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


Re: Calculate Bill

2016-03-29 Thread Steven D'Aprano
On Wed, 30 Mar 2016 09:33 am, Yum Di wrote:


[...]
> print ("Thank You for ordering at Pizza Shed! ")
> 
> Hey.. this code works. However, i need it to calculate the total cost.
> I dont know how to do that. Can someone help me..
> thanks


Think about how people calculate the bill at a real pizza restaurant.

Every time you order something, they write it down in a list:

seafood
thin and crispy
extra cheese
pineapple
Fizzy Orange


The list goes to the cook, who prepares the order, then when you're ready to
pay, it goes to somebody who works out the prices.

In your case, you don't need to care about the cook. So you can record the
prices of each item in a list:


prices = []  # No items have been ordered.

# Order 3 seafood pizzas:

prices.append(5.60 * 3)

and so on, for all the extra topics, drinks, deserts, anything else they
order.

Then, you calculate the total:

sum(prices)



-- 
Steven

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


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Terry Reedy

On 3/29/2016 6:29 PM, Marco Sulla via Python-list wrote:


Let me add that an items() and keys() for sequences will be also
useful for day-by-day programming, since they will be a shortcut for
enumerate(seq) and range(len(seq))


To me they are useless and confusing duplications since enumerate()(seq) 
and range(len(seq)) are quite different from dict.items and dict.keys. 
They cannot be used interchangably.


Dict.keys/values/items are re-iterable, set-like *dynamic views* of 
dicts.  They are not iterators.  They support binary set operations and 
inter-operate with sets.


>>> {1:1, 2:2}.keys() ^ {1, 3}
{2, 3}
>>> {1, 3} ^ {1:1, 2:2}.keys()
{2, 3}

They not independent objects but are views of the contests of the dict. 
They are relatively easy to implement because dicts are key-hashed sets 
of pairs. At least in CPython, changing a dict disables view iterators.


>>> d={1:1, 2:2}
>>> di = iter(d)
>>> next(di)
1
>>> d[3] = 3
>>> next(di)
Traceback (most recent call last):
  File "", line 1, in 
next(di)
RuntimeError: dictionary changed size during iteration

Enumerates are iterators.  Ranges are independent collections.  Neither 
support binary set operations.  Enumerates and range iterators are not 
disabled by sequence changes.



Since simply adding get(), items(), keys(), values() to existing
sequence interface will likely break existing code, I would try also
to write new sequence types, using a common interface with maps.


seq.get is plausible, but the use cases are not clear.  It is trivial to 
write, so it needs justification.  A major use of dict.get is to supply 
an empty list for values that can be appended to.

   d.get(key, []).append(val)
A similar use with lists could just as well be done with a dict.

For the rest, try writing sequence view classes that actually mimic dict 
views and interoperate with sets and views.  Find the dict view tests 
and adapt them to seq views.  To use the same code with dicts and seqs, 
add functions that return a dict view or seq view depending on the class 
of the collections.


def keys(ds):
reture ds.keys() if isinstance(ds, dict) else SeqKeys(ds)

You might search for 'python sequence view' first, and if there is 
nothing already on PyPI, add a seqview module there.


--
Terry Jan Reedy

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


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Chris Angelico
On Wed, Mar 30, 2016 at 9:29 AM, Marco Sulla via Python-list
 wrote:
> On 29 March 2016 at 16:31, Chris Angelico  wrote:
>> But the definition of a sequence, and likewise the definition of a
>> mapping, goes deeper than that. A sequence has *relative* stability;
>> if one item is at a lower index than another, it will continue to be
>> at a lower index, until you change one of those two items. Changes
>> elsewhere in the sequence might bring them closer together or push
>> them further apart, but one of them is still earlier in the sequence
>> than the other. A mapping, on the other hand, has *absolute*
>> stability. Any given key->value relationship is stable in and of
>> itself. If you stuff a thing into a dict under a particular key, you
>> expect to be able to get it back using that key, not some other.
>
> It's the same arguments of Steven D'Aprano. Let me counter these
> arguments with this example:
>
 class StrangeDict(dict):
> ... def insert(self, k, v):
> ... if k in self:
> ... for key in [x for x in sorted(self.keys()) if x >= k]:
> ... v_next = self[key]
> ... self[key] = v
> ... v = v_next
> ...
> ... self[key+1] = v
> ...
 a = StrangeDict({0:5, 1:7, 2: 14})
 a.insert(1, 5)
 a
> {0: 5, 1: 5, 2: 7, 3: 14}
>
> Yes, it's a terrible class and lacks a lot of safety checks, but I
> don't think at all it violates the map contract. You can continue and
> add some constraint at __init__() about key types and their
> contiguity, some other methods and voila', you'll get a list-like
> class.

The map contract is this:

x = StrangeDict()
x[123] = 456
...
assert x[123] == 456

Your mapping does violate the map contract.

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


Re: Statements as expressions [was Re: Undefined behaviour in C]

2016-03-29 Thread Rustom Mody
On Tuesday, March 29, 2016 at 12:18:38 AM UTC+5:30, Paul Rubin wrote:
> BartC  writes:
> > With more recent ones I've dropped that model, so that statements and
> > expressions are different, and that is strictly enforced. This makes
> > implementation simpler, and detects lots more errors.
> 
> You should try Haskell, where there are only expressions, but the ones
> that perform actions can be separated from the other ones through the
> type system, so using one in the wrong place raises a compile time type
> error.

When I studied Pascal was mainstream and Lisp (and to smaller extent
Prolog, APL) were hi-faluting.

In retrospect, Pascal got something right that most everyone, both before and 
after got wrong, viz that we need values AND effects.

Philosophically: Is programming about knowing or doing?
Clearly any onesided answer is wrong.
Both columns in the table here need equal weightage
http://blog.languager.org/2016/01/primacy.html#expstat

Pascal → C → Python is a slide down because
Pascal had the clear distinction of procedure and function
C conflated procedure into function with its 'void function'
[Actually the first C had no void]
Python only has None-return
But a None returned to signify a real semantics eg dict.get not finding key
And a None returned because asking for something is meaningless eg print in 
python3 are unfortunately undistinguishable although conceptually totally 
different

Yeah Haskell's type system carries Pascal's procedure←→function distinction
in great and excruciating detail -- pure and monadic types.
But IMHO monads for distinguishing values and effects is 
sledgehammer-for-cracking-an-egg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Threading is foobared?

2016-03-29 Thread Random832
On Tue, Mar 29, 2016, at 19:54, Rob Gaddi wrote:
> Just read on Usenet instead of through the mailing list.  That way
> you can accept broken threading as a given rather than wonder why it's
> happening in a particular case.

It's a given everywhere. Any thread that contains a sufficient number of
replies from both users using usenet and users using the mailing list
(gmane counts as the mailing list, since it _doesn't_ do the broken
stuff) is going to be broken for everyone everywhere, though it will be
broken in different places. For users reading by the mailing list,
Usenet users' replies to Mailing List users will be broken (but their
replies to each other will be fine). For users reading by Usenet,
Mailing List users' replies to each other will be broken (though all
replies made via Usenet or to Usenet users will be fine).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Random832
On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote:
> The map contract is this:
> 
> x = StrangeDict()
> x[123] = 456
> ...
> assert x[123] == 456
> 
> Your mapping does violate the map contract.

So, you can put *anything* in that "..."?

x = dict()
x[123] = 456
x[123] = 789
assert x[123] == 456

dict violates the map contract.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Steven D'Aprano
On Wednesday 30 March 2016 14:38, Random832 wrote:

> On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote:
>> The map contract is this:
>> 
>> x = StrangeDict()
>> x[123] = 456
>> ...
>> assert x[123] == 456
>> 
>> Your mapping does violate the map contract.
> 
> So, you can put *anything* in that "..."?

Yes, we're all very impressed that you spotted the trivial and obvious 
loophole that changing a key:value will change the key:value that you just 
changed *wink* but that doesn't really move the discussion anywhere.

This is not an argument about dicts being mutable, because clearly they 
aren't. This is an argument about key:value pairs being stable. "Stable" 
doesn't mean "immutable". If you change the value associated with a key 
directly, then it will change. That's the whole point. But if you change 
*one* key, the relationship between *other* keys and their values shouldn't 
change.

Given a surjection (many-to-one mapping) between keys and values in a 
mapping, we expect that changing the mapping of one key will not affect 
other keys. To be pedantic, by "change" I mean deleting the key (and, if 
necessary, value) or reassigning a new value to the key. To be even more 
pedantic, mutations to the value *do not count*.

Specifically, insertions and deletions to the mapping never affect the 
existing keys. But, critically, insertions and deletions to a sequence do 
sometimes affect the index of existing items.

So while we can say that there is a surjective function that maps the index 
of a sequence to an item, but that relationship fails to meet the 
requirements for it to be a mapping type like a dict.

https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection


If somebody wants to insist that this is a kind of mapping, I can't 
disagree, but it isn't useful as a mapping type.



-- 
Steven

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


Re: Suggestion: make sequence and map interfaces more similar

2016-03-29 Thread Steven D'Aprano
On Wednesday 30 March 2016 16:43, Steven D'Aprano wrote:

> This is not an argument about dicts being mutable, because clearly they
> aren't.

Er, I meant *immutable*. Dicts aren't immutable.


-- 
Steve

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