python3: why writing to socket require bytes type while writing to a file require str ?

2016-07-22 Thread Yubin Ruan
Hi,
I'm migrating my code to python3 now and find it hard to deal with python's 
'str' and 'bytes' type. It's kind of painful.
One thing I find really confusing is that, writing to a socket requires 
argument to be of type 'bytes'(otherwise python throw 'str does not support 
buffer interface...' exception), while writing to a file requires argument to 
be of type 'str'. Why is that? In standard UNIX interface, everything is file, 
which mean that writing to a socket is the same as writing to a normal file. 
This is true is python2. But thing doesn't seem to work in python 3.
Does anyone have idea why is this in python3 ?
In my understanding, writing to a file would requires that everything be 
written byte by byte. So writing objects of type 'bytes' to socket makes sense. 
But, how could python write to file using unicode(type 'str')? Does python 
encode 'str'(Unicode) automatically before writing things to file? If it's 
true, then why can't it do that automatic encoding when I trying to write a 
'str' to socket ?

Regards,
Ruan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python3: why writing to socket require bytes type while writing to a file require str ?

2016-07-22 Thread Chris Angelico
On Fri, Jul 22, 2016 at 6:52 PM, Yubin Ruan  wrote:
> In my understanding, writing to a file would requires that everything be 
> written byte by byte. So writing objects of type 'bytes' to socket makes 
> sense. But, how could python write to file using unicode(type 'str')? Does 
> python encode 'str'(Unicode) automatically before writing things to file? If 
> it's true, then why can't it do that automatic encoding when I trying to 
> write a 'str' to socket ?
>

Did you specify an encoding when you opened the file? Did you specify
an encoding when you opened the socket?

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


Re: python3: why writing to socket require bytes type while writing to a file require str ?

2016-07-22 Thread Frank Millman
"Yubin Ruan"  wrote in message 
news:47f3acf9-8da2-4aad-a6f0-7a9efbdfe...@googlegroups.com...


  In my understanding, writing to a file would requires that everything be 
written byte by byte. So writing objects of type 'bytes' to socket makes 
sense. But, how could python write to file using unicode(type 'str')? Does 
python encode 'str'(Unicode) automatically before writing things to file? 
If it's true, then why can't it do that automatic encoding when I trying 
to write a 'str' to socket ?




If you open a file for writing in text mode, using 'w', it expects a string.

If you open it in binary mode, using 'wb', it expects bytes.

HTH

Frank Millman


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


Re: python3: why writing to socket require bytes type while writing to a file require str ?

2016-07-22 Thread Steven D'Aprano
On Fri, 22 Jul 2016 06:52 pm, Yubin Ruan wrote:

> Hi,
> I'm migrating my code to python3 now and find it hard to deal with
> python's 'str' and 'bytes' type. It's kind of painful. One thing I
> find really confusing is that, writing to a socket requires argument
> to be of type 'bytes'

Correct. Sockets are low-level endpoint for transmitting bytes between
processes.


> (otherwise python throw 'str does not support 
> buffer interface...' exception), while writing to a file requires
> argument to be of type 'str'. Why is that? 

Only files opened in text mode expect str (text strings). Files opened in
binary mode expect bytes.

This is for convenience: Python is a high-level programming language, and so
for the majority of Python programmers, writing to text files should accept
*text*, not bytes. Python allows you to specify the encoding that the file
will use (defaulting to UTF-8), and will automatically encode and decode
when writing and reading from the file.


> In standard UNIX interface, 
> everything is file, which mean that writing to a socket is the same as
> writing to a normal file. 

Python is not Unix-only and doesn't exclusively follow the Unix philosophy.
For example, None is not a file, nor are floats, or lists.

A Python text file is an object which provides an interface for writing
Unicode text strings to low-level byte-oriented files using some encoding.
Python binary files are similar objects, except they skip the encoding part
and so require bytes.

Files opened in text mode will also automatically convert line-endings to
the correct ending used by your operating system.


> This is true is python2. But thing doesn't 
> seem to work in python 3. Does anyone have idea why is this in python3
> ? In my understanding, writing to a file would requires that 
> everything be written byte by byte. So writing objects of type 'bytes'
> to socket makes sense. But, how could python write to file using
> unicode(type 'str')? Does python encode 'str'(Unicode) automatically
> before writing things to file? 

Yes.

But remember, only if the file is opened in text mode.

To open the file in binary mode, add "b" to the mode:

open("foo", "rb")
open("foo", "wb")

> If it's true, then why can't it do that 
> automatic encoding when I trying to write a 'str' to socket ?

Probably because nobody has requested that functionality before.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Stupid question, just need a quick and dirty fix

2016-07-22 Thread thilfigr16
I'm certainly not going to sugar-coat it and act like I know anything about 
this language, or wax about how I think it's "inferior" for any reason (because 
doing so would be pretty foolish). I just figured I'd be able to muddle through 
and find *something* that would easily filter out results I didn't want. I 
assumed getting it to port through gmail to notify me would be the hard part 
and that was actually quite easy. I'm by no means looking to go out and put 
"Python programmer" on my resume after finishing this task, I was just hoping 
to dial in the code a bit better for my needs. 

My var names changed on this thread because I was just using them here as 
references. I'll figure out how to just post the whole PY file when I'm home 
tonight and I'll point out the lines where I'm having issues. 

I do appreciate the information and I still need to go up and read (comprehend) 
everything posted to see if I can take it from there. Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: learning python. learning defining functions . need help

2016-07-22 Thread Chris Angelico
On Fri, Jul 22, 2016 at 11:13 PM, Dennis Lee Bieber
 wrote:
> Now... Going much beyond the assignment (if you were having trouble
> with the assignment, this will seem like magic) [Python 2.7]:

I'm not sure, but I think your code would become Py3 compatible if you
just change your prints. Which I'd recommend - it's not difficult to
just always print a single string, and most example code is ASCII-only
and has no difficulty with the bytes/unicode distinction. But, point
of curiosity...

> class Refrigerator(object):
> def __init__(self, stock=None):
> if stock is None or type(stock) != type(dict()):
> self._stock = dict()
> else:
> self._stock = stock

... why do you call up "type(dict())"? Why not either just "dict" or "type({})"?

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


Just starting to learn Python, and encounter a problem

2016-07-22 Thread Zagyen Leo
yeah, it may be quite simple to you experts, but hard to me.

In one of exercises from the Tutorial it said: "Write a program that asks the 
user their name, if they enter your name say "That is a nice name", if they 
enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), 
otherwise tell them "You have a nice name."

And i write so:

name = input("Enter your name here: ")
if name == "John Cleese" or "Michael Palin":
print("Sounds like a gentleman.")
else:
print("You have a nice name.")

But strangely whatever I type in (e.g. Santa Claus), it always say "Sounds like 
a gentleman.", not the result I want.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread Random832


On Fri, Jul 22, 2016, at 09:59, Zagyen Leo wrote:
> yeah, it may be quite simple to you experts, but hard to me.
> 
> In one of exercises from the Tutorial it said: "Write a program that asks
> the user their name, if they enter your name say "That is a nice name",
> if they enter "John Cleese" or "Michael Palin", tell them how you feel
> about them ;), otherwise tell them "You have a nice name."
> 
> And i write so:
> 
> name = input("Enter your name here: ")
> if name == "John Cleese" or "Michael Palin":
> print("Sounds like a gentleman.")
> else:
> print("You have a nice name.")
> 
> But strangely whatever I type in (e.g. Santa Claus), it always say
> "Sounds like a gentleman.", not the result I want.

"or" is a lower precedence than "==".

> if name == "John Cleese" or "Michael Palin"

becomes if (name == "John Cleese") or "Michael Palin"; becomes if False
or "Michael Palin"; becomes if "Michael Palin"; and non-empty strings
are considered true.

You want if Name == "John Cleese" or Name == "Michael Palin"; or if Name
in ("John Cleese", "Michael Palin")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread Bob Gailer
On Jul 22, 2016 10:00 AM, "Zagyen Leo"  wrote:
>
> yeah, it may be quite simple to you experts, but hard to me.
>
> In one of exercises from the Tutorial it said: "Write a program that asks
the user their name, if they enter your name say "That is a nice name", if
they enter "John Cleese" or "Michael Palin", tell them how you feel about
them ;), otherwise tell them "You have a nice name."
>
> And i write so:
>
> name = input("Enter your name here: ")
> if name == "John Cleese" or "Michael Palin":
> print("Sounds like a gentleman.")
> else:
> print("You have a nice name.")
>
> But strangely whatever I type in (e.g. Santa Claus), it always say
"Sounds like a gentleman.", not the result I want.

Even without knowing the operator precedence, this will be evaluated either
as:
(name == "John Cleese") or "Michael Palin")
or:
name == ("John Cleese" or "Michael Palin").

Case 1: (name == "John Cleese")  evaluates to either True or False. False
or "Michael Palin" evaluates to  ( believe it or not) " Michael Palin"!
Which, as far as if is concerned, is True. True or "Michael Palin"
evaluates to True.

Case 2: "John Cleese" or "Michael Palin" evaluates to False; name== False
evaluates to False.

One way to get the results you want:
if name in ("John Cleese" or "Michael Palin"):
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread Gordon Levi
Zagyen Leo  wrote:

>yeah, it may be quite simple to you experts, but hard to me.
>
>In one of exercises from the Tutorial it said: "Write a program that asks the 
>user their name, if they enter your name say "That is a nice name", if they 
>enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), 
>otherwise tell them "You have a nice name."
>
>And i write so:
>
>name = input("Enter your name here: ")
>if name == "John Cleese" or "Michael Palin":
>print("Sounds like a gentleman.")
>else:
>print("You have a nice name.")
>
>But strangely whatever I type in (e.g. Santa Claus), it always say "Sounds 
>like a gentleman.", not the result I want.

The second line should be 
if name == "John Cleese" or name == "Michael Palin":

As discussed in recent lengthy thread in this group the following
line, and hence your statement, is always true -

If "Michael Palin":
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert from unsigned long long to PyLong

2016-07-22 Thread MRAB

On 2016-07-22 07:01, Tian JiaLin wrote:

HI There,

I'm using MySQLdb as the MySQL client. Recently I got a weird problem of this 
library. After looking into it, I suspect the problem may related to the 
conversion from unsigned long to PyLongObject.

Here is the detail, If you are familiar with MySQLdb, the following snippet is 
a way to query the data from MySQL:


connection = MySQLdb.connect(...)

connection.autocommit(True)
try:
cursor = connection.cursor()
if not cursor.execute(sql, values) > 0:
return None
row = cursor.fetchone()
finally:
connection.close()
return row[0]


Sometimes the return value of execute method would be 18446744073709552000 even 
there is no matched data available. I checked the source code of the library, 
the underlying implementation is 
https://github.com/farcepest/MySQLdb1/blob/master/_mysql.c#L835,

static PyObject *
_mysql_ConnectionObject_affected_rows(
_mysql_ConnectionObject *self,
PyObject *args)
{
if (!PyArg_ParseTuple(args, "")) return NULL;
check_connection(self);
return 
PyLong_FromUnsignedLongLong(mysql_affected_rows(&(self->connection)));
}

And here is the official doc for mysql_affected_rows 
http://dev.mysql.com/doc/refman/5.7/en/mysql-affected-rows.html.

Let me give a superficial understanding, please correct me if I were wrong.

In a 64-bit system, the mysql_affected_rows is supposed to return a number of 
unsigned long, which means the range should be 0 ~ 2^64 (18446744073709551616), 
How could it be possible the function PyLong_FromUnsignedLongLong return a 
converted value larger than 2^64, that's what I don't understand.

Does anyone have some ideas of it?


The versions of the components I used:

Python: 2.7.6
MySQL 5.7.11
MySQLdb 1.2.5


The function returns an unsigned value, but it will return -1 (i.e. ~0) 
if there's an error, so check for an error with ~result == 0.


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


Re: Stupid question, just need a quick and dirty fix

2016-07-22 Thread MRAB

On 2016-07-22 05:19, Jordan Bayless wrote:

I'm trying to modify some code to suit my purposes and I'm just trying to 
filter results as necessary. Basically, the code is returning one of a number 
from a subset of 150 numbers. I want to only do anything with it if the number 
is a 'good' one. I'm by no means a Python programmer (C# for me by trade) and 
I'm not looking for anything that will be distributed..I just want something 
that works.

Basically, here's what I'm trying to insert:

global blnDesiredInd


> blnDesiredInd == False



[snip]

The line:

blnDesiredInd == False

looks wrong. It should probably be:

blnDesiredInd = False

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


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread justin walters
:
On Jul 22, 2016 7:46 AM, "Gordon Levi"  wrote:
>
> Zagyen Leo  wrote:
>
> >yeah, it may be quite simple to you experts, but hard to me.
> >
> >In one of exercises from the Tutorial it said: "Write a program that
asks the user their name, if they enter your name say "That is a nice
name", if they enter "John Cleese" or "Michael Palin", tell them how you
feel about them ;), otherwise tell them "You have a nice name."
> >
> >And i write so:
> >
> >name = input("Enter your name here: ")
> >if name == "John Cleese" or "Michael Palin":
> >print("Sounds like a gentleman.")
> >else:
> >print("You have a nice name.")
> >
> >But strangely whatever I type in (e.g. Santa Claus), it always say
"Sounds like a gentleman.", not the result I want.
>
> The second line should be
> if name == "John Cleese" or name == "Michael Palin":
>
> As discussed in recent lengthy thread in this group the following
> line, and hence your statement, is always true -
>
> If "Michael Palin":
> --
> https://mail.python.org/mailman/listinfo/python-list

The easiest way to right this would be to use a tuple like so:

if name in ('John Cleese', 'Michael Palin'):
print ('They sound like a gentleman')
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread MRAB

On 2016-07-22 14:59, Zagyen Leo wrote:

yeah, it may be quite simple to you experts, but hard to me.

In one of exercises from the Tutorial it said: "Write a program that asks the user their name, if they enter your name 
say "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell them how you 
feel about them ;), otherwise tell them "You have a nice name."

And i write so:

name = input("Enter your name here: ")
if name == "John Cleese" or "Michael Palin":
print("Sounds like a gentleman.")
else:
print("You have a nice name.")

But strangely whatever I type in (e.g. Santa Claus), it always say "Sounds like a 
gentleman.", not the result I want.


This bit:

name == "John Cleese" or "Michael Palin"

means the same as:

(name == "John Cleese") or "Michael Palin"

If name is "Santa Claus", that's:

"Santa Claus" == "John Cleese" or "Michael Palin"

which is:

False or "Michael Palin"

which is:

"Michael Palin"

and any string except "" is treated as True.

The condition should be:

name == "John Cleese" or name == "Michael Palin"

(Shorter alternatives are available; you'll learn about them later!)

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


Re: learning python. learning defining functions . need help

2016-07-22 Thread justin walters
On Fri, Jul 22, 2016 at 6:24 AM, Chris Angelico  wrote:

> On Fri, Jul 22, 2016 at 11:13 PM, Dennis Lee Bieber
>  wrote:
> > Now... Going much beyond the assignment (if you were having
> trouble
> > with the assignment, this will seem like magic) [Python 2.7]:
>
> I'm not sure, but I think your code would become Py3 compatible if you
> just change your prints. Which I'd recommend - it's not difficult to
> just always print a single string, and most example code is ASCII-only
> and has no difficulty with the bytes/unicode distinction. But, point
> of curiosity...
>
> > class Refrigerator(object):
> > def __init__(self, stock=None):
> > if stock is None or type(stock) != type(dict()):
> > self._stock = dict()
> > else:
> > self._stock = stock
>
> ... why do you call up "type(dict())"? Why not either just "dict" or
> "type({})"?
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>

Hi Chris,

Try opening the interactive terminal on your command line and type the
following:

type({}) == dict()

That should illustrate why. This is because simply typing '{}' could be
interpreted as
either a dict or a set. My interpreter defaults 'type({})' to 'dict', but
it's best to not
take the risk.

You could also replace that line with:

if stock is None or type(stock) != dict:
-- 
https://mail.python.org/mailman/listinfo/python-list


Why not allow empty code blocks?

2016-07-22 Thread Kent Tong
Hi

I'm aware that we can use 'pass' as an empty code block. But why doesn't python 
allow a code block to be empty and thus eliminate the need for this null 
statement?

thanks in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: learning python. learning defining functions . need help

2016-07-22 Thread Random832
On Fri, Jul 22, 2016, at 11:21, justin walters wrote:
> Try opening the interactive terminal on your command line and type the
> following:
> 
> type({}) == dict()
> 
> That should illustrate why. 

That doesn't illustrate anything relevant at all. The reason this is
false is because dict() is a dict instance, not the dict type.

type({}) == dict == type(dict()) will always* be true.

>This is because simply typing '{}' could be interpreted as either a
>dict or a set. My interpreter defaults 'type({})' to 'dict', but it's
>best to not take the risk.

This is part of the language spec, it is not something that can be
chosen by each interpreter.

*well, assuming that "type" and "dict" have not been reassigned from
their built-in definitions.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: learning python. learning defining functions . need help

2016-07-22 Thread Chris Angelico
On Sat, Jul 23, 2016 at 1:21 AM, justin walters
 wrote:
> Hi Chris,
>
> Try opening the interactive terminal on your command line and type the
> following:
>
> type({}) == dict()
>
> That should illustrate why. This is because simply typing '{}' could be
> interpreted as
> either a dict or a set. My interpreter defaults 'type({})' to 'dict', but
> it's best to not
> take the risk.

Of course the type of {} is not equal to an empty dict, but it *will*
be equal to dict itself:

>>> type({}) == dict
True

And it's not ambiguous; it's always going to mean a dictionary.
There's no empty set syntax in Python (well, not as of 3.6, anyway).

> You could also replace that line with:
>
> if stock is None or type(stock) != dict:

That's exactly what I was saying. Barring shenanigans (like shadowing
'dict' with a function or something), type(dict()) will always be
dict.

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


Re: Stupid question, just need a quick and dirty fix

2016-07-22 Thread Cousin Stanley
Jordan Bayless wrote:

> 
> desired = Id < 10 or Id > 133 or Id in good_ids
> 
> When I try to validate whether I passed that check, 
> I'm told there's a Name error and it's not defined 
>  

  On the outside chance that failing to define Id 
  produces the Name error, I defined Id in a for loop
  as a test for your copy/pasted code 


$ cat id_test.py
#!/usr/bin/env python3

good_ids = {
2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 24, 25, 26, 27, 28, 31, 34, 35, 36, 37,
38, 39, 40, 45, 50, 51, 53, 55, 56, 57, 59, 62, 65, 68, 71, 76, 78, 80,
82, 83, 87, 88, 89, 91, 93, 94, 96, 97, 101, 103, 105, 106, 107, 109,
110, 112, 113, 115, 122, 124, 125, 126, 130, 131, 132, 134, 135, 136,
137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 
151
}

test_ids = [ 1 , 10 , 128 , 42 , 137 , 444 ]

print( )

for Id in test_ids : 

desired = Id < 10  or  Id > 133  or  Id in good_ids

print( '  Id :  %4d  desired :  %s ' % ( Id , desired ) )


$ ./id_test.py

  Id : 1  desired :  True 
  Id :10  desired :  False 
  Id :   128  desired :  False 
  Id :42  desired :  False 
  Id :   137  desired :  True 
  Id :   444  desired :  True 



-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Algorithm for sequencing a collection of dependent equations

2016-07-22 Thread Malcolm Greene
We're working on a DSL (domain specific language) that we translate into
a list of tokenized expressions. My challenge is to figure out how to
sequence evaluation of these expressions so that we evaluate these
expressions in the proper order given that expressions have dependencies
on other expressions.
 
We've done the work to determine the full list of tokens associated with
each expression (after referencing other expressions) and we've detected
expressions that result in loops.
 
Here's an example of expressions and their full list of dependencies:
 
a = b + b + b + c + c   > b, c, d, e, s, t, x
b = c + d + e > c, d, e, s, t, x
c = s + 3 > s, x
d = t + 1 > t
e = t + 2 > t
s = x + 100 > x
t = 10 > None
x = 1 > None
y = 2 > None
 
I'm looking for an algorithm/data structure that will me to start with
the least dependent expression (t, x, y) and move through the list of
expressions in dependency order ending with the expression with the most
dependencies.
 
I imagine that spreadsheets have to perform a similar type of analysis
to figure out how to recalculate their cells.
 
Suggestions on algorithms and/or data structures (some form of graph?)
to support the above goals?
 
Thank you,
Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Floating point equality [was Re: What exactly is "exact" (was Clean Singleton Docstrings)]

2016-07-22 Thread Ben Bacarisse
Chris Kaynor  writes:

> On Thu, Jul 21, 2016 at 4:54 PM, Ben Bacarisse  wrote:
>
>> Steven D'Aprano  writes:
>> 
>> > Or you might be using a language like Javascript, which intentionally has
>> > only floats for numbers. That's okay, you can still perform exact integer
>> > arithmetic, so long as you stay within the bounds of ±2**16.
>>
>> Small point: it's 2**52.
>>
>
> If you really want to be picky, it is 2**53, inclusive:

Yes, I mis-typed.  Typical, I suppose, for a correction!

To add something useful, there are properties Number.MAX_SAFE_INTEGER
and Number.MIN_SAFE_INTEGER which are 2**53 - 1 and -2**53 + 1.  These
are the largest (and smallest) integers such that i and i+1 (or i and
i-1) are exactly representable.


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


Re: Algorithm for sequencing a collection of dependent equations

2016-07-22 Thread Tim Golden

On 22/07/2016 17:01, Malcolm Greene wrote:

We're working on a DSL (domain specific language) that we translate into
a list of tokenized expressions. My challenge is to figure out how to
sequence evaluation of these expressions so that we evaluate these
expressions in the proper order given that expressions have dependencies
on other expressions.

We've done the work to determine the full list of tokens associated with
each expression (after referencing other expressions) and we've detected
expressions that result in loops.


[... snip ...]


I'm looking for an algorithm/data structure that will me to start with
the least dependent expression (t, x, y) and move through the list of
expressions in dependency order ending with the expression with the most
dependencies.

I imagine that spreadsheets have to perform a similar type of analysis
to figure out how to recalculate their cells.

Suggestions on algorithms and/or data structures (some form of graph?)
to support the above goals?


I think that what you're looking for is a topological sort

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


Re: Why not allow empty code blocks?

2016-07-22 Thread Rob Gaddi
Kent Tong wrote:

> Hi
>
> I'm aware that we can use 'pass' as an empty code block. But why doesn't 
> python allow a code block to be empty and thus eliminate the need for this 
> null statement?
>
> thanks in advance

Because it's more likely that you have an indentation error than an
intentional need for an empty code block, and Python's trying to prevent
you shooting yourself in the foot.  If you actually needed an empty code
block, the langugage provides a way of marking that emptyness as
intentional.  That way is the pass statement.

-- 
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: Algorithm for sequencing a collection of dependent equations

2016-07-22 Thread Malcolm Greene
Hi Tim,

> I think that what you're looking for is a topological sort

BINGO! That's *exactly* what I was searching for.

Thank you very much,
Malcolm

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


Re: learning python. learning defining functions . need help

2016-07-22 Thread D'Arcy J.M. Cain
On Fri, 22 Jul 2016 08:21:17 -0700
justin walters  wrote:
> You could also replace that line with:
> 
> if stock is None or type(stock) != dict:

Use isinstance().  That handles classes that subclass dict as well.

-- 
D'Arcy J.M. Cain
System Administrator, Vex.Net
http://www.Vex.Net/ IM:da...@vex.net
VoIP: sip:da...@vex.net
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: learning python. learning defining functions . need help

2016-07-22 Thread MRAB

On 2016-07-22 16:41, D'Arcy J.M. Cain wrote:

On Fri, 22 Jul 2016 08:21:17 -0700
justin walters  wrote:

You could also replace that line with:

if stock is None or type(stock) != dict:


Use isinstance().  That handles classes that subclass dict as well.

If you're checking that it's a dict, there's no need to check whether 
it's None, because None isn't a dict either!

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


Re: Stupid question, just need a quick and dirty fix

2016-07-22 Thread Michael Selik
On Fri, Jul 22, 2016 at 2:11 AM Steven D'Aprano  wrote:

> On Fri, 22 Jul 2016 03:18 pm, Michael Selik wrote:
> >> On Jul 22, 2016, at 12:39 AM, Jordan Bayless 
> wrote:
> >>
> >> Posting the entire code snippet is tough because it's thousands of lines
> >> of code.
> >
> > You could paste into a GitHub gist (https://gist.github.com/) and share
> > the link.
>
> Are you going to read "thousands of lines" of unfamiliar code trying to
> work
> out what changes need to be made to fix an underspecified problem?
>
> Yeah, sure you are. Have fun.
>

I suppose not :-)
But then I could follow up with a request for the traceback.
-- 
https://mail.python.org/mailman/listinfo/python-list


Dynamically call methods where method is known by address vs name

2016-07-22 Thread Malcolm Greene
I know I can do the following:
 
>>> s = 'lower'
>>> getattr(s, 'upper')()
'LOWER'
 
But how could I do the same if I had the method 'address' (better
name???) vs. method name?
 
>>> upper_method = s.upper
 
How do I combine this upper_method with string s to execute the method
and return 'LOWER'?
 
Thank you,
Malcolm
 
 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dynamically call methods where method is known by address vs name

2016-07-22 Thread Michael Selik
On Fri, Jul 22, 2016 at 4:05 PM Malcolm Greene  wrote:

> I know I can do the following:
>
> >>> s = 'lower'
> >>> getattr(s, 'upper')()
> 'LOWER'
>
> But how could I do the same if I had the method 'address' (better
> name???) vs. method name?
>
> >>> upper_method = s.upper
>
> How do I combine this upper_method with string s to execute the method
> and return 'LOWER'?
>

In [1]: s = 'hello'
In [2]: f = s.upper
In [3]: f()
Out[3]: 'HELLO'
In [4]: g = str.upper
In [5]: g(s)
Out[5]: 'HELLO'

Is that what you're looking for?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dynamically call methods where method is known by address vs name

2016-07-22 Thread Malcolm Greene
Hi Michael,
 
> Out[3]: 'HELLO'
> In [4]: g = str.upper
> In [5]: g(s)
> Out[5]: 'HELLO'
 
That's perfect! My mistake was trying to use the method returned by
''.upper vs. str.upper.
 
Thank you,
Malcolm
 
-- 
https://mail.python.org/mailman/listinfo/python-list


How asyncio works? and event loop vs exceptions

2016-07-22 Thread Marco S. via Python-list
I'm developing a web app based on aiohttp, and I find the event loop
concept very interesting. I never programmed with it before, but I
know that node.js and GUIs are based on it.

What I can't understand is how asyncio make it possible to run
multiple tasks concurrently, since it's single threaded (if you don't
use loop.run_in_executor()). I just tried to imagine that it should
act as a cpu scheduler. Is this true? If so, how and when asyncio
decide to switch to another task?

Furthermore I have a question about exceptions in asyncio. If I
understand well how it works, tasks exceptions can be caught only if
you wait for task completion, with yield from, await or
loop.run_until_complete(future). But in this case the coroutine blocks
the execution of the program until it returns. On the contrary you can
execute the coroutine inside an asyncio task and it will be
non-blocking, but in this case exceptions can't be caught in a try

statement.

Is this correct? If so, asyncio programming style can't be a little
divergent from what was the philosophy of Python until now?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: learning python. learning defining functions . need help

2016-07-22 Thread Steven D'Aprano
On Sat, 23 Jul 2016 01:21 am, justin walters wrote:

> That should illustrate why. This is because simply typing '{}' could be
> interpreted as
> either a dict or a set. 

No. {} is always an empty dict. That is a language guarantee. Any
programming language where {} is not an empty disk is not valid Python.

> My interpreter defaults 'type({})' to 'dict', but it's best to not
> take the risk.

Are you concerned that type([]) might not be list? Or type("") might not be
str? Or that type(0) might not be int?

> You could also replace that line with:
> 
> if stock is None or type(stock) != dict:

Generally speaking, the right way to test whether something is an instance
of a type is to use the isinstance() function:

if stock is None or not isinstance(stock, dict): ...


That will work correctly even if stock belongs to a subclass of dict.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-22 Thread Steven D'Aprano
On Sat, 23 Jul 2016 01:33 am, Kent Tong wrote:

> Hi
> 
> I'm aware that we can use 'pass' as an empty code block. But why doesn't
> python allow a code block to be empty and thus eliminate the need for this
> null statement?

Because it cannot tell the difference between an empty code block and
failing to indent the code block:

for x in sequence:
print('loop')


Is that meant to print 'loop' each time around the loop, or just once, at
the end of the loop?

There are cases where the interpreter could tell:


if flag:
else:
   block


Obviously the "if" block is empty. But for consistency, and simplicity, the
interpreter requires a pass there too. One less thing to be programmed, one
less thing for the user to remember. Just require pass any time you have an
empty block, rather than try to remember where it is required and were it
is optional.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Why not allow empty code blocks?

2016-07-22 Thread Kent Tong
On Saturday, July 23, 2016 at 9:49:51 AM UTC+8, Steven D'Aprano wrote:

> Because it cannot tell the difference between an empty code block and
> failing to indent the code block:
> 
> for x in sequence:
> print('loop')

Thanks for the excellent answer!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Just starting to learn Python, and encounter a problem

2016-07-22 Thread Zagyen Leo
I got it! Thank you.

Hope in one day I could help other newbies as you do.
-- 
https://mail.python.org/mailman/listinfo/python-list