Re: Data Types

2016-09-22 Thread Larry Hudson via Python-list

On 09/20/2016 09:03 PM, Cai Gengyang wrote:
[snip...]

So for example for "bool" , it only applies to True/False and nothing else? (2 
data types), i.e. :


Not exactly...  bool is the data type (or class), True and False are the only two _values_ (not 
types).





type(True)



type(False)




[snip...]

Besides the bool class, with its two values, there is also the Nonetype class, which has only 
one value:  None.


But to expand on/rephrase what has already been said:  while the bool class/type has only the 
two values True/False, in expressions using logical operators (and, or, not...), ANY data type 
can be interpreted as a boolean.  These are often referred to as truthy and falsey values to 
distinguish them from actual boolean True/False values.


I'm sure you've already seen the list, if not you should quickly learn it...
Any numeric (int, float, complex) that is zero is falsey.
Any empty collection (list, string, dictionary...) is falsey.
EVERYTHING else is truthy.

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


Re: csjark module

2016-09-22 Thread Peter Otten
bezen...@gmail.com wrote:

> On Thursday, September 22, 2016 at 5:51:43 AM UTC+3, beze...@gmail.com
> wrote:
>> On Wednesday, September 21, 2016 at 10:09:25 PM UTC+3, Peter Otten wrote:
>> > bezen...@gmail.com wrote:
>> > 
>> > > On Wednesday, September 21, 2016 at 5:15:38 PM UTC+3, Peter Otten
>> > > wrote:
>> > >> bezen...@gmail.com wrote:
>> > >> 
>> > >> > On Wednesday, September 21, 2016 at 3:17:11 PM UTC+3, Peter Otten
>> > >> > wrote:
>> > >> >> bezen...@gmail.com wrote:
>> > >> >> 
>> > >> >> > On Wednesday, September 21, 2016 at 1:14:14 PM UTC+3, Peter
>> > >> >> > Otten wrote:
>> > >> >> >> bezen...@gmail.com wrote:
>> > >> >> >> 
>> > >> >> >> > After setting up csjark (http://csjark.readthedocs.io/), I'm
>> > >> >> >> > trying to test on of my C header files which has following
>> > >> >> >> > statements:
>> > >> >> >> > 
>> > >> >> >> > typedef struct {
>> > >> >> >> >unsigned long X;
>> > >> >> >> >__int64 Y;
>> > >> >> >> > } abc;
>> > >> >> >> > 
>> > >> >> >> > 
>> > >> >> >> > If I'm changing __int64 to unsigned long I'm not getting
>> > >> >> >> > this error For the __int64 i'm getting the mention error. Am
>> > >> >> >> > I missing something?
>> > >> >> >> > 
>> > >> >> >> > 
>> > >> >> >> > In addition, I'm getting following error:
>> > >> >> >> > Attribute error("'tuple object has no attibute 'children'",)
>> > >> >> >> > 
>> > >> >> >> > I'd be glad to have some assistance.
>> > >> >> >> 
>> > >> >> >> It looks like development of csjark has stopped in 2011. Try
>> > >> >> >> installing a pycparser version from that time frame -- 2.05
>> > >> >> >> should be a good candidate according to
>> > >> >> >>  so
>> > >> >> >> if you are using pip after
>> > >> >> >> 
>> > >> >> >> $ pip install pycparser==2.05
>> > >> >> >> 
>> > >> >> >> csjark might work.
>> > >> >> > 
>> > >> >> > I've installed all the required SW, but still getting the same
>> > >> >> > error
>> > >> >> 
>> > >> >> When you invoke the interactive interpreter what does
>> > >> >> 
>> > >> >> >>> import pycparser
>> > >> >> >>> pycparser.__version__
>> > >> >> '2.05'
>> > >> >> 
>> > >> >> produce on your system?
>> > >> > 
>> > >> > I have version 2.07 (which is the one used for the development)
>> > >> 
>> > >> For cjshark to work (or at least not fail in the way you observed)
>> > >> you need 2.5.
>> > >> 
>> > >> 2.7 returns 2-tuples where 2.5 does not. Compare for example:
>> > >> 
>> > >> 
>> > 
https://github.com/eliben/pycparser/blob/release_v2.07/pycparser/c_ast.py#L149
>> > >> 
>> > >> def children(self):
>> > >> nodelist = []
>> > >> if self.name is not None: nodelist.append(("name",
>> > >> self.name)) if self.subscript is not None:
>> > >> nodelist.append(("subscript",
>> > >> self.subscript))
>> > >> return tuple(nodelist)
>> > >> 
>> > >> and
>> > >> 
>> > >> 
>> > 
https://github.com/eliben/pycparser/blob/release_v2.05/pycparser/c_ast.py#L136
>> > >> 
>> > >> def children(self):
>> > >> nodelist = []
>> > >> if self.name is not None: nodelist.append(self.name)
>> > >> if self.subscript is not None:
>> > >> nodelist.append(self.subscript) return tuple(nodelist)
>> > >> 
>> > >> I wonder why you didn't just try what I suggested...
>> > > 
>> > > Thanks,
>> > > This one solved the 2nd problem.
>> > > 
>> > > Do you have any suggestions for the 1st one?
>> > 
>> > Here's what I see from your original post:
>> > 
>> > https://mail.python.org/pipermail/python-list/2016-September/714323.html
>> > 
>> > So I have no idea what your "1st problem" might be. Can you restate it?
>> > 
>> > You have to use text, pictures are removed.
>> 
>> Clarification with example:
>> 
>> I'm taking the complex_union_test.h file (which is one of the test files
>> of csjark) and changing on line 8 from int to __int64 so the code is
>> 
>> #include "union_test.h"
>> #include "cenum_test.h"
>> 
>> typedef signed int BOOL;
>> typedef enum {TRUE, FALSE} bool_t;
>> 
>> typedef union {
>> __int64 int_member;
>> struct cenum_test cenum_test_member;
>> long long long_long_member;
>> BOOL bool_member;
>> bool_t bool_t_member;
>> short short_member;
>> } complex_union;
>> 
>> struct struct_with_complex_union {
>> complex_union complex_union_member;
>> bool_t bool_t_member;
>> union union_test union_test_member;
>> };
>> 
>> Now trying to execute the parsing and getting following error:
>> Skipped "headers\complex_union_test.":Win32 as it raised
>> ParseError('headers\\complex_union_test.h:8: before: __int64',)
>> 
>> I have similar error with my .h file.
> 
> seems that I have a solution for it:
> instead of __int64 to use "long long" statement

That seems to be a complaint of the C compiler, e. g.

$ cat tmp.h
typedef struct {
   unsigned long X;
   __int64 Y;
} abc;
$ gcc tmp.h
tmp.h:3:4: error: unknown type name ‘__int64’
__int64 Y;
^

You can fix that wi

Re: Pasting code into the cmdline interpreter

2016-09-22 Thread eryk sun
On Thu, Sep 22, 2016 at 5:12 AM, Veek M  wrote:
> 2. Blank lines in my code within the editor are perfectly acceptable for
> readability but they act as a block termination on cmd line.

You can write a simple paste() function. For example:

import sys
paste = lambda: exec(sys.stdin.read(), globals())

>>> paste()
class Foo:
"""test class"""

def spam(self):
'''test method'''
return 'eggs'

>>> Foo().spam()
'eggs'

In a Unix terminal and IDLE, stdin.read() is terminated by typing
Ctrl+D at the start of an empty line. For the Windows console, it's
Ctrl+Z, Enter. Actually in a Unix terminal the cursor can also be at
the end of a line, but a bug in Python requires pressing Ctrl+D twice
in that case.
-- 
https://mail.python.org/mailman/listinfo/python-list


Refer to a numbered heading in ReST

2016-09-22 Thread Steven D'Aprano
I have a ReST (ReStructured Text) document that auto-numbers headings.

I have a heading like:


My Heading
--


which will be given a number like 10.1 (say), except of course I don't know 
what the number will be until I've compiled the .rst file using Sphinx.

Later in the document I want to refer to the heading number, but *not* turn it 
into a cross-reference or link. I want to say:


See clause XX.X.


where the XX.X is replaced by the number 10.1 (or whatever it turns out to be) 
but it should be just plain text. How can I do this using ReST and Sphinx?




-- 
Steven
git gets easier once you get the basic idea that branches are homeomorphic 
endofunctors mapping submanifolds of a Hilbert space.

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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Steven D'Aprano
On Thursday 22 September 2016 17:42, eryk sun wrote:

> On Thu, Sep 22, 2016 at 5:12 AM, Veek M  wrote:
>> 2. Blank lines in my code within the editor are perfectly acceptable for
>> readability but they act as a block termination on cmd line.
> 
> You can write a simple paste() function. For example:
> 
> import sys
> paste = lambda: exec(sys.stdin.read(), globals())

Nice!



-- 
Steven
git gets easier once you get the basic idea that branches are homeomorphic 
endofunctors mapping submanifolds of a Hilbert space.

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


Re: Data Types

2016-09-22 Thread Lawrence D’Oliveiro
On Thursday, September 22, 2016 at 3:47:27 PM UTC+12, Sayth Renshaw wrote:
> What about 0 or 1 they are true and false like no other numbers?

>>> isinstance(1, bool)
False
>>> isinstance(True, int)
True
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: strings and ints consistency - isinstance

2016-09-22 Thread Lawrence D’Oliveiro
On Thursday, September 22, 2016 at 3:41:42 PM UTC+12, Sayth Renshaw wrote:
> if isinstance(int(answer), int) is True:

Not sure what the point of this is...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Lawrence D’Oliveiro
On Thursday, September 22, 2016 at 5:12:13 PM UTC+12, Veek M wrote:
> How do i deal with this - what's the best way to achieve what I'm trying 
> to do.

If you want a scratchpad for trying out Python code, I can recommend 
Jupyter/IPython .
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is import defined in the source code?

2016-09-22 Thread Lawrence D’Oliveiro
On Thursday, September 22, 2016 at 4:14:16 PM UTC+12, Peng Yu wrote:
>
> ... I want know where import is defined in the source code.

This  looks like 
the code, and this 
 where it 
hooks into the parsing.

Just a guess...
-- 
https://mail.python.org/mailman/listinfo/python-list


OT-Requirement-Python Developer

2016-09-22 Thread Shimpy Sandhu
Hi folks

I am looking for python developer for Ludhiana location.

If anyone is interested, please share updated CV at shi...@revinfotech.com

Regards
Shimpy Sandhu
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
eryk sun wrote:

> On Thu, Sep 22, 2016 at 5:12 AM, Veek M  wrote:
>> 2. Blank lines in my code within the editor are perfectly acceptable
>> for readability but they act as a block termination on cmd line.
> 
> You can write a simple paste() function. For example:
> 
> import sys
> paste = lambda: exec(sys.stdin.read(), globals())
> 
> >>> paste()
> class Foo:
> """test class"""
> 
> def spam(self):
> '''test method'''
> return 'eggs'
> 
> >>> Foo().spam()
> 'eggs'
> 
> In a Unix terminal and IDLE, stdin.read() is terminated by typing
> Ctrl+D at the start of an empty line. For the Windows console, it's
> Ctrl+Z, Enter. Actually in a Unix terminal the cursor can also be at
> the end of a line, but a bug in Python requires pressing Ctrl+D twice
> in that case.

ah! very clever and many thanks! so, you use .pythonrc.py to 
store/define your cmd-line shortcuts.

It doesn't work in python2.x, because exec is a stmt, so, def paste(
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
Ben Finney wrote:

> Veek M  writes:
> 
>> Ben Finney wrote:
>>
>> > Since you are writing code into a module file, why not just run the
>> > module from that file with the non-interactive Python interpreter?
>> > 
>> It's part of a hexchat plugin/addon..
> 
> Which tells me that it still isn't appropriate to copy-paste the code
> directly into the *interactive* Python interpreter. Instead, it's a
> module that should be imported from file, by Hexchat.
> 
> Unless I misunderstand what you're talking about?
> 
ah nope, you got it.
-- 
https://mail.python.org/mailman/listinfo/python-list


h(re) for help, import re - on NameError

2016-09-22 Thread Veek M
Is there a way to use .pythonrc.py to provide a help function that 
autoloads whatever module name is passed like so:
\>>> h(re)

I tried inheriting site._Helper and overriding __init__ and __call__ but 
that didn't work, also I don't know how to deal/trap/catch the NameError 
(no quotes on h(re)) - is there a way to insert a try/except block 
around the >>> prompt?

I hate having to: import whatever every-time i forget. Actually could I 
ditch the () in h(re) and just do: h re - the joy of that :p
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: strings and ints consistency - isinstance

2016-09-22 Thread Ned Batchelder
On Wednesday, September 21, 2016 at 11:41:42 PM UTC-4, Sayth Renshaw wrote:
> This ends being the code I can use to get it to work, seems clear and 
> pythonic, open to opinion on that :-)
> 
> 
> answer = input("\t >> ")
> if isinstance(int(answer), int) is True:
> raise ValueError("Ints aren't valid input")
> sys.exit()
> elif isinstance(answer, str) is True:
> print(v0 * t - 0.5 * g * t ** 2)
> else:
> print("Ok please ammend your entries")
> 
> Cheers
> 
> Sayth

1) When checking for truth, there's very very rarely a need to use
"if x is True:".  Instead, just use "if x:"

2) "isinstance(int(answer), int)" will either be True, because the
int() call succeeded and produced an int, or the int() call will raise
an error.  Using it as a condition is baroque, and will never result
in the elif clause being tested.  So I'm not sure how your code is
ever printing the result of the calculation, or printing the
"amend" message.

Are you sure you've tested this code thoroughly?

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


Re: Obtain the raw line of text read by CSVDictReader when reporting errors?

2016-09-22 Thread Malcolm Greene
Oscar/MRAB,

> You could put something between the file and the reader ...

Thank you both for your suggestions ... brilliant! You guys helped me
solve my problem and gave me an excellent strategy for future scenarios.

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


Re: strings and ints consistency - isinstance

2016-09-22 Thread Steve D'Aprano
On Thu, 22 Sep 2016 01:41 pm, Sayth Renshaw wrote:

> This ends being the code I can use to get it to work, seems clear and
> pythonic, open to opinion on that :-)

Neither clear, nor Pythonic.


> answer = input("\t >> ")

Since input() returns a string in Python 3, this will always be a string.


> if isinstance(int(answer), int) is True:

int(answer) will either succeed, or it will fail. If it fails, it will raise
ValueError, and your code will fail with an exception.

If it succeeds, then it will return an int. Testing whether int(answer)
returns an int is a waste of time -- it *always* returns an int, if it
returns at all. So if it returns, it will return an int, isinstance() will
always return True, and True is True. So your code will then

> raise ValueError("Ints aren't valid input")

Which means your code will ALWAYS raise ValueError:

if answer is a numeric string, like "123", then int() will succeed, the if
block will run, and ValueError is raised;

but if answer is NOT a numeric string, like "abc", then int() will raise
ValueError.

So we can replace your entire block of code with a single line:

raise ValueError

since that is the only result possible. The rest of your code is dead
code -- it cannot be executed.

But if it could...


> sys.exit()

It seems a bit harsh to exit the application just because the user types the
wrong value. Shouldn't you try again, let them type another string?


> elif isinstance(answer, str) is True:
> print(v0 * t - 0.5 * g * t ** 2)

Since input() returns a string, answer is always a string, and isinstance()
will always return True. So True is True will always evaluate to True, and
the print statement with the mysterious formula will always print.


> else:
> print("Ok please ammend your entries")

That can never occur, since both the if... clause and the elif... clause
will always evaluate as True. So this is dead code.




-- 
Steve
“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: Data Types

2016-09-22 Thread Steve D'Aprano
On Thu, 22 Sep 2016 01:46 pm, Sayth Renshaw wrote:

> What about 0 or 1 they are true and false like no other numbers? what
> category do they fall in with regards to booleans?

0 and 1 are ints:

py> type(0)

py> type(1)



just like 2, 3, 4, -1, -999, 1098765432 etc.

But just like 1 == 1.0 (a float), and 0 == 0.0 (a float), and in fact 1 also
equals Fraction(1, 1) and Decimal(1) and 1+0j (complex number), so 1 also
equals the bool True and 0 equals the bool False.

The reason for this is that in many programming languages, there are no
boolean values. People use 0 for false and 1 (or sometimes -1) for true. In
the early days, Python was the same.

See https://www.python.org/dev/peps/pep-0285/ for more details.




-- 
Steve
“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


Any ReST aware editors?

2016-09-22 Thread Steve D'Aprano
I have editors which will use syntax highlighting on .rst files, but I'm
hoping for something a bit smarter.

What I'd like is an editor with a split window, one side showing the rst
that I can edit, the other side showing the formatted text updated as I
type. (Or at least, updated every thirty seconds or so.)

Anybody know anything like that?



-- 
Steve
“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: Any ReST aware editors?

2016-09-22 Thread jkn
Hi Steve

On Thursday, September 22, 2016 at 12:13:16 PM UTC+1, Steve D'Aprano wrote:
> I have editors which will use syntax highlighting on .rst files, but I'm
> hoping for something a bit smarter.
> 
> What I'd like is an editor with a split window, one side showing the rst
> that I can edit, the other side showing the formatted text updated as I
> type. (Or at least, updated every thirty seconds or so.)
> 
> Anybody know anything like that?

I am not certain, but I am pretty sure that the Leo 'outlining' editor (written 
in Python) allows you to do just that, via its 'viewrendered' plugin.

Leo is an extremely capable editor which can work in a 'scripts + data' manner; 
you can write 'code as data' and intersperse this with Python code which acts 
on the data. FWIW this brief description barely begins to scratch the 
surface

Leo is cross-platform and open source; its main developer, Ed Ream, is very 
responsive to suggestions and feedback

http://leoeditor.com/

There is also a 'leo-editor' Google Groups

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


Re: Any ReST aware editors?

2016-09-22 Thread Jon Ribbens
On 2016-09-22, Steve D'Aprano  wrote:
> I have editors which will use syntax highlighting on .rst files, but I'm
> hoping for something a bit smarter.
>
> What I'd like is an editor with a split window, one side showing the rst
> that I can edit, the other side showing the formatted text updated as I
> type. (Or at least, updated every thirty seconds or so.)
>
> Anybody know anything like that?

There's dillinger.io if online is ok.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Any ReST aware editors?

2016-09-22 Thread Yann Kaiser
Does that work with with ReST?

On Thu, Sep 22, 2016, 12:59 Jon Ribbens  wrote:

> On 2016-09-22, Steve D'Aprano  wrote:
> > I have editors which will use syntax highlighting on .rst files, but I'm
> > hoping for something a bit smarter.
> >
> > What I'd like is an editor with a split window, one side showing the rst
> > that I can edit, the other side showing the formatted text updated as I
> > type. (Or at least, updated every thirty seconds or so.)
> >
> > Anybody know anything like that?
>
> There's dillinger.io if online is ok.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
Yann Kaiser
kaiser.y...@gmail.com
yann.kai...@efrei.net
+33 6 51 64 01 89
https://github.com/epsy
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Any ReST aware editors?

2016-09-22 Thread Jon Ribbens
On 2016-09-22, Yann Kaiser  wrote:
> On Thu, Sep 22, 2016, 12:59 Jon Ribbens  wrote:
>> On 2016-09-22, Steve D'Aprano  wrote:
>> > I have editors which will use syntax highlighting on .rst files, but I'm
>> > hoping for something a bit smarter.
>> >
>> > What I'd like is an editor with a split window, one side showing the rst
>> > that I can edit, the other side showing the formatted text updated as I
>> > type. (Or at least, updated every thirty seconds or so.)
>> >
>> > Anybody know anything like that?
>>
>> There's dillinger.io if online is ok.
>
> Does that work with with ReST?

Ah, apologies, ignore me, I was forgetting that ReST and MD
are not the same.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Another å, ä, ö question

2016-09-22 Thread Peter Otten
Martin Schöön wrote:

> Den 2016-09-20 skrev Peter Otten <__pete...@web.de>:
>> Martin Schöön wrote:
>>
>>> Den 2016-09-19 skrev Christian Gollwitzer :
 Am 19.09.16 um 22:21 schrieb Martin Schöön:
> I am studying some of these tutorials:
> https://pythonprogramming.net/matplotlib-intro-tutorial/
> 

 Assuming that you use UTF-8 (you should check with an emacs expert, I
 am not an emacs user), try putting the header

 #!/usr/bin/python
 # -*- coding: utf-8 -*-

 on top of your files.

>>> I already have this and since it doesn't work from command line
>>> either it can't be an emacs unique problem.
>>> 
>>
>> Are all non-ascii strings unicode? I. e.
>>
>> u"Schöön" rather than just "Schöön"
>>
>> ?
> 
> I am not sure I answer your questions since I am not quite sure I
> understand it but here goes: The complete file is UTF-8 encoded as
> that is how Geany is set up to create new files (I just checked).

When the encoding used for the file and the encoding used by the terminal 
differ the output of non-ascii characters gets messed up. Example script:

# -*- coding: iso-8859-15 -*-

print "first unicode:"
print u"Schöön"

print "then bytes:"
print "Schöön"

When I dump that in my UTF-8 terminal all "ö"s are lost because it gets the 
invalid byte sequence b"\xf6" rather than the required b"\xc3\xb6":

$ cat demo.py
# -*- coding: iso-8859-15 -*-

print "first unicode:"
print u"Sch��n"

print "then bytes:"
print "Sch��n"

But when I run the code:

$ python demo.py
first unicode:
Schöön
then bytes:
Sch��n

There are other advantages, too:

>>> print "Schöön".upper()
SCHööN
>>> print u"Schöön".upper()
SCHÖÖN
>>> print "Schöön"[:4]
Sch�
>>> print u"Schöön"[:4]
Schö


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


Re: Data Types

2016-09-22 Thread BartC

On 22/09/2016 02:40, Steve D'Aprano wrote:

On Wed, 21 Sep 2016 10:25 pm, BartC wrote:


On 21/09/2016 05:03, Cai Gengyang wrote:


Are there any other data types that will give you type(A) or type(B) =
 besides True and False?


No types but any variable or expression containing True or False will be
a bool type (or class bool):


"Containing" True or False? Certainly not:


Well, I wrote 'containing' before I added 'or expression', when 
'evaluating to' might have been better.



  print (10<20)=>  True
  print (type(10<20))  =>  


10<20 shouldn't be thought of as some alternative value which is a bool, any
more than we should think of 1+1 as being a different value to 2.


They're a little different:

 1+1 yielding 2 is  int+int => int
 10<20 yielding True is int bool

My post was really about bool values lurking everywhere not just where 
you explicitly write or assign True or False.



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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Gregory Ewing

eryk sun wrote:

Actually in a Unix terminal the cursor can also be at
the end of a line, but a bug in Python requires pressing Ctrl+D twice
in that case.


I wouldn't call that a bug, rather it's a consequence of
what Ctrl-D does. It doesn't really mean EOF, it means to
send whatever the terminal driver has in its input buffer.
If the buffer is empty at the time, the process gets a
zero-length read which is taken as EOF. But if the buffer
is not empty, it just gets whatever is in the buffer.

There's nothing Python can do about that, because it
never sees the Ctrl-D -- that's handled entirely by the
terminal driver.

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


Re: Any ReST aware editors?

2016-09-22 Thread Marko Rauhamaa
Steve D'Aprano :

> What I'd like is an editor with a split window, one side showing the
> rst that I can edit, the other side showing the formatted text updated
> as I type. (Or at least, updated every thirty seconds or so.)
>
> Anybody know anything like that?

Open a .rst file in emacs and press C-c C-c C-p to see a PDF output of
the file.

On fedora, you need:

dnf install rst2pdf xpdf


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


Re: Any ReST aware editors?

2016-09-22 Thread José Abílio Matos
On Thursday, September 22, 2016 9:13:02 PM WEST Steve D'Aprano wrote:
> I have editors which will use syntax highlighting on .rst files, but I'm
> hoping for something a bit smarter.
> 
> What I'd like is an editor with a split window, one side showing the rst
> that I can edit, the other side showing the formatted text updated as I
> type. (Or at least, updated every thirty seconds or so.)
> 
> Anybody know anything like that?

Maybe ReText (https://github.com/retext-project/retext)

There is a short introduction at
https://lwn.net/Articles/686879/

Regards,

--
José Matos
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: strings and ints consistency - isinstance

2016-09-22 Thread Gregory Ewing

On Wednesday, September 21, 2016 at 11:41:42 PM UTC-4, Sayth Renshaw wrote:


answer = input("\t >> ")
if isinstance(int(answer), int) is True:
   raise ValueError("Ints aren't valid input")


You seem to be trying to check that the user hasn't entered
an integer. But that's a backwards way of looking at it. If
the only valid inputs at that point are "y" or "n", then
you should check for those specifically:

   answer = input("\t >> ")
   if answer == "y":
  # do the "yes" thing
   elif answer == "n":
  # do the "no" thing
   else:
  # user entered something wrong

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


Re: strings and ints consistency - isinstance

2016-09-22 Thread Sayth Renshaw

> > This ends being the code I can use to get it to work, seems clear and
> > pythonic, open to opinion on that :-)
> 
> Neither clear, nor Pythonic.

Sadly imo clearer than the many hack attempts on SO.

> 
> > answer = input("\t >> ")
> 
> Since input() returns a string in Python 3, this will always be a string.
> 
> 
> > if isinstance(int(answer), int) is True:
> 
> int(answer) will either succeed, or it will fail. If it fails, it will raise
> ValueError, and your code will fail with an exception.
> 
> If it succeeds, then it will return an int. Testing whether int(answer)
> returns an int is a waste of time -- it *always* returns an int, if it
> returns at all. So if it returns, it will return an int, isinstance() will
> always return True, and True is True. So your code will then
> 
> > raise ValueError("Ints aren't valid input")
> 
> Which means your code will ALWAYS raise ValueError:
> 
> if answer is a numeric string, like "123", then int() will succeed, the if
> block will run, and ValueError is raised;
> 
> but if answer is NOT a numeric string, like "abc", then int() will raise
> ValueError.
> 
> So we can replace your entire block of code with a single line:
> 
> raise ValueError
> 
> since that is the only result possible. The rest of your code is dead
> code -- it cannot be executed.
> 
> But if it could...
> 
> 
> > sys.exit()
> 
> It seems a bit harsh to exit the application just because the user types the
> wrong value. Shouldn't you try again, let them type another string?
> 
> 
> > elif isinstance(answer, str) is True:
> > print(v0 * t - 0.5 * g * t ** 2)
> 
> Since input() returns a string, answer is always a string, and isinstance()
> will always return True. So True is True will always evaluate to True, and
> the print statement with the mysterious formula will always print.
> 
> 
> > else:
> > print("Ok please ammend your entries")
> 

True it failed, just actually happy to get it to fail or pass successfully on 
int input.

Just felt it was a clearer and more consistent approach to verifying input, 
then most of the varied and rather inconsistent approaches I have seen in 
trying to get this to work.

Half opt for try except the other half if else and then implement them largely 
differently. Every many and varied approach str2bool(), isalpha() using list 
with isinstance(var, [ int, str, bool]) etc.

Anyway back to the old drawing board.

Cheers

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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread eryk sun
On Thu, Sep 22, 2016 at 12:40 PM, Gregory Ewing
 wrote:
> eryk sun wrote:
>>
>> Actually in a Unix terminal the cursor can also be at
>> the end of a line, but a bug in Python requires pressing Ctrl+D twice
>> in that case.
>
> I wouldn't call that a bug, rather it's a consequence of
> what Ctrl-D does. It doesn't really mean EOF, it means to
> send whatever the terminal driver has in its input buffer.
> If the buffer is empty at the time, the process gets a
> zero-length read which is taken as EOF. But if the buffer
> is not empty, it just gets whatever is in the buffer.
>
> There's nothing Python can do about that, because it
> never sees the Ctrl-D -- that's handled entirely by the
> terminal driver.

Yes, FileIO.readall continues making read() system calls until it sees
an empty read. But if we know we're reading from a terminal, we should
be able to assume that a read either consumes an entire line up to a
newline character or the entire buffer, no? In other words, if we see
a read that returns less than the buffer size but doesn't end on a
newline, then for a terminal, and only a terminal, I think we can
infer Ctrl+D was typed and handle it as EOF.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Veek M
eryk sun wrote:

> On Thu, Sep 22, 2016 at 12:40 PM, Gregory Ewing
>  wrote:
>> eryk sun wrote:
>>>
>>> Actually in a Unix terminal the cursor can also be at
>>> the end of a line, but a bug in Python requires pressing Ctrl+D
>>> twice in that case.
>>
>> I wouldn't call that a bug, rather it's a consequence of
>> what Ctrl-D does. It doesn't really mean EOF, it means to
>> send whatever the terminal driver has in its input buffer.
>> If the buffer is empty at the time, the process gets a
>> zero-length read which is taken as EOF. But if the buffer
>> is not empty, it just gets whatever is in the buffer.
>>
>> There's nothing Python can do about that, because it
>> never sees the Ctrl-D -- that's handled entirely by the
>> terminal driver.
> 
> Yes, FileIO.readall continues making read() system calls until it sees
> an empty read. But if we know we're reading from a terminal, we should
> be able to assume that a read either consumes an entire line up to a
> newline character or the entire buffer, no? In other words, if we see
> a read that returns less than the buffer size but doesn't end on a
> newline, then for a terminal, and only a terminal, I think we can
> infer Ctrl+D was typed and handle it as EOF.
 
read() changes it behavior intelligently according to the file type 
(pipe, fifo, etc). By default, from a terminal, it reads up to the first 
newline - canonical mode/cooked mode vs non-canonical mode (vi/less). 
Maybe python interpreter is doing the read in non-canonical mode?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Any ReST aware editors?

2016-09-22 Thread Chris Angelico
On Thu, Sep 22, 2016 at 9:13 PM, Steve D'Aprano
 wrote:
> What I'd like is an editor with a split window, one side showing the rst
> that I can edit, the other side showing the formatted text updated as I
> type. (Or at least, updated every thirty seconds or so.)
>

If I were doing this, I'd simply have a script that watches the .rst
file and rebuilds a corresponding output file, which can then be shown
in another window, completely separate to the editor. Advantage:
Requires no editor integration, so you can use any editor you like.
Disadvantage: Can't see changes until you save. Advantage: Forces you
to save frequently :)

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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Random832
On Thu, Sep 22, 2016, at 09:45, eryk sun wrote:
> On Thu, Sep 22, 2016 at 12:40 PM, Gregory Ewing
>  wrote:
> > eryk sun wrote:
> >>
> >> Actually in a Unix terminal the cursor can also be at
> >> the end of a line, but a bug in Python requires pressing Ctrl+D twice
> >> in that case.
> >
> > I wouldn't call that a bug, rather it's a consequence of
> > what Ctrl-D does. It doesn't really mean EOF, it means to
> > send whatever the terminal driver has in its input buffer.
> > If the buffer is empty at the time, the process gets a
> > zero-length read which is taken as EOF. But if the buffer
> > is not empty, it just gets whatever is in the buffer.
> >
> > There's nothing Python can do about that, because it
> > never sees the Ctrl-D -- that's handled entirely by the
> > terminal driver.
> 
> Yes, FileIO.readall continues making read() system calls until it sees
> an empty read. But if we know we're reading from a terminal, we should
> be able to assume that a read either consumes an entire line up to a
> newline character or the entire buffer, no? In other words, if we see
> a read that returns less than the buffer size but doesn't end on a
> newline, then for a terminal, and only a terminal, I think we can
> infer Ctrl+D was typed and handle it as EOF.

I don't see where you're getting that users should even expect ctrl-d at
the end of a line to be treated as EOF. It doesn't behave that way in
any other program - try it in cat, dash, etc. There are also other
circumstances that can cause a partial read. For example, if the user
types the dsusp character (^Y by default) on systems that support it,
the program will be suspended and will receive a partial read when
resumed. I wouldn't bet on a guarantee that you can't get a partial read
if input is too long to fit in the driver's edit buffer (which may be
smaller than the program's read buffer) on some platforms (though when
I've tried it it simply stops accepting input until I hit ctrl-D or
enter)... and savvy users may deliberately type ctrl-D for this purpose.

And, of course, in readline, the terminal is really in cbreak mode and
Python receives an actual Ctrl+D rather than having to infer anything.
But here, too, other programs ignore it just like Python: try it in
bash, zsh, etc.

The only "bug" is in some users' simplistic understanding that "ctrl-D
means EOF".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Data Types

2016-09-22 Thread Chris Angelico
On Thu, Sep 22, 2016 at 10:33 PM, BartC  wrote:
>>>   print (10<20)=>  True
>>>   print (type(10<20))  =>  
>>
>>
>> 10<20 shouldn't be thought of as some alternative value which is a bool,
>> any
>> more than we should think of 1+1 as being a different value to 2.
>
>
> They're a little different:
>
>  1+1 yielding 2 is  int+int => int
>  10<20 yielding True is int bool

That's a couple of example expressions and the way they're handled.

> My post was really about bool values lurking everywhere not just where you
> explicitly write or assign True or False.

Sure. Thing is, those expressions are actually just syntactic sugar
for functions. Let's replace the integers with these puppies:

class Spam:
def __init__(self, value):
self.value = value
def __repr__(self):
return "Spam(%r)" % self.value
def __add__(self, other):
return Spam(self.value + other.value)
def __lt__(self, other):
if self.value < other.value:
return "Yes, %r < %r" % (self.value, other.value)
return ""

>>> Spam(1) + Spam(1)
Spam(2)
>>> Spam(10) < Spam(20)
'Yes, 10 < 20'
>>> Spam(10) > Spam(20)
''

This is perfectly legal code, and it doesn't use True or False for its
comparisons. If you want it to, you have to actually return one of
those constants from __lt__, either by explicitly typing its name, or
by passing it up the chain (eg "return self.value < other.value"),
which just moves the problem around.

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


Re: Another å, ä, ö question

2016-09-22 Thread Chris Angelico
On Thu, Sep 22, 2016 at 10:27 PM, Peter Otten <__pete...@web.de> wrote:
> When the encoding used for the file and the encoding used by the terminal
> differ the output of non-ascii characters gets messed up. Example script:
>
> # -*- coding: iso-8859-15 -*-
>
> print "first unicode:"
> print u"Schöön"
>
> print "then bytes:"
> print "Schöön"
>
> When I dump that in my UTF-8 terminal all "ö"s are lost because it gets the
> invalid byte sequence b"\xf6" rather than the required b"\xc3\xb6":
>
> $ cat demo.py
> # -*- coding: iso-8859-15 -*-
>
> print "first unicode:"
> print u"Sch��n"
>
> print "then bytes:"
> print "Sch��n"
>
> But when I run the code:
>
> $ python demo.py
> first unicode:
> Schöön
> then bytes:
> Sch��n

What this really means is that you (almost certainly) shouldn't be
storing non-ASCII text in byte strings. Most stuff will "just work" if
you're using a Unicode string (obviously cat doesn't acknowledge the
coding cookie, but Python itself does, as do a number of editors), and
of course, you can avoid all the u"..." prefixes by going to Py3.
Trying to use text in byte strings is extremely encoding-dependent,
and thus dangerous. Sure, it'll generally work for ASCII... but only
because you're highly likely to have your terminal set to an
ASCII-compatible encoding. If you pick something else you're in
for a whole new world of fun. Acres of entertainment.

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


Re: Obtain the raw line of text read by CSVDictReader when reporting errors?

2016-09-22 Thread Chris Angelico
On Thu, Sep 22, 2016 at 8:36 PM, Malcolm Greene  wrote:
> Oscar/MRAB,
>
>> You could put something between the file and the reader ...
>
> Thank you both for your suggestions ... brilliant! You guys helped me
> solve my problem and gave me an excellent strategy for future scenarios.

This is why, despite the confusion it sometimes causes, we all prefer
duck typing to static typing. The csv.DictReader wants a "file-like
object", not necessarily a file - and in this case, all it asks is an
iterable of lines, so a simple generator will work. This is true of
MANY, if not all, places that a file is used.

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


Re: Any ReST aware editors?

2016-09-22 Thread Manolo Martínez
On 09/23/16 at 01:20am, Chris Angelico wrote:
> If I were doing this, I'd simply have a script that watches the .rst
> file and rebuilds a corresponding output file, which can then be shown
> in another window, completely separate to the editor. 

[when-changed]://github.com/joh/when-changed) is a handy little script
that does just this. For this use case I do:

when-changed doc.rst make doc.pdf

where the makefile calls [pandoc](http://pandoc.org/MANUAL.html)

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


Re: How to import all things defined the files in a module directory in __init__.py?

2016-09-22 Thread Peng Yu
On Wed, Sep 21, 2016 at 11:14 PM, Ben Finney  wrote:
> Peng Yu  writes:
>
>> I want to import all the thing (or the ones available in the
>> respective __all__) defined in each of the file by putting the
>> following lines in __init__.py
>>
>> from file1 import *
>> 
>> from filen import *
>>
>> However, I don't want to hardcode the file names in __init__.py. Is
>> there an automatic way of doing it?
>
> Why do you want to do that? It will defeat static analysis of the code,
> which is one of the more important tools to make your code reliable.
>
> It will also make the names in the code impossible to automatically
> match against where they came from. Explicit is better than implicit;
> you are proposing to make an unknown horde of names in the code implicit
> and untraceable.
>
> Why? What problem are you trying to solve that you believe needs this
> approach?

This will make refactoring easy. If everything is explicit, when one
do refactoring, at two places need to be changed which can be a
burden.

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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread eryk sun
On Thu, Sep 22, 2016 at 3:21 PM, Random832  wrote:
> On Thu, Sep 22, 2016, at 09:45, eryk sun wrote:
>
>> Yes, FileIO.readall continues making read() system calls until it sees
>> an empty read. But if we know we're reading from a terminal, we should
>> be able to assume that a read either consumes an entire line up to a
>> newline character or the entire buffer, no? In other words, if we see
>> a read that returns less than the buffer size but doesn't end on a
>> newline, then for a terminal, and only a terminal, I think we can
>> infer Ctrl+D was typed and handle it as EOF.

> I don't see where you're getting that users should even expect ctrl-d at
> the end of a line to be treated as EOF. It doesn't behave that way in
> any other program - try it in cat, dash, etc.

I thought it could be avoided as a convenience by inferring EOF when
reading from a terminal, but clearly that's not the case.

> For example, if the user types the dsusp character (^Y by default) on
> systems that support it, the program will be suspended and will receive a
> partial read when resumed.

I didn't consider this, which means I'm stuck with double tapping
Ctrl+D to get exactly the pasted input without adding an extra
newline.

This is on my mind because I want to add Ctrl+D support for console
I/O in Windows, for consistency with Unix terminals and IDLE. With how
this works on Windows, the read returns with the control character
still in the buffer (e.g. '\x04'), so you know exactly what the user
typed. But I see now that it should retain the default readall()
behavior to only count an empty read (from the function that wraps
ReadConsoleW) as EOF.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: h(re) for help, import re - on NameError

2016-09-22 Thread Chris Angelico
On Thu, Sep 22, 2016 at 8:10 PM, Veek M  wrote:
> Is there a way to use .pythonrc.py to provide a help function that
> autoloads whatever module name is passed like so:
> \>>> h(re)
>
> I tried inheriting site._Helper and overriding __init__ and __call__ but
> that didn't work, also I don't know how to deal/trap/catch the NameError
> (no quotes on h(re)) - is there a way to insert a try/except block
> around the >>> prompt?
>
> I hate having to: import whatever every-time i forget. Actually could I
> ditch the () in h(re) and just do: h re - the joy of that :p

You could use sys.excepthook to catch the NameError. I don't know of a
way to catch the SyntaxError and look at the original text, but with
NameError it's pretty easy:

def excepthook(t,v,tb):
if t is NameError:
n = v.args[0].split("'")[1]
globals()[n] = __import__(n)
exec(tb.tb_frame.f_code, tb.tb_frame.f_globals)
else:
excepthook.old(t,v,tb)

import sys
excepthook.old = sys.excepthook
sys.excepthook = excepthook

Paste that into interactive Python and give it a try. Be aware that
it'll attempt to import *any* dud name, so it'll potentially slow
stuff down any time you typo. Also, it re-executes the current
traceback frame, which may or may not be appropriate; it's fine for
help(re), but not otherwise.

As an alternative, you could inspect tb.tb_frame.f_code to see if it
matches "help(x)", and if it does, simply re-execute it with the
string form of the name:

exec(tb.tb_frame.f_code, tb.tb_frame.f_globals, {n: n})

This works because help('re') does the same thing as help(re), so by
effectively setting re="re", you gain that functionality without
actually importing into the global namespace.

Adequately recognizing help(re) without false positives is left as an
exercise for the reader. :)

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


Hidding Character as you type

2016-09-22 Thread Andrew Clark
I'm looking for a way to either completely hide character as you type in 
command line or add * to each character as you for simple password 
obscurity. I've tried getpass.getpass() however the characters still show up on 
the screen as you type it. Can anyone help? I'm using python 2.7 on windows.

host = 'ldxnis12.dx.deere.com'
username = raw_input("Enter username: ")
password = raw_input("Enter password: ")


Output:

Enter username: username
Enter password: iwanthistonotshowup
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to import all things defined the files in a module directory in __init__.py?

2016-09-22 Thread Chris Angelico
On Fri, Sep 23, 2016 at 1:50 AM, Peng Yu  wrote:
>
> This will make refactoring easy. If everything is explicit, when one
> do refactoring, at two places need to be changed which can be a
> burden.

So you want it to be easy to move stuff around between files in a
package? Sounds like you don't actually have a package at all - you
have a single module that you're splitting across several files.

How big would this file be if you simply put it all into one .py file
and got rid of the package altogether? For reference, the Decimal
module (ignoring the C accelerator) is over six thousand lines of
code, as a single module. Now, that might be pushing the boundaries a
bit, but certainly there's no reason to split a file that's under a
thousand lines of code. Just keep it all in one file, and organize it
using marker comments - that way, there's no API change as you reorder
stuff.

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


Re: Hidding Character as you type

2016-09-22 Thread Chris Angelico
On Fri, Sep 23, 2016 at 2:16 AM, Andrew Clark  wrote:
> I'm looking for a way to either completely hide character as you type in 
> command line or add * to each character as you for simple password 
> obscurity. I've tried getpass.getpass() however the characters still show up 
> on the screen as you type it. Can anyone help? I'm using python 2.7 on 
> windows.
>
> host = 'ldxnis12.dx.deere.com'
> username = raw_input("Enter username: ")
> password = raw_input("Enter password: ")
>
>
> Output:
>
> Enter username: username
> Enter password: iwanthistonotshowup

Sounds like a limitation or bug in getpass. I don't have 2.7 handy,
but just tried it on Win 7, CPython 3.5, and it correctly hid the
characters. (Granted, a lot of Windows users are surprised by the lack
of asterisks. But it's still better than leaving it visible.) It
doesn't hide the password in Idle (and gives a warning to that
effect), but if you're working in a GUI, you have other options
anyway.

Try upgrading to 3.5 and see if you can make it work there. If not,
gather a ton of details about your system, and raise the issue - what
you want is exactly what getpass should provide.

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


Re: Hidding Character as you type

2016-09-22 Thread MRAB

On 2016-09-22 17:16, Andrew Clark wrote:

I'm looking for a way to either completely hide character as you type in 
command line or add * to each character as you for simple password 
obscurity. I've tried getpass.getpass() however the characters still show up on 
the screen as you type it. Can anyone help? I'm using python 2.7 on windows.

host = 'ldxnis12.dx.deere.com'
username = raw_input("Enter username: ")
password = raw_input("Enter password: ")


Output:

Enter username: username
Enter password: iwanthistonotshowup


Here's an answer on StackOverflow:

How to read password with echo “*” in Python console program?
http://stackoverflow.com/questions/7838564/how-to-read-password-with-echo-in-python-console-program

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


RE: Any ReST aware editors?

2016-09-22 Thread Gerald Britton
>
> I have editors which will use syntax highlighting on .rst files, but I'm
> hoping for something a bit smarter. What I'd like is an editor with a
> split window, one side showing the rst
> that I can edit, the other side showing the formatted text updated as I
> type. (Or at least, updated every thirty seconds or so.) Anybody know
> anything like that?


Visual Studio Code does an OK job with the

reStructuredText Language Support for Visual Studio Code

Extension
-- 
Gerald Britton, MCSE-DP, MVP
LinkedIn Profile: http://ca.linkedin.com/in/geraldbritton
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: automated comparison tool

2016-09-22 Thread Andrew Clark
On Wednesday, September 21, 2016 at 8:26:37 PM UTC-5, Steve D'Aprano wrote:
> On Thu, 22 Sep 2016 01:55 am, Andrew Clark wrote:
> 
> > I reinstalled paramiko and now i'm getting a slighty different error but
> > still says no cryptography.
> 
> [...]
> 
> > ImportError: No module named 'cryptography'
> 
> 
> You appear to be missing a dependency of paramiko. You need to identify
> which "cryptography" module it relies on, and install it. Start by reading
> the paramiko documentation and especially look for "requirements"
> or "dependencies".
> 
> 
> 
> 
> -- 
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

I finally realized that pip was not working due to the proxy. Once i used pip 
--proxy command i was able to download the packages no issue. Everything works 
now.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I am newbie who can explain this code to me?

2016-09-22 Thread 380162267qq
在 2016年9月20日星期二 UTC-4下午3:11:27,Terry Reedy写道:
> On 9/20/2016 9:12 AM, Peter Otten wrote:
> 
> >> 在 2016年9月20日星期二 UTC-4上午8:17:13,BartC写道:
> >>> On 20/09/2016 13:12, 38016226...@gmail.com wrote:
> >>> d = {}
> >>> keys = range(256)
> >>> vals = map(chr, keys)
> >>> map(operator.setitem, [d]*len(keys), keys, vals)
> 
>  It is from python library. What does [d]*len(keys) mean?
>  d is the name of dict but put d in [] really confused me.
> 
> Where in which 'python library?  I cannot findI the above in 2.7 or 3.6 
> stdlib.  The code should be replaced by
> 
> > It should be noted that the code above is really bad Python.
> > Better alternatives are the simple loop
> >
> > d = {}
> > for i in range(256):
> >  d[i] = chr(i)
> >
> > or the dict comprehension
> >
> > d = {i: chr(i) for i in range(256)}
> 
> this.
> 
> -- 
> Terry Jan Reedy

I read an old 3.2 library and didn't notice at that time.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Another å, ä, ö question

2016-09-22 Thread Martin Schöön
Den 2016-09-22 skrev Peter Otten <__pete...@web.de>:
> Martin Schöön wrote:
>> 
>> I am not sure I answer your questions since I am not quite sure I
>> understand it but here goes: The complete file is UTF-8 encoded as
>> that is how Geany is set up to create new files (I just checked).
>
> When the encoding used for the file and the encoding used by the terminal 
> differ the output of non-ascii characters gets messed up. Example script:
>
> # -*- coding: iso-8859-15 -*-
>
> print "first unicode:"
> print u"Schöön"
>
> print "then bytes:"
> print "Schöön"
>
> When I dump that in my UTF-8 terminal all "ö"s are lost because it gets the 
> invalid byte sequence b"\xf6" rather than the required b"\xc3\xb6":
>
> $ cat demo.py
> # -*- coding: iso-8859-15 -*-
>
> print "first unicode:"
> print u"Sch��n"
>
> print "then bytes:"
> print "Sch��n"
>
> But when I run the code:
>
> $ python demo.py
> first unicode:
> Schöön
> then bytes:
> Sch��n
>
> There are other advantages, too:
>
 print "Schöön".upper()
> SCHööN
 print u"Schöön".upper()
> SCHÖÖN
 print "Schöön"[:4]
> Sch�
 print u"Schöön"[:4]
> Schö
>
Cool :-)
Thanks for the education.

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


Why does the insert after list function fail?

2016-09-22 Thread 380162267qq
A=["1","2","3"]
print(list(map(float,A)).insert(0,1))

I want to insert 1 at the head of the list but this gives me a surprise
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why does the insert after list function fail?

2016-09-22 Thread John Gordon
In <39ec91a8-eeae-489f-9237-9d9a481a8...@googlegroups.com> 
38016226...@gmail.com writes:

> A=["1","2","3"]
> print(list(map(float,A)).insert(0,1))

> I want to insert 1 at the head of the list but this gives me a surprise

insert() does not return anything; it modifies the existing list in-place.

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

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


Re: Why does the insert after list function fail?

2016-09-22 Thread Wildman via Python-list
On Thu, 22 Sep 2016 12:29:12 -0700, 380162267qq wrote:

> A=["1","2","3"]
> print(list(map(float,A)).insert(0,1))
> 
> I want to insert 1 at the head of the list but this gives me a surprise

I am not certain about what you are doing so I might be way off here.
The following will insert 1 at the head of the list...

Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> A=["1","2","3"]
>>> list.insert(A,0,"1")
>>> print(A)
['1', '1', '2', '3']

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: strings and ints consistency - isinstance

2016-09-22 Thread Larry Hudson via Python-list

On 09/22/2016 06:40 AM, Sayth Renshaw wrote:
[snip...]


True it failed, just actually happy to get it to fail or pass successfully on 
int input.

Just felt it was a clearer and more consistent approach to verifying input, 
then most of the varied and rather inconsistent approaches I have seen in 
trying to get this to work.

Half opt for try except the other half if else and then implement them largely 
differently. Every many and varied approach str2bool(), isalpha() using list 
with isinstance(var, [ int, str, bool]) etc.

Anyway back to the old drawing board.

Cheers

Sayth



IMHO...  This sort of thing deserves to be written as a separate function which can then be 
called anytime, anyplace.  This keeps your validation and repeated input in one place and is 
done automatically, and lets your main program simply assume the input is valid.


For example, here is the help message for the number input function I wrote for my personal 
utility library:


---
get_num(prmt, min_val=None, max_val=None, flt=False)

Get a number from the console

Parameters:
prmt:   The prompt to be used with the input function, required.
min_val:The minimum permissible value, or None if no minimum (the 
default)
max_val:The maximum permissible value, or None if no maximum (the 
default)
flt:If True, accepts and returns floats
If False, accepts and returns integers (the default)

Invalid input or out-of-range values are not accepted and a warning message
is displayed.  It will then repeat the input prompt for a new value.
---

Admittedly, this may be overkill for general use, but it IS very handy.  Even if it is overkill, 
it is still very easy to use.  Similar validated input functions are useful as well — such as a 
Yes/No function among others.


If you're interested, I could post the source for this version, but if you think of it as a 
generic function rather than for a specific situation, it is pretty straight-forward to write. 
something similar.


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


Re: strings and ints consistency - isinstance

2016-09-22 Thread Steve D'Aprano
On Thu, 22 Sep 2016 11:40 pm, Sayth Renshaw wrote:

> True it failed, just actually happy to get it to fail or pass successfully
> on int input.

But it doesn't. It raises ValueError no matter what you enter.





-- 
Steve
“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: How to import all things defined the files in a module directory in __init__.py?

2016-09-22 Thread Ben Finney
Peng Yu  writes:

> On Wed, Sep 21, 2016 at 11:14 PM, Ben Finney  
> wrote:
> > [Importing ‘*’ from a module] will also make the names in the code
> > impossible to automatically match against where they came from.
> > Explicit is better than implicit; you are proposing to make an
> > unknown horde of names in the code implicit and untraceable.
>
> This will make refactoring easy. If everything is explicit, when one
> do refactoring, at two places need to be changed which can be a
> burden.

That's completely backward: Importing ‘*’ from the module makes
refactoring significantly *more* difficult.

With explicit ‘import foo; foo.lorem()’, an automated tool can know that
when ‘lorem’ changes to a different name, this module's use of
‘foo.lorem’ should also change.

With non-explicit ‘from foo import *; lorem()’, then an automated too
has *no way* of knowing that ‘lorem’ should change when you alter that
name in the ‘foo’ module.

So no, what you say above is the opposite of correct. Instead, using
star import makes a rename *more* difficult to do correctly.

-- 
 \  “Faith is generally nothing more than the permission religious |
  `\ people give to one another to believe things strongly without |
_o__)  evidence.” —Sam Harris, _Letter to a Christian Nation_ 2006 |
Ben Finney

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


Re: How to import all things defined the files in a module directory in __init__.py?

2016-09-22 Thread Peng Yu
On Thu, Sep 22, 2016 at 8:35 PM, Ben Finney  wrote:
> Peng Yu  writes:
>
>> On Wed, Sep 21, 2016 at 11:14 PM, Ben Finney  
>> wrote:
>> > [Importing ‘*’ from a module] will also make the names in the code
>> > impossible to automatically match against where they came from.
>> > Explicit is better than implicit; you are proposing to make an
>> > unknown horde of names in the code implicit and untraceable.
>>
>> This will make refactoring easy. If everything is explicit, when one
>> do refactoring, at two places need to be changed which can be a
>> burden.
>
> That's completely backward: Importing ‘*’ from the module makes
> refactoring significantly *more* difficult.
>
> With explicit ‘import foo; foo.lorem()’, an automated tool can know that
> when ‘lorem’ changes to a different name, this module's use of
> ‘foo.lorem’ should also change.

Is there such a good automated tool for python refactoring?

> With non-explicit ‘from foo import *; lorem()’, then an automated too
> has *no way* of knowing that ‘lorem’ should change when you alter that
> name in the ‘foo’ module.
>
> So no, what you say above is the opposite of correct. Instead, using
> star import makes a rename *more* difficult to do correctly.
>
> --
>  \  “Faith is generally nothing more than the permission religious |
>   `\ people give to one another to believe things strongly without |
> _o__)  evidence.” —Sam Harris, _Letter to a Christian Nation_ 2006 |
> Ben Finney
>
> --
> https://mail.python.org/mailman/listinfo/python-list



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


Automated refactoring tools (was: How to import all things defined the files in a module directory in __init__.py?)

2016-09-22 Thread Ben Finney
Peng Yu  writes:

> Is there such a good automated tool for python refactoring?

This sounds like a job for — Bicycle Repair Man!

Watch him extract jumbled code into well ordered classes.

Gasp, as he renames all occurrences of a method.

Thank You Bicycle Repair Man!

http://bicyclerepair.sourceforge.net/>

There is also Rope https://pypi.python.org/pypi/rope> which is a
library used in numerous programming environments, including Emacs
https://pypi.python.org/pypi/ropemacs>.

-- 
 \   “I just got out of the hospital; I was in a speed-reading |
  `\ accident. I hit a bookmark and flew across the room.” —Steven |
_o__)   Wright |
Ben Finney

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


Re: Why does the insert after list function fail?

2016-09-22 Thread Jussi Piitulainen
38016226...@gmail.com writes:

> A=["1","2","3"]
> print(list(map(float,A)).insert(0,1))
>
> I want to insert 1 at the head of the list but this gives me a surprise

Is it the same surprise that you get from print([1,2,3].insert(0,1))?

Or the more advanced surprise from print(A.insert(0,1))?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: h(re) for help, import re - on NameError

2016-09-22 Thread Veek M
Chris Angelico wrote:

> On Thu, Sep 22, 2016 at 8:10 PM, Veek M  wrote:
>> Is there a way to use .pythonrc.py to provide a help function that
>> autoloads whatever module name is passed like so:
>> \>>> h(re)
>>
>> I tried inheriting site._Helper and overriding __init__ and __call__
>> but that didn't work, also I don't know how to deal/trap/catch the
>> NameError (no quotes on h(re)) - is there a way to insert a
>> try/except block around the >>> prompt?
>>
>> I hate having to: import whatever every-time i forget. Actually could
>> I ditch the () in h(re) and just do: h re - the joy of that :p
> 
> You could use sys.excepthook to catch the NameError. I don't know of a
> way to catch the SyntaxError and look at the original text, but with
> NameError it's pretty easy:
> 
> def excepthook(t,v,tb):
> if t is NameError:
> n = v.args[0].split("'")[1]
> globals()[n] = __import__(n)
> exec(tb.tb_frame.f_code, tb.tb_frame.f_globals)
> else:
> excepthook.old(t,v,tb)
> 
> import sys
> excepthook.old = sys.excepthook
> sys.excepthook = excepthook
> 
> Paste that into interactive Python and give it a try. Be aware that
> it'll attempt to import *any* dud name, so it'll potentially slow
> stuff down any time you typo. Also, it re-executes the current
> traceback frame, which may or may not be appropriate; it's fine for
> help(re), but not otherwise.
> 
> As an alternative, you could inspect tb.tb_frame.f_code to see if it
> matches "help(x)", and if it does, simply re-execute it with the
> string form of the name:
> 
> exec(tb.tb_frame.f_code, tb.tb_frame.f_globals, {n: n})
> 
> This works because help('re') does the same thing as help(re), so by
> effectively setting re="re", you gain that functionality without
> actually importing into the global namespace.
> 
> Adequately recognizing help(re) without false positives is left as an
> exercise for the reader. :)
> 
> ChrisA

works great :) - okay so you save and replace the default exception 
handler for the interpreter. Then when the procedure is called, check to 
see if type is NameError - if yes, then value contains the error string 
with module name, so you split and extract module name, and import the 
module and map it to a name in the global NS and hey presto (run the old 
code with the modified NS - that's a bit funky)!

Regarding fiddling with the code-object, yep, 
tb.tb_frame.f_code.co_names has a tuple ('h', 're') I suppose that's 
clean because it's your input after all vs splitting on something system 
generated (like an error message) 

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


Re: Pasting code into the cmdline interpreter

2016-09-22 Thread Gregory Ewing

eryk sun wrote:

if we see
a read that returns less than the buffer size but doesn't end on a
newline, then for a terminal, and only a terminal, I think we can
infer Ctrl+D was typed and handle it as EOF.


I don't think it would be wise to rely on that. There is
no promise that any given read() call will read all the
data that's available.

Even if it worked, I'm not sure that this behaviour would
be desirable. Some programs may rely on the current
behaviour, e.g. shells that do auto-completion when you
type ctrl-D on a non-empty line.

At the very least it would make programs written in
Python behave differently from any other unix program
when reading from a terminal, which I don't think is
a good idea.

--
Greg

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


Re: h(re) for help, import re - on NameError

2016-09-22 Thread Peter Otten
Veek M wrote:

> Is there a way to use .pythonrc.py to provide a help function that
> autoloads whatever module name is passed like so:

By the way, the current help() already loads a module if you pass its name 
as a string:

$ echo 'print("importing foo")' >  foo.py
$ python3
Python 3.4.3 (default, Sep 14 2016, 12:36:27) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help("foo")
importing foo
Help on module foo:

NAME
foo

[snip]


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