Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Ethan Furman

On 05/23/2017 08:47 PM, breamore...@gmail.com wrote:


Well that's what is says here https://github.com/ofek/venum so it must be true. 
 Please move over Ethan, your time is up :-)


No comment.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Chris Angelico
On Wed, May 24, 2017 at 5:22 PM, Ethan Furman  wrote:
> On 05/23/2017 08:47 PM, breamore...@gmail.com wrote:
>
>> Well that's what is says here https://github.com/ofek/venum so it must be
>> true.  Please move over Ethan, your time is up :-)
>
>
> No comment.
>

# No longer no comment.

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


threading.Semaphore or gevent.lock.Semaphore

2017-05-24 Thread Sergey
Hello,

I'm developing Flask app, processed by gevent.wsgi.WSGIServer.
If I need to isolate some pieces of code inside request handlers, can I use 
threading.Lock?
If I need semaphore, must I use threading.Semaphore or gevent.lock.Semaphore?
What is the difference between them?

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


Re: Building a PDF from Byte-of-Python

2017-05-24 Thread ElChino

Dennis Lee Bieber wrote:


As for creating a PDF -- that is described in the about.md file (it
uses "gitbook")


Thanks. Tried Gitbook after downloading it. Yuk!
But I had some success using "sphinx-quickstart --batchfile"
and tweaking the generated source/conf.py file and a
hand-generated index.md file.





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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Steve D'Aprano
On Wed, 24 May 2017 01:47 pm, breamore...@gmail.com wrote:

> Well that's what is says here https://github.com/ofek/venum so it must be
> true.  Please move over Ethan, your time is up :-)

The page says:

venum provides an Enum that is actually just a namedtuple, but 
easier to create. This means an Enum can be created during 
program execution and members are truly immutable (can't 
dynamically add new ones). Also, this saves a bit of space 
over the stdlib's Enum.


(1) Std lib enums are created during program execution too.

(2) Being namedtuples is a negative, not a positive.

(3) Members being immutable may, or may not, be a good thing, depending on
the application.

(4) If it is true that venum uses less space (memory? disk space?) than
enum, that would be a positive.


The example given is:

>>> from venum import Enum
>>> ContentTypes = Enum(
... ('JSON', 'application/json; charset=utf-8'),
... ('HTML', 'text/html; charset=utf-8'),
... ('JS', 'text/javascript; charset=utf-8'),
... ('XML', 'application/xml'),
... ('TEXT', 'text/plain; charset=utf-8'),
... ('JPEG', 'image/jpeg'),
... ('PNG', 'image/png'),
... ('YAML', 'application/x-yaml'),
... name='ContentTypes'
... )


but I'm not convinced that's "verifiably better" than:

from enum import Enum
class ContentTypes(Enum):
JSON = 'application/json; charset=utf-8'
HTML = 'text/html; charset=utf-8'
JS = 'text/javascript; charset=utf-8'
XML = 'application/xml'
TEXT = 'text/plain; charset=utf-8'
JPEG = 'image/jpeg'
PNG = 'image/png'
YAML = 'application/x-yaml'



Although I wonder:

- maybe the enumeration (the class ContentTypes) could have a nicer repr
than 



- maybe you could add functionality to freeze the enumeration so that new
members cannot be added?


class ContentTypes(Enum, frozen=True)
class ContentTypes(FrozenEnum)



-- 
Steve
Emoji: a small, fuzzy, indistinct picture used to replace a clear and
perfectly comprehensible word.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Chris Angelico
On Wed, May 24, 2017 at 7:10 PM, Steve D'Aprano
 wrote:
> Although I wonder:
>
> - maybe the enumeration (the class ContentTypes) could have a nicer repr
> than
>
> 
>
> - maybe you could add functionality to freeze the enumeration so that new
> members cannot be added?
>
>
> class ContentTypes(Enum, frozen=True)
> class ContentTypes(FrozenEnum)

I'm sure it could be done. But would it really benefit anyone
anything? Java has "final" classes, which can't be subclassed; and I
haven't heard many people saying "I wish you would declare more of
your classes final" or "I wish Python let you declare a class as
final".

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


Re: How to install Python package from source on Windows

2017-05-24 Thread Paul Moore
On Monday, 15 May 2017 22:42:22 UTC+1, Deborah Swanson  wrote:
> MRAB wrote, on Monday, May 15, 2017 12:44 PM
> > 
> > On 2017-05-15 13:52, eryk sun wrote:
> > > On Mon, May 15, 2017 at 6:37 AM, Deborah Swanson 
> > >  wrote:
> > >>
> > >> Where did you find recordclass-0.4.3-cp34-cp34m-win32.whl?  There 
> > >> weren't any win32 builds on 
> > https://pypi.python.org/pypi/recordclass.
> > > 
> > > It's in the 
> > middle of the file list:
> > > 
> > > recordclass-0.4.3-cp34-cp34m-win32.whl (md5) Python Wheel cp34 
> > > 2017-04-17 17KB
> > > 
> > > Maybe you're looking at a cached page in your browser? But that 
> > > doesn't explain why pip doesn't see it.
> > > 
> > >> Maybe I can find an earlier 3 build that won't demand Visual C++.
> > > 
> > > The wheel doesn't need a compiler. It has an ABI tag because it 
> > > already includes the compiled extension module.
> > > 
> > I used pip to install into Python 3.4 (32-bit) from PyPI. It fetched 
> > "recordclass-0.4.3.tar.gz" and compiled it instead of fetching 
> > "recordclass-0.4.3-cp34-cp34m-win32.whl".
> > 
> > Why?
> 
> Excellent question, though I have no clue what the answer is.
> 
> > Come to think of it, what's that "cp34m" in the name? I don't have
> that 
> > in the regex module's wheels, I have "none" instead.
> 
> Another excellent question. "cp" in "cp34m" might stand for C++, but if
> so, what's the rest of it mean? Or maybe "CPython 3.4" plus "m"
> (whatever "m" stands for)?
> 
> What's "the regex module's wheels"? I certainly don't know, though I
> know vague outines of what "regex" and "wheel" are.
>  
> > Rename "recordclass-0.4.3-cp34-cp34m-win32.whl" to 
> > "recordclass-0.4.3-cp34-name-win32.whl".
> > 
> > With the new name, it installs and seems to work!
> 
> Most excellent and I will try it. 

I don't know whether you solved your issue, but in case you didn't, the problem 
is that the "cp34m" part of the name indicates the "ABI" used in the extension 
(roughly, how the C part of the code links to the Python interpreter). Older 
versions of pip (such as the one shipped with Python 3.4, which is itself a bit 
old now) didn't recognise that tag, and so won't install that wheel.

The best way to fix this is to upgrade the copy of pip you have, using

   python -m pip install --upgrade pip

When you do that, you'll get a version of pip that recognises the "cp34m" tag, 
and "pip install recordclass" should then just work.

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


Re: SSL certificate of a server on Windows

2017-05-24 Thread COPIN Mathieu.
Le mardi 23 mai 2017 19:10:11 UTC+2, Irmen de Jong a écrit :
> On 23-5-2017 10:19, COPIN Mathieu. wrote:
> > Hi, 
> > 
> > I want to get a server certificate from the host-name.
> > 
> > I know I could do something like :
> >> call(openssl, s_client, -showcerts, -connect, hostname:port)
> > 
> > 
> > But the thing is to do it without openssl because I want to run the script 
> > on Windows.
> > 
> > Any suggestions ?
> > Mathieu
> > 
> 
> I guess you mean: without calling "openssl.exe"
> 
> 
> import ssl
> cert = sll.get_server_certificate(("www.google.com", 443))
> 
> See
> https://docs.python.org/3.6/library/ssl.html#ssl.get_server_certificate
> 
> 
> 
> Irmen

That's what I neeeded, thank you !
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Scala considering significant indentation like Python

2017-05-24 Thread Grant Edwards
On 2017-05-23, Ben Finney  wrote:
> Grant Edwards  writes:
>
>> On 2017-05-23, Michael Torrie  wrote:
>> > Sometimes things get longer than a page (like a class definition).
>>
>> A nice folding mode works nicely for that sort of thing. I normally
>> use emacs, but it doesn't seem to have a folding mode built-in, and
>> the add-on one's I've tried didn't seem to work in a very useful way.
>
> The ‘set-selective-display’ command will collapse the current buffer's
> text to lines indented to the specified number of columns; the same
> command with no argument will expand the buffer to normal again. The
> command is bound to ‘C-x $’ in default Emacs.

Thanks for the tip!

I'd been looking at folding modes, and never ran across that.

-- 
Grant Edwards   grant.b.edwardsYow! I own seven-eighths of
  at   all the artists in downtown
  gmail.comBurbank!

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Steve D'Aprano
On Wed, 24 May 2017 10:07 pm, Chris Angelico wrote:

> On Wed, May 24, 2017 at 7:10 PM, Steve D'Aprano
>  wrote:
>> Although I wonder:
>>
>> - maybe the enumeration (the class ContentTypes) could have a nicer repr
>> than
>>
>> 
>>
>> - maybe you could add functionality to freeze the enumeration so that new
>> members cannot be added?
>>
>>
>> class ContentTypes(Enum, frozen=True)
>> class ContentTypes(FrozenEnum)
> 
> I'm sure it could be done. But would it really benefit anyone
> anything? Java has "final" classes, which can't be subclassed; and I
> haven't heard many people saying "I wish you would declare more of
> your classes final" or "I wish Python let you declare a class as
> final".

I've wanted that from time to time. Never quite enough to make my own
metaclass to get it, or enough to write a C extension, but if the
functionality existed, I would have used it.

Same as if Python supported constants (names that can only be assigned to
once). Again, the pain of building a custom "constant-like" solution is
greater than the benefit, so I've done without.

But if Python did support these things, maybe the compiler could make a few
optimizations, or maybe we could write a few less unit tests, or catch a
few bugs a little earlier... or not.


It's just a different way at looking at minimalism. Guido says, the language
should be as small as possible. If you don't want to assign to a name, then
just don't assign to it. No need to build support for constants into the
language when you can trust the developer to Don't Do That.

(But note that Python does support read-only attributes, a related concept.)

While other language designers take on minimalism is that the entity in
question should support as few things as possible. If you have a name that
you don't want to ever be rebound to a different value, then the language
shouldn't support rebinding that name, since you can't trust the developer
to Don't Do That.

Neither view is entirely right or wrong, which is why there will always be
arguments over it. But I'll note that Python has supported read-only
properties for, oh, a decade or more, and do I hear people complaining
about how much libraries and applications over-use and abuse properties?
Not very often.




-- 
Steve
Emoji: a small, fuzzy, indistinct picture used to replace a clear and
perfectly comprehensible word.

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


Re: Scala considering significant indentation like Python

2017-05-24 Thread Rustom Mody
On Wednesday, May 24, 2017 at 2:14:15 AM UTC+5:30, Ben Finney wrote:
> Grant Edwards grant.b.edwards writes:
> 
> > On 2017-05-23, Michael Torrie  wrote:
> > > Sometimes things get longer than a page (like a class definition).
> >
> > A nice folding mode works nicely for that sort of thing. I normally
> > use emacs, but it doesn't seem to have a folding mode built-in, and
> > the add-on one's I've tried didn't seem to work in a very useful way.
> 
> The ‘set-selective-display’ command will collapse the current buffer's
> text to lines indented to the specified number of columns; the same
> command with no argument will expand the buffer to normal again. The
> command is bound to ‘C-x $’ in default Emacs.

I would have thought hideshow minor mode is what is desired??

(info "(emacs)Hideshow")

Which however happens to have rather ridiculous keybindings
If you like org-mode style TAB and Shift-TAB here's a hack  — barely tried out!!

--
;; Add to your init
;; To get Tab and Shift-Tab to behave as in org-mode

(defvar rusi/hs-hide nil "Current state of hideshow for toggling all.")
;;;###autoload
(defun rusi/hs-toggle-all () "Toggle hideshow all."
  (interactive)
  (setq rusi/hs-hide (not rusi/hs-hide))
  (if rusi/hs-hide
  (hs-hide-all)
(hs-show-all)))

(add-hook 'hs-minor-mode-hook
  (lambda ()
(define-key hs-minor-mode-map (kbd "") 'rusi/hs-toggle-all)
(define-key hs-minor-mode-map (kbd "") 'hs-toggle-hiding)))

(add-hook 'python-mode-hook 'hs-minor-mode)
(add-hook 'c-mode-hook  'hs-minor-mode)
(add-hook 'emacs-lisp-mode-hook 'hs-minor-mode)
;; etc

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


EuroPython 2017: Social event tickets available

2017-05-24 Thread M.-A. Lemburg
After trainings and talks, EuroPython is going (Coco)nuts ! Join us
for the EuroPython social event in Rimini, which will be held in the
Coconuts Club on Thursday, July 13th.


   * EuroPython 2017 Social Event *

 https://ep2017.europython.eu/en/events/social-event/


Tickets for the social event are not included in the conference
ticket. They are now available in our ticket store (listed under
‘Goodies’) for the price of 25 EUR.


   * EuroPython 2017 Ticket Store *

https://ep2017.europython.eu/p3/cart/


The social event ticket includes an aperitivo buffet of Italian
specialties, a choice of two drinks and a reserved area in the club
from 19:00 to 22:00. The club will open to the general public after
that.


Enjoy,
--
EuroPython 2017 Team
http://ep2017.europython.eu/
http://www.europython-society.org/

PS: Please forward or retweet to help us reach all interested parties:
https://twitter.com/europython/status/867390553973030912
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


constants in Python [was: Verifiably better, validated Enum for Python]

2017-05-24 Thread Ethan Furman

On 05/24/2017 07:31 AM, Steve D'Aprano wrote:

On Wed, 24 May 2017 10:07 pm, Chris Angelico wrote:

On Wed, May 24, 2017 at 7:10 PM, Steve D'Aprano wrote:



Although I wonder:

- maybe the enumeration (the class ContentTypes) could have a nicer repr
than



- maybe you could add functionality to freeze the enumeration so that new
members cannot be added?


I'm sure it could be done. But would it really benefit anyone
anything? Java has "final" classes, which can't be subclassed; and I
haven't heard many people saying "I wish you would declare more of
your classes final" or "I wish Python let you declare a class as
final".



Same as if Python supported constants (names that can only be assigned to
once). Again, the pain of building a custom "constant-like" solution is
greater than the benefit, so I've done without.


Check out the NamedConstant class from aenum [1] -- it's probably as close as
you're going to get:

>>> from aenum import NamedConstant
>>> class Konstant(NamedConstant):
... PI = 3.14159
... TAU = 2 * PI

>>> Konstant.PI


>> print(Konstant.PI)
3.14159

>>> Konstant.PI = 'apple'
Traceback (most recent call last):
...
AttributeError: cannot rebind constant 

>>> del Konstant.PI
Traceback (most recent call last):
...
AttributeError: cannot delete constant 



Neither view is entirely right or wrong, which is why there will always be
arguments over it. But I'll note that Python has supported read-only
properties for, oh, a decade or more, and do I hear people complaining
about how much libraries and applications over-use and abuse properties?
Not very often.


But getting around a Python-code read-only property is trivial -- not pretty, 
but trivial.

--
~Ethan~


[1] https://pypi.python.org/pypi/aenum
--
https://mail.python.org/mailman/listinfo/python-list


Re: Concatenating files in order

2017-05-24 Thread Peter Otten
Dennis Lee Bieber wrote:

> On Tue, 23 May 2017 21:42:45 +0100, bartc  declaimed the
> following:
> 
>>Is it necessary to sort them? If XXX is known, then presumably the first
>>file will be called XXX_chunk_0, the next XXX_chunk_1 and so on.
>>
> 
> XXX_chunk_1
> XXX_chunk_10
> XXX_chunk_2

This is a problem you run into if you do sort the filenames (the wrong way, 
alphabetically). If I understand Bart correctly he suggests something like

with open(DESTFILE, "wb") as outstream:
for filename in map("XXX_chunk_{}".format, itertools.count()):
try:
with open(filename, "rb") as instream:
shutil.copyfileobj(instream, outstream)
except FileNotFoundError:
break


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


Re: Concatenating files in order

2017-05-24 Thread bartc

On 24/05/2017 16:41, Peter Otten wrote:

Dennis Lee Bieber wrote:


On Tue, 23 May 2017 21:42:45 +0100, bartc  declaimed the
following:


Is it necessary to sort them? If XXX is known, then presumably the first
file will be called XXX_chunk_0, the next XXX_chunk_1 and so on.



XXX_chunk_1
XXX_chunk_10
XXX_chunk_2


This is a problem you run into if you do sort the filenames (the wrong way,
alphabetically). If I understand Bart correctly he suggests something like

with open(DESTFILE, "wb") as outstream:
for filename in map("XXX_chunk_{}".format, itertools.count()):
try:
with open(filename, "rb") as instream:
shutil.copyfileobj(instream, outstream)
except FileNotFoundError:
break



Yes, that sort of thing, provided the first file end with _0, XXX is 
known, and the endings are consecutive and well-formed. I was going to 
post some code but wasn't sure how 'with' dealt with file errors:


 i = 0

 while 1:
 file = "XXX_chunk_"+str(i)
 print (file)
 with open(file) as inf:
   
 i += 1


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


Hi everyone

2017-05-24 Thread Spaarwiel
Hi there, i was always interested in coding but never took the time to learn it.

So at age 34 i'm going to try and see if i can win this.

Saw on a website this is good group page to come for help so i will def. be 
asking alot of questions here :)

B.t.w i have no knowledge of coding whatsoever so i'm starting lower that the 
bottom.

Anyways cheers!

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


Re: Hi everyone

2017-05-24 Thread Ian Kelly
On Wed, May 24, 2017 at 11:20 AM, Spaarwiel  wrote:
>
> Hi there, i was always interested in coding but never took the time to
learn it.
>
> So at age 34 i'm going to try and see if i can win this.
>
> Saw on a website this is good group page to come for help so i will def.
be asking alot of questions here :)
>
> B.t.w i have no knowledge of coding whatsoever so i'm starting lower that
the bottom.

Please note this list is specifically for discussion of the Python
language, not coding in general. If you have Python questions you're
welcome to ask them here but you may find the Python tutor mailing list a
better resource for learning: https://mail.python.org/mailman/listinfo/tutor
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Concatenating files in order

2017-05-24 Thread Peter Otten
bartc wrote:

> On 24/05/2017 16:41, Peter Otten wrote:
>> Dennis Lee Bieber wrote:
>>
>>> On Tue, 23 May 2017 21:42:45 +0100, bartc  declaimed the
>>> following:
>>>
 Is it necessary to sort them? If XXX is known, then presumably the
 first file will be called XXX_chunk_0, the next XXX_chunk_1 and so on.

>>>
>>> XXX_chunk_1
>>> XXX_chunk_10
>>> XXX_chunk_2
>>
>> This is a problem you run into if you do sort the filenames (the wrong
>> way, alphabetically). If I understand Bart correctly he suggests
>> something like
>>
>> with open(DESTFILE, "wb") as outstream:
>> for filename in map("XXX_chunk_{}".format, itertools.count()):
>> try:
>> with open(filename, "rb") as instream:
>> shutil.copyfileobj(instream, outstream)
>> except FileNotFoundError:
>> break
>>
> 
> Yes, that sort of thing, provided the first file end with _0, XXX is
> known, and the endings are consecutive and well-formed. I was going to
> post some code but wasn't sure how 'with' dealt with file errors:
> 
>   i = 0
> 
>   while 1:
>   file = "XXX_chunk_"+str(i)
>   print (file)
>   with open(file) as inf:
> 
>   i += 1
 
Inside the with suite the author of the context manager gets to decide. 
E. g. you may decide to swallow everyhing:

>>> from contextlib import contextmanager
>>> 
>>> @contextmanager
... def catch():
...try: yield
...except: pass
... 
>>> with catch(): 1/0
... 
>>>

For whatever open() returns the reaction is to close the file and propagate 
the error:

>>> with open("/dev/null", "rb") as f: 1/0
... 
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: division by zero
>>> f.closed
True

However, in the case of a failing open() the file's __enter__ method is not 
yet called and so the behaviour is the same as for the conventional

inf = open(file)


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


dictConfig: logging.StreamHandler object is not iterable.

2017-05-24 Thread Tim Williams
(Apologies for using Google Groups to post)

I'm trying to use dictConfig to configure logging. I keep running into the 
error that the logging.StreamHandler object is not iterable.

I'm using Python 3.4.3 on a Windows 7 box.

C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC 
v.1600 64 bit (AMD64)]


I want to use the configobj module to create the dictionary from an INI file, 
but that's not the problem I'm having. 

Here is my test code:
#
import logging, logging.config, logging.handlers
import configobj

# config = configobj.ConfigObj('loggingtest.ini')
# config['version']=eval(config['version'])
config = {
  'version': 1, 
  'level': 'INFO',
  'formatters': {'fmt1': {'format': '%(asctime)s: (%(levelname)s)  
%(message)s', 
  'datefmt': ''}
 }, 
  'loggers': {'root': {'level': 'INFO', 
   'handlers': 'cfg://handlers.console'}, 
  'file': {'level': 'WARN', 
   'handlers': 'cfg://handlers.file'}
  }, 
  'handlers': {'console': {'class': 'logging.StreamHandler', 
   'level': 'INFO', 
   'stream': 'ext://sys.stdout'}, 
   'file': {'class': 'logging.FileHandler', 
'level': 'WARN', 
'filename': 'test.log'}
   }, 
  }


logging.config.dictConfig(config)


When I run it, I get this traceback:

Traceback (most recent call last):
  File "C:\Python34\lib\logging\config.py", line 611, in configure
self.configure_logger(name, loggers[name])
  File "C:\Python34\lib\logging\config.py", line 775, in configure_logger
self.common_logger_config(logger, config, incremental)
  File "C:\Python34\lib\logging\config.py", line 767, in common_logger_config
self.add_handlers(logger, handlers)
  File "C:\Python34\lib\logging\config.py", line 748, in add_handlers
for h in handlers:
TypeError: 'StreamHandler' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "L:\workspace\MyPython\src\testlog.py", line 27, in 
logging.config.dictConfig(config)
  File "C:\Python34\lib\logging\config.py", line 789, in dictConfig
dictConfigClass(config).configure()
  File "C:\Python34\lib\logging\config.py", line 614, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure logger 'root': 'StreamHandler' object is not 
iterable


I even tried creating a JSON file to create the dictionary, and got the same 
error.

Thanks for any help
--
Tim
-- 
https://mail.python.org/mailman/listinfo/python-list


Logging function calls without changing code

2017-05-24 Thread Rajat Sharma
Hi Everyone, 

Is there a way to log all function calls of a class without changing anything 
in that class.

What I mean to say is if I have written a class previously and I want to enable 
logging in that then I would probably need to write the following before my 
function calls-

logger.debug(' called...')

But, is there a way that I do not need to change my existing code and can 
create a wrapper around that existing class or something else which can help me 
do the same?

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Ian Kelly
On Wed, May 24, 2017 at 3:10 AM, Steve D'Aprano
 wrote:
> The page says:
>
> venum provides an Enum that is actually just a namedtuple,

No kidding. This is the entirety of the code for it:


from collections import namedtuple


def Enum(*args, **kwargs):
fields, values = zip(*args)
return namedtuple(kwargs.get('name', 'Enum'), fields)(*values)


I wanted to verify that venum was better so I started reading through
the features of https://docs.python.org/3/library/enum.html to confirm
that venum also supports them. Turns out, it supports almost none of
them.

"Enumeration members have human readable string representations" - Nope.
"...while their repr has more information" - Nope.
"The type of an enumeration member is the enumeration it belongs to" - Nope.
"Enum members also have a property that contains just their item name" - Nope.
"Enumerations support iteration, in definition order" - Finally a yes,
with the caveat that iterating over the venum only results in the
values. Although one could iterate over ._fields to get the names.
"Enumeration members are hashable, so they can be used in dictionaries
and sets" - venum members are just the values, so they're hashable if
and only if the values are hashable.

Programmatic access by value - No, you'd have to iterate over the
venum to search for the value.
Programmatic access by name - Yes, by using getattr, no convenient syntax.
Aliases for duplicate values - Depends entirely upon the identity
semantics of how the values are specified. Enum(('a', 1), ('b', 1))
would create an alias in CPython, but Enum(('a', 100), ('b',
100)) would not.
@unique decorator - no support
automatic values - no support
Iteration excludes aliases - No.
__members__ attribute - Sort of, using _fields and getattr.

Enumeration members compared by identity - Likely to cause surprises
since venum members are just values.
Ordered comparisons explicitly not supported - No, venum members may
or may not be orderable.
"Equality comparisons are defined though" - Only insofar as they're
defined for the values
"Comparisons against non-enumeration values will always compare not
equal" - No such guarantee
Defining enum methods (including special methods) and properties - no support
"Subclassing an enumeration is allowed only if the enumeration does
not define any members" - venums aren't classes so they can't be
subclassed, period.
"Enumerations can be pickled and unpickled" - Only if the value supports it.

"The Enum class is callable, providing the following functional API" -
Finally, an unqualified yes!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dictConfig: logging.StreamHandler object is not iterable.

2017-05-24 Thread Peter Otten
Tim Williams wrote:

> (Apologies for using Google Groups to post)
> 
> I'm trying to use dictConfig to configure logging. I keep running into the
> error that the logging.StreamHandler object is not iterable.
> 
> I'm using Python 3.4.3 on a Windows 7 box.
> 
> C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40)
> [MSC v.1600 64 bit (AMD64)]
> 
> 
> I want to use the configobj module to create the dictionary from an INI
> file, but that's not the problem I'm having.
> 
> Here is my test code:
> #
> import logging, logging.config, logging.handlers
> import configobj
> 
> # config = configobj.ConfigObj('loggingtest.ini')
> # config['version']=eval(config['version'])
> config = {
>   'version': 1,
>   'level': 'INFO',
>   'formatters': {'fmt1': {'format': '%(asctime)s: (%(levelname)s) 
>   %(message)s',
>   'datefmt': ''}
>  },
>   'loggers': {'root': {'level': 'INFO',
>'handlers': 'cfg://handlers.console'},

If I'm reading



"""
loggers - the corresponding value will be a dict in which each key is a 
logger name and each value is a dict describing how to configure the 
corresponding Logger instance.

The configuring dict is searched for the following keys:

[...]

handlers (optional). A list of ids of the handlers for this logger.
"""

correctly this should be

'loggers': {'root': {'level': 'INFO',
 'handlers': ['console']},


>   'file': {'level': 'WARN',
>'handlers': 'cfg://handlers.file'}

Same here: 

... 'handlers': ['file'] ...

>   },
>   'handlers': {'console': {'class': 'logging.StreamHandler',
>'level': 'INFO',
>'stream': 'ext://sys.stdout'},
>'file': {'class': 'logging.FileHandler',
> 'level': 'WARN',
> 'filename': 'test.log'}
>},
>   }
> 
> 
> logging.config.dictConfig(config)
> 
> 
> When I run it, I get this traceback:
> 
> Traceback (most recent call last):
>   File "C:\Python34\lib\logging\config.py", line 611, in configure
> self.configure_logger(name, loggers[name])
>   File "C:\Python34\lib\logging\config.py", line 775, in configure_logger
> self.common_logger_config(logger, config, incremental)
>   File "C:\Python34\lib\logging\config.py", line 767, in
>   common_logger_config
> self.add_handlers(logger, handlers)
>   File "C:\Python34\lib\logging\config.py", line 748, in add_handlers
> for h in handlers:
> TypeError: 'StreamHandler' object is not iterable
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
>   File "L:\workspace\MyPython\src\testlog.py", line 27, in 
> logging.config.dictConfig(config)
>   File "C:\Python34\lib\logging\config.py", line 789, in dictConfig
> dictConfigClass(config).configure()
>   File "C:\Python34\lib\logging\config.py", line 614, in configure
> '%r: %s' % (name, e))
> ValueError: Unable to configure logger 'root': 'StreamHandler' object is
> not iterable
> 
> 
> I even tried creating a JSON file to create the dictionary, and got the
> same error.
> 
> Thanks for any help
> --
> Tim


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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Chris Angelico
On Thu, May 25, 2017 at 12:31 AM, Steve D'Aprano
 wrote:
> On Wed, 24 May 2017 10:07 pm, Chris Angelico wrote:
>
>> I'm sure it could be done. But would it really benefit anyone
>> anything? Java has "final" classes, which can't be subclassed; and I
>> haven't heard many people saying "I wish you would declare more of
>> your classes final" or "I wish Python let you declare a class as
>> final".
>
> I've wanted that from time to time. Never quite enough to make my own
> metaclass to get it, or enough to write a C extension, but if the
> functionality existed, I would have used it.

>From what I've heard (albeit nothing more than anecdotal), the
frustration comes from Fred marking his class final because he thinks
nobody will need to subclass it, and then Joe coming along and wanting
to subclass Fred's class. So Fred might still think "final is great,
my stuff runs 0.1% faster", but Joe thinks "final is a pain in the
behind".

> Same as if Python supported constants (names that can only be assigned to
> once). Again, the pain of building a custom "constant-like" solution is
> greater than the benefit, so I've done without.
>
> But if Python did support these things, maybe the compiler could make a few
> optimizations, or maybe we could write a few less unit tests, or catch a
> few bugs a little earlier... or not.

Named constants would definitely be a possibility for the language, as
they'd be an optimization only. (And I'm sure macropy can do it,
although I haven't checked.) The benefit would be that you don't need
to do a LOAD_GLOBAL to fetch them, plus there's the possibility of
constant-folding (eg "HOURS_PER_DAY * MINUTES_PER_HOUR *
SECONDS_PER_MINUTE" could be folded down to just 86400, instead of
three loads and two binary multiplies). In theory, the benefit of a
final class is that the compiler can statically resolve method
lookups, but I don't think you can do that in Python anyway. Consider:

@final
class Ham:
def spam(self):
pass
def eggs(self):
return self.spam()
bacon = Ham()
bacon.eggs()

Before calling Ham.spam(), Python needs to check to see if bacon
itself has an attribute spam. So there's the same risk of annoying
people that Java has, plus it's not really going to benefit you all
that much unless you also prevent instance overrides.

Now, maybe that would be a valuable thing despite the semantic change.
I don't know. But I'm not going to push for it.

> It's just a different way at looking at minimalism. Guido says, the language
> should be as small as possible. If you don't want to assign to a name, then
> just don't assign to it. No need to build support for constants into the
> language when you can trust the developer to Don't Do That.
>
> (But note that Python does support read-only attributes, a related concept.)

AIUI, read-only attributes are less about "you're not allowed to
change this" and more about "changing this doesn't even make sense".

class ChunkedBuffer:
@property
def capacity(self):
return sum(chunk.capacity for chunk in self.chunks)

You can't just arbitrarily edit the capacity; which one would it
change? As a side effect, you CAN use this to enforce immutability,
but that isn't the point.

And hey. The lack of enforced read-only stuff means we don't get
people saying "look, I can change it using ctypes" :)

> While other language designers take on minimalism is that the entity in
> question should support as few things as possible. If you have a name that
> you don't want to ever be rebound to a different value, then the language
> shouldn't support rebinding that name, since you can't trust the developer
> to Don't Do That.
>
> Neither view is entirely right or wrong, which is why there will always be
> arguments over it. But I'll note that Python has supported read-only
> properties for, oh, a decade or more, and do I hear people complaining
> about how much libraries and applications over-use and abuse properties?
> Not very often.

No, and that's largely because Python has built a culture of "don't
use properties at all". The normal idiom in C++ is something like
this:

class Spam {
private:
int _x;
public:
Spam(int x) {_x = x;}
int get_x() {return _x;}
void set_x(int x) {_x = x;}
};

The normal idiom in Python is:

class Spam:
def __init__(self, x):
self.x = x

Look ma, no properties! So there's no abuse of properties either. But
in codebases that _do_ use @property heavily, yes, there definitely
are complaints about the over-use and abuse. Of course, that doesn't
mean that Python's way is inherently better; I'm sure that large C++
codebases have huge complaints about the over-use and abuse of public
data attributes instead of proper getters and setters. And that's fine
- for C++. Different language, different culture, different style.
Non-subclassable classes would be a perfectly acceptable thing in C++,
except for the fact that you don't need to, because you can get the
same benefits by just n

Re: dictConfig: logging.StreamHandler object is not iterable.

2017-05-24 Thread Tim Williams
On Wednesday, May 24, 2017 at 2:46:54 PM UTC-4, Tim Williams wrote:
> (Apologies for using Google Groups to post)
> 
> I'm trying to use dictConfig to configure logging. I keep running into the 
> error that the logging.StreamHandler object is not iterable.
> 
> I'm using Python 3.4.3 on a Windows 7 box.
> 
> C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) 
> [MSC v.1600 64 bit (AMD64)]
> 
> 
> I want to use the configobj module to create the dictionary from an INI file, 
> but that's not the problem I'm having. 
> 
> Here is my test code:
> #
> import logging, logging.config, logging.handlers
> import configobj
> 
> # config = configobj.ConfigObj('loggingtest.ini')
> # config['version']=eval(config['version'])
> config = {
>   'version': 1, 
>   'level': 'INFO',
>   'formatters': {'fmt1': {'format': '%(asctime)s: (%(levelname)s)  
> %(message)s', 
>   'datefmt': ''}
>  }, 
>   'loggers': {'root': {'level': 'INFO', 
>'handlers': 'cfg://handlers.console'}, 
>   'file': {'level': 'WARN', 
>'handlers': 'cfg://handlers.file'}
>   }, 
>   'handlers': {'console': {'class': 'logging.StreamHandler', 
>'level': 'INFO', 
>'stream': 'ext://sys.stdout'}, 
>'file': {'class': 'logging.FileHandler', 
> 'level': 'WARN', 
> 'filename': 'test.log'}
>}, 
>   }
> 
> 
> logging.config.dictConfig(config)
> 
> 
> When I run it, I get this traceback:
> 
> Traceback (most recent call last):
>   File "C:\Python34\lib\logging\config.py", line 611, in configure
> self.configure_logger(name, loggers[name])
>   File "C:\Python34\lib\logging\config.py", line 775, in configure_logger
> self.common_logger_config(logger, config, incremental)
>   File "C:\Python34\lib\logging\config.py", line 767, in common_logger_config
> self.add_handlers(logger, handlers)
>   File "C:\Python34\lib\logging\config.py", line 748, in add_handlers
> for h in handlers:
> TypeError: 'StreamHandler' object is not iterable
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
>   File "L:\workspace\MyPython\src\testlog.py", line 27, in 
> logging.config.dictConfig(config)
>   File "C:\Python34\lib\logging\config.py", line 789, in dictConfig
> dictConfigClass(config).configure()
>   File "C:\Python34\lib\logging\config.py", line 614, in configure
> '%r: %s' % (name, e))
> ValueError: Unable to configure logger 'root': 'StreamHandler' object is not 
> iterable
> 
> 
> I even tried creating a JSON file to create the dictionary, and got the same 
> error.
> 
> Thanks for any help
> --
> Tim

Peter,

Thanks. That did it for my dictionary.
What I'm really trying to do is use configobj to do this from an INI file. The 
one problem is that all the values are strings, hence the 

config['version']=eval(config['version'])

It looks like if I do something similar with the handlers in the loggers, like:

config['loggers']['root']['handlers']=eval(config['loggers']['root']['handlers'])
config['loggers']['file']['handlers']=eval(config['loggers']['file']['handlers'])

logging.config.dictConfig(dict(config))

seems to work.

I'm using configobj instead of configparser because configobj can nest 
sections. The INI file I'm trying to build has more sections for other things.

version = 1
level = INFO
[formatters]
[[fmt1]]
format = "%(asctime)s: (%(levelname)s)  %(message)s"
datefmt =
[handlers]
[[console]]
class = logging.StreamHandler
level = INFO
stream = ext://sys.stdout
[[file]]
class = logging.FileHandler
level = WARN
filename = test.log
[loggers]
[[root]]
level = INFO
handlers = [console]
[[file]]
level = WARN
handlers = ['file']
propagate = 1

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


Re: dictConfig: logging.StreamHandler object is not iterable.

2017-05-24 Thread Tim Williams
On Wednesday, May 24, 2017 at 2:46:54 PM UTC-4, Tim Williams wrote:
> (Apologies for using Google Groups to post)
> 
> I'm trying to use dictConfig to configure logging. I keep running into the 
> error that the logging.StreamHandler object is not iterable.
> 
> I'm using Python 3.4.3 on a Windows 7 box.
> 
> C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) 
> [MSC v.1600 64 bit (AMD64)]
> 
> 
> I want to use the configobj module to create the dictionary from an INI file, 
> but that's not the problem I'm having. 
> 
> Here is my test code:
> #
> import logging, logging.config, logging.handlers
> import configobj
> 
> # config = configobj.ConfigObj('loggingtest.ini')
> # config['version']=eval(config['version'])
> config = {
>   'version': 1, 
>   'level': 'INFO',
>   'formatters': {'fmt1': {'format': '%(asctime)s: (%(levelname)s)  
> %(message)s', 
>   'datefmt': ''}
>  }, 
>   'loggers': {'root': {'level': 'INFO', 
>'handlers': 'cfg://handlers.console'}, 
>   'file': {'level': 'WARN', 
>'handlers': 'cfg://handlers.file'}
>   }, 
>   'handlers': {'console': {'class': 'logging.StreamHandler', 
>'level': 'INFO', 
>'stream': 'ext://sys.stdout'}, 
>'file': {'class': 'logging.FileHandler', 
> 'level': 'WARN', 
> 'filename': 'test.log'}
>}, 
>   }
> 
> 
> logging.config.dictConfig(config)
> 
> 
> When I run it, I get this traceback:
> 
> Traceback (most recent call last):
>   File "C:\Python34\lib\logging\config.py", line 611, in configure
> self.configure_logger(name, loggers[name])
>   File "C:\Python34\lib\logging\config.py", line 775, in configure_logger
> self.common_logger_config(logger, config, incremental)
>   File "C:\Python34\lib\logging\config.py", line 767, in common_logger_config
> self.add_handlers(logger, handlers)
>   File "C:\Python34\lib\logging\config.py", line 748, in add_handlers
> for h in handlers:
> TypeError: 'StreamHandler' object is not iterable
> 
> During handling of the above exception, another exception occurred:
> 
> Traceback (most recent call last):
>   File "L:\workspace\MyPython\src\testlog.py", line 27, in 
> logging.config.dictConfig(config)
>   File "C:\Python34\lib\logging\config.py", line 789, in dictConfig
> dictConfigClass(config).configure()
>   File "C:\Python34\lib\logging\config.py", line 614, in configure
> '%r: %s' % (name, e))
> ValueError: Unable to configure logger 'root': 'StreamHandler' object is not 
> iterable
> 
> 
> I even tried creating a JSON file to create the dictionary, and got the same 
> error.
> 
> Thanks for any help
> --
> Tim

Just as a followup, if I use 'unrepr=True' in my ConfigObj, I don't have to 
convert the strings.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dictConfig: logging.StreamHandler object is not iterable.

2017-05-24 Thread Peter Otten
Tim Williams wrote:

> Just as a followup, if I use 'unrepr=True' in my ConfigObj, I don't have
> to convert the strings.

I'd keep it simple and would use JSON...

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread bartc

On 24/05/2017 15:31, Steve D'Aprano wrote:


Same as if Python supported constants (names that can only be assigned to
once).


That's not quite the same as my notion of 'named constant' that I expand 
below. This suggests that the actual literal bound to the name may not 
be known until runtime.



Again, the pain of building a custom "constant-like" solution is
greater than the benefit, so I've done without.

But if Python did support these things, maybe the compiler could make a few
optimizations, or maybe we could write a few less unit tests, or catch a
few bugs a little earlier... or not.


It's just a different way at looking at minimalism. Guido says, the language
should be as small as possible.


A funny way of making things minimal when people are then obliged to 
create dozens of different add-on libraries to try and add the missing 
functionality. It doesn't make the language any faster either when the 
solutions involve extra modules, classes, attribute lookups and type

dispatching.

Anyway, my Python 3.4 comprises 5000 files in around 90MB. Minimalism 
hasn't really worked.



If you don't want to assign to a name, then
just don't assign to it. No need to build support for constants into the
language when you can trust the developer to Don't Do That.


Yet the language will stop you assigning to 672, or "abc" (Had to do a 
quick that that was actually the case! Python is full of surprises.)


Maybe the language could have been made even smaller if that was not 
checked; after all the developer ought to be trusted not to assign to them!


Well, named constants are just such literals, but with a name. The 
design of Python however means that that immediately causes a difficult 
because then we have to deal with different scopes, name lookups, and 
named constants defined inside a module or class so requiring an 
attribute lookup.


Ideally a named constant would be instantly mapped to the equivalent 
literal, and done during compilation. Then a range of optimisations also 
become possible (and enables a fast 'switch' statement).


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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Ian Kelly
On Wed, May 24, 2017 at 4:11 PM, bartc  wrote:
> On 24/05/2017 15:31, Steve D'Aprano wrote:
>> If you don't want to assign to a name, then
>> just don't assign to it. No need to build support for constants into the
>> language when you can trust the developer to Don't Do That.
>
> Yet the language will stop you assigning to 672, or "abc" (Had to do a quick
> that that was actually the case! Python is full of surprises.)
>
> Maybe the language could have been made even smaller if that was not
> checked; after all the developer ought to be trusted not to assign to them!

Probably not, because then code would have to be written to implement
assigning to something that isn't an identifier. In Python's data
model I don't know what that would even mean.

> Well, named constants are just such literals, but with a name. The design of
> Python however means that that immediately causes a difficult because then
> we have to deal with different scopes, name lookups, and named constants
> defined inside a module or class so requiring an attribute lookup.
>
> Ideally a named constant would be instantly mapped to the equivalent
> literal, and done during compilation. Then a range of optimisations also
> become possible (and enables a fast 'switch' statement).

What if you want to define a named constant that isn't a literal? For example:

const LOCALHOST = IPAddress('127.0.0.1')
-- 
https://mail.python.org/mailman/listinfo/python-list


adding type hints to one of my projects, things learned

2017-05-24 Thread Irmen de Jong
Hi,

I wanted to share my experience with adding type hints to one of my projects.

TL;DR: There were some benefits, mypy discovered a couple of bugs, there are a 
few
annoyances for me, and I am not really sold on it yet.
Please correct my mistakes or help me solve some problems if possible :)


(Sorry about the crappy formatting, I copied the md text verbatim from the same 
post I
made on reddit. If you want to read all this and desire better layout you can 
perhaps
read it there instead:
https://www.reddit.com/r/Python/comments/6d5haz/the_story_of_adding_type_hints_to_one_of_my/
)



Adding type hints to Tale
-

Intro
-

'Tale - an Interactive Fiction, MUD & mudlib framework' is
a medium sized Python project. At the time of writing (just after
releasing version 3.1 of the project),
it has about 15000 SLOC (~9500 in the tale library,
~3800 in the test suite, and ~2100 in the demo stories).

You can find it on Github; https://github.com/irmen/Tale

Tale started as a Python 2.x-and-3.x compatible library but I decided
I want to be able to use modern Python (3.5+) features and not worry
anymore about backwards compatibility, so I cleaned up and modernized the code 
a while ago.

After finishing that, one of the major new Python features I still hadn't used 
anywhere,
was _type hinting_. Because I wanted to learn to use it, I took Tale as
a test case and added type hints to all of the code.
I wanted to learn about the syntax,
how to apply it to an existing code base,
to see what benefits it gives,
and to discover what problems it introduces and what limitations it has.

Below are the results.


Benefits


The following things have proven to be beneficial to me:

- PyCharm (my IDE of choice) is giving more detailed warning messages and code
completion suggestions:
  it adds inferred types or type hints to it.
- The MyPy tool (http://mypy.readthedocs.io/en/latest/index.html) is able to 
statically
find type related errors in the code
  at _compile time_ rather than having to run into them during _run time_.
  It correctly identified several mistakes that were in the code that I had
  not discovered yet and weren't caught by the unit tests.
- Mypy is pretty smart, I was quite surprised by its capability to infer
  the type of things and how it propagates through the code.
- Type hinting is optional so you can mix code with and without type hints.



Things I'm not happy with
-

- It takes a lot of effort to add correct type hints everywhere.
  Before this task is complete, mypy can and will report lots of
  errors that are wrong or can be misleading.

- Mypy has bugs. One of the most obvious is that it doesn't know about
  several modules and classes from the standard library.

- Shutting mypy up is done via a `# type: ignore` comment.
  Tale now has about 60 of these...
  Some of them can and should be removed once mypy gets smarter,
  but I have no way of knowing which ones they are. How am I going to maintain 
these?
  It strongly reminds me of the 'suppress-warning' type of comments found
  in other languages.  This is problematic because it hides possible errors
  in a way that is hard to find later.

- I really don't like these two major aspects of the type hint syntax:
1. Sometimes you have to use _strings_ rather than the type itself.
   This is because the hints are parsed at the same time as all other code,
   and sometimes you need "forward references" to types that are not yet 
defined.
   This can sometimes be fixed by rearranging the definition order
   of your classes, but if classes reference each other (which is common)
   this doesn't help. I find the most irritating that you have to
   do this for the actual class that you're type hinting the methods of!
   I understand the reason (the class is still being parsed, and is not
   yet _defined_) but I find it very cumbersome.
2. Type hints for variables are often required to help mypy. Especially
   if you're initializing names with empty collection types such as `[]` or 
`{}`
   which is common.  Also you have to do this via a _comment_ such as `# 
type:
List[str]`
   The latter is improved in Python 3.6 (see PEP-526) but I want to
   stick with 3.5 as a minimum for a while.


- Because type hints are parsed by Python itself, and because mypy
  even parses the comments as well,
  you'll have to import all types that you use in hints.
  This causes a lot of extra imports in every module.
  In my case this even led to some circular import problems that
  were only fixable by changing the modules itself. (One can argue
  that this is a good thing! Because circular references often
  are a code smell)
  Some types are only used in a _comment_, which
  causes the IDE to warn me about unused imports that it wants to
  clean up (but if I do this, it breaks mypy). PyCharm is not (yet)
  smart enough to see that an import is really used ev

Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Gregory Ewing

Steve D'Aprano wrote:

But I'll note that Python has supported read-only
properties for, oh, a decade or more, and do I hear people complaining
about how much libraries and applications over-use and abuse properties?


That's not quite the same thing. Python doesn't go out of its
way to support read-only properties; it's just that if you
create a property and don't define what it means to write it,
then it can't be written.

Read-only variables, on the other hand, would require adding
a new concept to the language and extending the interpreter
to support it.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Gregory Ewing

Chris Angelico wrote:

So Fred might still think "final is great,
my stuff runs 0.1% faster", but Joe thinks "final is a pain in the
behind".


C# addresses this issue by making final the default. That way,
your behind is so numb from constant pain that you don't really
notice it, and the relief from the occasional moments when the
pain is lifted feel like bliss.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Gregory Ewing

bartc wrote:
Anyway, my Python 3.4 comprises 5000 files in around 90MB. Minimalism 
hasn't really worked.


Most of that is standard library code, not part of the core
language.

Well, named constants are just such literals, but with a name. The 
design of Python however means that that immediately causes a difficult 
because then we have to deal with different scopes, name lookups, and 
named constants defined inside a module or class so requiring an 
attribute lookup.


This is the kind of interaction between features that makes
extending the core language much more difficult than adding
library features. The latter is mostly a linear process, but
interactions between core language features tends to grow
exponentially.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Gregory Ewing

bartc wrote:


Yet the language will stop you assigning to 672, or "abc".

Maybe the language could have been made even smaller if that was not
checked; after all the developer ought to be trusted not to assign to them!


I'm told that some Fortran implementations experimented with
something akin to that, with "interesting" results.

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


Re: I need help with making my claculator

2017-05-24 Thread woooee
How do you then run the mainloop, i.e. get it to do something?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I need help with making my claculator

2017-05-24 Thread MRAB

On 2017-05-25 00:02, woo...@gmail.com wrote:

How do you then run the mainloop, i.e. get it to do something?


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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread bartc

On 24/05/2017 23:59, Gregory Ewing wrote:

bartc wrote:


Yet the language will stop you assigning to 672, or "abc".

Maybe the language could have been made even smaller if that was not
checked; after all the developer ought to be trusted not to assign to
them!


I'm told that some Fortran implementations experimented with
something akin to that, with "interesting" results.


That was quite likely with older Fortrans, where subroutines only used 
pass-by-reference, but which didn't stop you passing references to 
constants that the subroutine could then modify.


I doubt that's still the case. With C, however, I tried this today:

  "abcdef"[3] = 'z';
  puts("abcdef");

Some versions crashed; some printed 'abczef', and some 'abcdef'. (The 
language says this is undefined, but it doesn't try too hard to stop you 
doing it.)



--
bartc

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


Re: I need help with making my claculator

2017-05-24 Thread woooee
This is most likely using class objects instead of instance objects.  Not a 
normal thing in Python.  As stated above, it is difficult, as the responses in 
this thread show, to get assistance with some alternate coding style.  It is 
better to use Python in the way that is intended.  Otherwise, you can not 
expect volunteers to spend extra time trying to figure out someone's alternate 
style.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Logging function calls without changing code

2017-05-24 Thread Matt Wheeler
Hi Rajat,

On Wed, 24 May 2017 at 20:05 Rajat Sharma  wrote:

> Is there a way to log all function calls of a class without changing
> anything in that class.
>

Several... depending on what you want to achieve some may be more suited
than others


> What I mean to say is if I have written a class previously and I want to
> enable logging in that then I would probably need to write the following
> before my function calls-
>
> logger.debug(' called...')
>
> But, is there a way that I do not need to change my existing code and can
> create a wrapper around that existing class or something else which can
> help me do the same?
>

My first thought is why not write a simple wrapper class like so:

```
class Wrapper(Original):
def __init__(self, *args, **kwargs):
_wrapped = Original(*args, **kwargs)

def __getattr__(self, attr):
print('accessed {}'.format(attr))
return getattr(self._wrapped(attr))
```

This could easily be translated into a decorator so that you can apply it
directly to the original class, something like:
```
def log_accesses(cls):
class Wrapper(object):
def __init__(self, *args, **kwargs):
self._wrapped = cls(*args, **kwargs)

def __getattr__(self, attr):
print('accessed {}'.format(attr))
return getattr(self._wrapped(attr)

return Wrapper

@log_accesses
class Original(..
```

If you want to also log the arguments passed to the functions (you didn't
say that) things get a bit more complex, but it's still certainly
achievable.

If you actually need to wrap the class in place for testing you might look
into combining something like the above with the mock library.
-- 

--
Matt Wheeler
http://funkyh.at
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: adding type hints to one of my projects, things learned

2017-05-24 Thread Ethan Furman

Thank you for that write-up!  I haven't used type hints, fearing pretty much 
the obstacles you ran into.

The only thing I can (partially) offer is a tool, written by Google I believe, that parses and annotates code with the 
types the code is /currently/ working with.  I say partially because I cannot find it at the moment... ah ha!  found it!


  https://github.com/google/pytype

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


RE: How to install Python package from source on Windows

2017-05-24 Thread Deborah Swanson
Paul Moore wrote, on Wednesday, May 24, 2017 5:53 AM
> On Monday, 15 May 2017 22:42:22 UTC+1, Deborah Swanson  wrote:
> > MRAB wrote, on Monday, May 15, 2017 12:44 PM
> > > 
> > > On 2017-05-15 13:52, eryk sun wrote:
> > > > On Mon, May 15, 2017 at 6:37 AM, Deborah Swanson
> > > >  wrote:
> > > >>
> > > >> Where did you find 
> recordclass-0.4.3-cp34-cp34m-win32.whl?  There
> > > >> weren't any win32 builds on 
> > > https://pypi.python.org/pypi/recordclass.
> > > > 
> > > > It's in the
> > > middle of the file list:
> > > > 
> > > > recordclass-0.4.3-cp34-cp34m-win32.whl (md5) Python 
> Wheel cp34
> > > > 2017-04-17 17KB
> > > > 
> > > > Maybe you're looking at a cached page in your browser? But that
> > > > doesn't explain why pip doesn't see it.
> > > > 
> > > >> Maybe I can find an earlier 3 build that won't demand 
> Visual C++.
> > > > 
> > > > The wheel doesn't need a compiler. It has an ABI tag because it
> > > > already includes the compiled extension module.
> > > > 
> > > I used pip to install into Python 3.4 (32-bit) from PyPI. 
> It fetched
> > > "recordclass-0.4.3.tar.gz" and compiled it instead of fetching 
> > > "recordclass-0.4.3-cp34-cp34m-win32.whl".
> > > 
> > > Why?
> > 
> > Excellent question, though I have no clue what the answer is.
> > 
> > > Come to think of it, what's that "cp34m" in the name? I don't have
> > that
> > > in the regex module's wheels, I have "none" instead.
> > 
> > Another excellent question. "cp" in "cp34m" might stand for 
> C++, but 
> > if so, what's the rest of it mean? Or maybe "CPython 3.4" plus "m" 
> > (whatever "m" stands for)?
> > 
> > What's "the regex module's wheels"? I certainly don't know, 
> though I 
> > know vague outines of what "regex" and "wheel" are.
> >  
> > > Rename "recordclass-0.4.3-cp34-cp34m-win32.whl" to
> > > "recordclass-0.4.3-cp34-name-win32.whl".
> > > 
> > > With the new name, it installs and seems to work!
> > 
> > Most excellent and I will try it.
> 
> I don't know whether you solved your issue, but in case you 
> didn't, the problem is that the "cp34m" part of the name 
> indicates the "ABI" used in the extension (roughly, how the C 
> part of the code links to the Python interpreter). Older 
> versions of pip (such as the one shipped with Python 3.4, 
> which is itself a bit old now) didn't recognise that tag, and 
> so won't install that wheel.
> 
> The best way to fix this is to upgrade the copy of pip you have, using
> 
>python -m pip install --upgrade pip
> 
> When you do that, you'll get a version of pip that recognises 
> the "cp34m" tag, and "pip install recordclass" should then just work.
> 
> Hope this helps,
> Paul

Ah, but. When I tried to upgrade pip it failed because it could neither
find nor install Visual Studio 2015.  Unfortunately it had uninstalled
pip before it found that problem.

So now I'm pipless. Read the thread if you want to know why I don't have
and can't (and won't) install Visual Studio 2015.

Looks like I'll have to reinstall Anaconda3 if I need the old pip before
I get resituated in Linux, but that's a major pain in inself because it
won't reinstall in the same directory, especially since I could also end
up having to reinstall Pycharm (and risk losing all my code histories)
too. Bleah.  Hope I don't need pip in the immediate future, old pip or
new.

Deborah

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Chris Angelico
On Thu, May 25, 2017 at 9:34 AM, bartc  wrote:
> That was quite likely with older Fortrans, where subroutines only used
> pass-by-reference, but which didn't stop you passing references to constants
> that the subroutine could then modify.
>
> I doubt that's still the case. With C, however, I tried this today:
>
>   "abcdef"[3] = 'z';
>   puts("abcdef");
>
> Some versions crashed; some printed 'abczef', and some 'abcdef'. (The
> language says this is undefined, but it doesn't try too hard to stop you
> doing it.)

And why should they try to stop you? The whole point of undefined
behaviour is that you shouldn't be doing this, so if you do, the
interpreter's allowed to do anything.

# Lifted from reddit: change the value of 29 to be 100
import ctypes
def deref(addr, typ):
return ctypes.cast(addr, ctypes.POINTER(typ))
deref(id(29), ctypes.c_int)[6] = 100

print(29)
x = 29
y = x + 1
print(y - 1)

What's going to happen? Will it print 100 twice? What is y? The
behaviour of CPython after you mess around with ctypes like this is as
undefined as any of C's weirdnesses.

And yes, Steve, this is a challenge to you: if you think C's undefined
behaviour is an abomination that should not be allowed to exist,
define what Python should do here.

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


Re: How to install Python package from source on Windows

2017-05-24 Thread eryk sun
On Thu, May 25, 2017 at 12:18 AM, Deborah Swanson
 wrote:
>
> When I tried to upgrade pip it failed because it could neither
> find nor install Visual Studio 2015.

Installing and upgrading pip does not require a C compiler.

> So now I'm pipless. Read the thread if you want to know why I don't have
> and can't (and won't) install Visual Studio 2015.

VS 2015 is the wrong version for Python 3.4 anyway. You would need VS
2010. However, you don't need it in this case. You just need the
latest pip.

For packages that don't have wheels available on PyPI, you can often
find an unofficial build on Christoph Gohlke's site [1]. He still
builds and distributes wheels for Python 3.4, but I don't know for how
much longer.

[1]: http://www.lfd.uci.edu/~gohlke/pythonlibs
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread ofekmeister
On Tuesday, May 23, 2017 at 11:47:21 PM UTC-4, bream...@gmail.com wrote:
> Well that's what is says here https://github.com/ofek/venum so it must be 
> true.  Please move over Ethan, your time is up :-)
> 
> Kindest regards.
> 
> Mark Lawrence.

Hey I've just run some tests and have updated the docs showing memory usage 
https://github.com/ofek/venum
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: How to install Python package from source on Windows

2017-05-24 Thread Deborah Swanson


eryk sun wrote, on Wednesday, May 24, 2017 6:32 PM
> 
> On Thu, May 25, 2017 at 12:18 AM, Deborah Swanson 
>  wrote:
> >
> > When I tried to upgrade pip it failed because it could neither find 
> > nor install Visual Studio 2015.
> 
> Installing and upgrading pip does not require a C compiler.
> 
> > So now I'm pipless. Read the thread if you want to know why I don't 
> > have and can't (and won't) install Visual Studio 2015.
> 
> VS 2015 is the wrong version for Python 3.4 anyway. You would 
> need VS 2010. However, you don't need it in this case. You 
> just need the latest pip.
> 
> For packages that don't have wheels available on PyPI, you 
> can often find an unofficial build on Christoph Gohlke's site 
> [1]. He still builds and distributes wheels for Python 3.4, 
> but I don't know for how much longer.
> 
> [1]: http://www.lfd.uci.edu/~gohlke/pythonlibs

Ok, I'm done with you guys who don't have a clue what happens to users
of operating sytems forced at gunpoint to die. Well, that's the attempt
anyway, but both me and my operating system are real hard to kill.

I'm dealing with it, so please, no more advice to use fancy toys that
don't work on XP. And hopefully no more XP bashing because it's my only
choice right now, and I'm not going to turn off my computer and twiddle
my thumbs all day, especially when there's tons of python to keep
learning and using every day, right here on Windows XP. I spent 6 hours
today on a very difficult project, and I'm not going to shut it all down
and quit because some people apparently think that's the only
alternative to upgrading to some other system, and I can neither afford
the time or money to do that right now. And I don't need to. I know XP
inside and out, having tested it at Microsoft for 2+ years, and used it
intensively for the last 15 years.

Actually, any more XP bashing and replying posts will be immediately
deleted on my computer without reply from me. (Not saying that you or
Paul did that, just warning anyone who wants to use this opportunity to
jump on the XP beatdown wagon. And I keep track and keep names, so I'll
know you if you ever reply to me again about anything.)

Deborah

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


Re: Hi everyone

2017-05-24 Thread tommy yama
Hi Ian,

yeah. feel free to ask for any relating python.

thanks!

On Thursday, May 25, 2017, Ian Kelly  wrote:

> On Wed, May 24, 2017 at 11:20 AM, Spaarwiel  > wrote:
> >
> > Hi there, i was always interested in coding but never took the time to
> learn it.
> >
> > So at age 34 i'm going to try and see if i can win this.
> >
> > Saw on a website this is good group page to come for help so i will def.
> be asking alot of questions here :)
> >
> > B.t.w i have no knowledge of coding whatsoever so i'm starting lower that
> the bottom.
>
> Please note this list is specifically for discussion of the Python
> language, not coding in general. If you have Python questions you're
> welcome to ask them here but you may find the Python tutor mailing list a
> better resource for learning: https://mail.python.org/
> mailman/listinfo/tutor
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Sent from Gmail Mobile
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to install Python package from source on Windows

2017-05-24 Thread Chris Angelico
On Thu, May 25, 2017 at 2:20 PM, Deborah Swanson
 wrote:
>> For packages that don't have wheels available on PyPI, you
>> can often find an unofficial build on Christoph Gohlke's site
>> [1]. He still builds and distributes wheels for Python 3.4,
>> but I don't know for how much longer.
>>
>> [1]: http://www.lfd.uci.edu/~gohlke/pythonlibs
>
> Ok, I'm done with you guys who don't have a clue what happens to users
> of operating sytems forced at gunpoint to die. Well, that's the attempt
> anyway, but both me and my operating system are real hard to kill.
>
> I'm dealing with it, so please, no more advice to use fancy toys that
> don't work on XP. And hopefully no more XP bashing because it's my only
> choice right now, and I'm not going to turn off my computer and twiddle
> my thumbs all day, especially when there's tons of python to keep
> learning and using every day, right here on Windows XP. I spent 6 hours
> today on a very difficult project, and I'm not going to shut it all down
> and quit because some people apparently think that's the only
> alternative to upgrading to some other system, and I can neither afford
> the time or money to do that right now. And I don't need to. I know XP
> inside and out, having tested it at Microsoft for 2+ years, and used it
> intensively for the last 15 years.

I don't know why you're still talking about XP bashing. The post
you're quoting is specifically stating that you CAN use this on XP
(the mention of Python 3.4 was because that version runs on XP). The
"fancy toys" you're referring to are wheels? They're just a specific
format of precompiled binary that can be downloaded easily and
installed. They can be produced by the original package author (in
which case pip will find them no trouble), but if they're not, there's
a wonderfully helpful chap who builds them and makes them available.
That's the link you were given - it's third-party but very well
respected.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Ian Kelly
On Wed, May 24, 2017 at 8:49 PM,   wrote:
> On Tuesday, May 23, 2017 at 11:47:21 PM UTC-4, bream...@gmail.com wrote:
>> Well that's what is says here https://github.com/ofek/venum so it must be 
>> true.  Please move over Ethan, your time is up :-)
>>
>> Kindest regards.
>>
>> Mark Lawrence.
>
> Hey I've just run some tests and have updated the docs showing memory usage 
> https://github.com/ofek/venum

>From the updated documentation:

"""
This example was run on a 64-bit machine.

Note that stdlib's Enum by itself uses 1056 bytes with each member
requiring 56 bytes, whereas namedtuple Enum uses just 48 bytes with
each member requiring only 16 bytes.

>>> from sys import getsizeof
>>> from enum import Enum as StdEnum
>>> from venum import Enum
>>>
>>> class SomeEnum(StdEnum):
... BLUE = 3
>>>
>>> getsizeof(SomeEnum)
1056
>>> getsizeof(Enum(('BLUE', 3)))
56
"""

There's a huge problem with this analysis. Specifically, every time
you call Enum, you're creating not just a new namedtuple instance, but
also a new namedtuple singleton class, and you're not accounting for
the size of the class:

>>> Color = Enum(('BLUE', 3), name = 'Color')
>>> Color
Color(BLUE=3)
>>> getsizeof(Color)
56
>>> Color.__class__

>>> getsizeof(Color.__class__)
888

So you're not saving nearly as much memory as you think.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to install Python package from source on Windows

2017-05-24 Thread Gregory Ewing

Deborah Swanson wrote:


So now I'm pipless.


You should be able to get it back using

   python -m ensurepip

BTW, I don't know why upgrading pip would fail due to lack of
Visual Studio. That shouldn't be able to happen, because pip
is pure Python.

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


Re: Verifiably better, validated Enum for Python

2017-05-24 Thread Steven D'Aprano
On Thu, 25 May 2017 10:59:55 +1200, Gregory Ewing wrote:

> bartc wrote:
> 
>> Yet the language will stop you assigning to 672, or "abc".
>>
>> Maybe the language could have been made even smaller if that was not
>> checked; after all the developer ought to be trusted not to assign to
>> them!
> 
> I'm told that some Fortran implementations experimented with something
> akin to that, with "interesting" results.


It wasn't intentional -- it was an accident due to the way they 
implemented pass-by-reference semantics. If you passed a constant to a 
function expecting a variable passed by reference, and then assigned to 
the parameter, the compiler would change the value of the constant.

Pascal solved that problem by prohibiting you from passing constants or 
expressions to functions or procedures as pass-by-reference parameters.



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