Re: Decorators with arguments?

2020-05-25 Thread Christopher de Vidal
Peter Otten, Cameron Simpson, thank you for your detailed replies :-) I
confess, I didn't quite understand all you were saying. (Still only an
intermediate-level programmer.) But Cameron what you said questioning my
use of decorators and maybe a class instead got me thinking. I realized
what I needed was a function within a function. Couldn't have gotten there
without your help. Working code:

#!/usr/bin/env python3
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
import json
import mqtt
from time import sleep

def bridge(col_name):
def on_snapshot(col_snapshot, changes, read_time):
data = dict()
for doc in col_snapshot:
serial = doc.id
data[serial] = json.dumps(doc.to_dict()['value'])
for change in changes:
serial = change.document.id
mqtt_topic = col_name + '/outgoing/' + serial
if change.type.name in ['ADDED', 'MODIFIED']:
contents = data[serial]
mqtt.publish(mqtt_topic, contents)
elif change.type.name == 'REMOVED':
mqtt.publish(mqtt_topic, '')


@mqtt.incoming
def mqtt_subscribe(serial, value):
# TODO Passing a None entry to delete from MQTT doesn't trigger
this
#   callback, so it doesn't delete from Firestore. Need this ugly
#   workaround 'clear_mqtt'.
if value == 'clear_mqtt':
value = None
mqtt.publish(col_name + '/incoming/' + serial, None)
mqtt.publish(col_name + '/outgoing/' + serial, None)
db.collection(col_name).document(serial).set({'value': value})


col_watch = db.collection(col_name).on_snapshot(on_snapshot)
mqtt.subscribe(col_name + '/incoming/#', mqtt_subscribe)
return col_watch


cred = credentials.Certificate("certs/firebase.json")
firebase_admin.initialize_app(cred)
db = firestore.Client()
mqtt.connect()
adapters = list()
for collection in ['door_status', 'cpu_temp']:
adapters.append(bridge(collection))
while True:
sleep(1)
for adapter in adapters:
adapter.unsubscribe()

Christopher de Vidal

Would you consider yourself a good person? Have you ever taken the 'Good
Person' test? It's a fascinating five minute quiz. Google it.


On Fri, May 15, 2020 at 9:55 AM Peter Otten <__pete...@web.de> wrote:

> Christopher de Vidal wrote:
>
> > Help please? Creating an MQTT-to-Firestore bridge and I know a decorator
> > would help but I'm stumped how to create one. I've used decorators before
> > but not with arguments.
> >
> > The Firestore collection.on_snapshot() method invokes a callback and
> sends
> > it three parameters (collection_snapshot, changes, and read_time). I need
> > the callback to also know the name of the collection so that I can
> publish
> > to the equivalent MQTT topic name. I had thought to add a fourth
> parameter
> > and I believe a decorator is the right approach but am stumped how to add
> > that fourth parameter. How would I do this with the code below?
> >
> > #!/usr/bin/env python3
> > from google.cloud import firestore
> > import firebase_admin
> > from firebase_admin import credentials
> > import json
> > import mqtt
> >
> >
>
> firebase_admin.initialize_app(credentials.Certificate("certs/firebase.json"))
> > db = firestore.Client()
> > mqtt.connect()
> >
> >
> > def load_json(contents):
> > try:
> > return json.loads(contents)
> > except (json.decoder.JSONDecodeError, TypeError):
> > return contents
> >
> >
> > def on_snapshot(col_name, col_snapshot, changes, read_time):
> > data = dict()
> > for doc in col_snapshot:
> > serial = doc.id
> > contents = load_json(doc.to_dict()['value'])
> > data[serial] = contents
> > for change in changes:
> > serial = change.document.id
> > mqtt_topic = col_name + '/' + serial
> > contents = data[serial]
> > if change.type.name in ['ADDED', 'MODIFIED']:
> > mqtt.publish(mqtt_topic, contents)
> > elif change.type.name == 'REMOVED':
> > mqtt.publish(mqtt_topic, None)
> >
> >
> > # Start repeated code section
> > # TODO Better to use decorators but I was stumped on how to pass
> arguments
> > def door_status_on_snapshot(col_snapshot, changes, read_time):
> > on_snapshot('door_status', col_snapshot, changes, read_time)
> &g

Decorators with arguments?

2020-05-14 Thread Christopher de Vidal
Help please? Creating an MQTT-to-Firestore bridge and I know a decorator
would help but I'm stumped how to create one. I've used decorators before
but not with arguments.

The Firestore collection.on_snapshot() method invokes a callback and sends
it three parameters (collection_snapshot, changes, and read_time). I need
the callback to also know the name of the collection so that I can publish
to the equivalent MQTT topic name. I had thought to add a fourth parameter
and I believe a decorator is the right approach but am stumped how to add
that fourth parameter. How would I do this with the code below?

#!/usr/bin/env python3
from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
import json
import mqtt

firebase_admin.initialize_app(credentials.Certificate("certs/firebase.json"))
db = firestore.Client()
mqtt.connect()


def load_json(contents):
try:
return json.loads(contents)
except (json.decoder.JSONDecodeError, TypeError):
return contents


def on_snapshot(col_name, col_snapshot, changes, read_time):
data = dict()
for doc in col_snapshot:
serial = doc.id
contents = load_json(doc.to_dict()['value'])
data[serial] = contents
for change in changes:
serial = change.document.id
mqtt_topic = col_name + '/' + serial
contents = data[serial]
if change.type.name in ['ADDED', 'MODIFIED']:
mqtt.publish(mqtt_topic, contents)
elif change.type.name == 'REMOVED':
mqtt.publish(mqtt_topic, None)


# Start repeated code section
# TODO Better to use decorators but I was stumped on how to pass arguments
def door_status_on_snapshot(col_snapshot, changes, read_time):
on_snapshot('door_status', col_snapshot, changes, read_time)


door_status_col_ref = db.collection('door_status')
door_status_col_watch =
door_status_col_ref.on_snapshot(door_status_on_snapshot)

# Repetition...
def cpu_temp_on_snapshot(col_snapshot, changes, read_time):
on_snapshot('cpu_temp', col_snapshot, changes, read_time)


cpu_temp_col_ref = db.collection('cpu_temp')
cpu_temp_col_watch = cpu_temp_col_ref.on_snapshot(cpu_temp_on_snapshot)
# End repeated code section

# Start repeated code section
door_status_col_watch.unsubscribe()
cpu_temp_col_watch.unsubscribe()
# Repetition...
# End repeated code section

Christopher de Vidal

Would you consider yourself a good person? Have you ever taken the 'Good
Person' test? It's a fascinating five minute quiz. Google it.
-- 
https://mail.python.org/mailman/listinfo/python-list


I need to create .odt or .rtf documents in Python3. what is the best tool to do this....

2020-01-12 Thread christopher rehm
hi all im new here. i need to create .odt or rtf documents from a python 3 
program. i need a package or library that actually has real documentation and 
examples, using python3 and the tool ( sorry PyRTF3 is a major failure here)
does anyone have any suggestions?

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


Re: [Python-ideas] Re: Enhancing Zipapp

2020-01-08 Thread Christopher Barker
On Wed, Jan 8, 2020 at 1:24 AM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> But a thought on that -- you may be able to accomplish something similar
>> with conda, "conda constructor", and "conda run". -- or a new tool built
>> from those. The idea is that the first time you ran your "app", it would
>> install its dependencies, and then use them in an isolated environment. But
>> if the multiple apps had the same dependencies, they would share them, so
>> you wouldn't get major bloat on the host machine.
>>
>
> I guess it's time to dig more into anaconda, been
> putting it off, will do.
>

to be clear -- you want to look at "conda", not "Anaconda" -- conda is a
package manager, Anaconda is a distribution created with the conda package
manager.


> but a wheel is just as big as the installed package (at least a zipped
>> version) -- it's essentially the package compressed into a tarball.
>>
>
> I really hope C extentions would become redundent someday
> in Python, which would make Python development real
> Python dev.
>

That's not going to completely happen. Which does not mean that a solution
that doesn't support them isn't still useful for a lot. But it would be
interesting to see how many commonly used packages on PyPi rely on C
extensions (other than the SciPy Stack).


> But: "Unlike “conventional” zipapps, shiv packs a site-packages style
>> directory of your tool’s dependencies into the resulting binary, and then
>> at bootstrap time extracts it into a ~/.shiv cache directory."
>>
>
> Maybe we can have a PYZ directory where the
> packages for each app are extracted then it's not
> a global dump but more specific
>

I'm not sure how that differs from a .shiv directory, which is not global.
But a way to share packages in the "central place for packages" would be
nice. -- maybe how conda does it with hard links?

-CHB


-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Re: Enhancing Zipapp

2020-01-08 Thread Christopher Barker
On Wed, Jan 8, 2020 at 1:49 AM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> Have a look at this write up about the horror that is zip file name
>> handling.
>>
>> https://marcosc.com/2008/12/zip-files-and-encoding-i-hate-you/
>>
>> This has been a pain point at work.
>>
>
I'm pretty sure this is a non-issue for this use-case. If you need to open
sip files created by arbitrary other systems, or create zip files that can
be opened by arbitrary other systems, then it's a big mess. But that isn't
the case here.

-CHB


-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Re: Enhancing Zipapp

2020-01-07 Thread Christopher Barker
On Mon, Jan 6, 2020 at 10:50 PM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:


> - More metadata
>

good idea, and simple.


> - Integrity check with hashing
> - Protecting the meta data
>

This could be a big challenge -- and I'm not expert, so have no idea what
the issues are.


> - Bundling 3rd party packages
>

Well, as you state below, that could make it big. but it also could make it
useful -- folks want to use environments of various sorts to keep
dependencies separate, so bundling them all up in an app would be nice.

But a thought on that -- you may be able to accomplish something similar
with conda, "conda constructor", and "conda run". -- or a new tool built
from those. The idea is that the first time you ran your "app", it would
install its dependencies, and then use them in an isolated environment. But
if the multiple apps had the same dependencies, they would share them, so
you wouldn't get major bloat on the host machine.


> Are you aiming for a bundle that can run on multiple platforms? If so,
>> then it’ll have to have a way to bundle multiple compiled extensions and
>> select the right ones at runtime.
>>
>
> According to the discussion on the Python, Be Bold thread, it became
> clear that it will be a pain to generate and will have an unnecessary
> size but sure this a most stable idea
>
> Suggesting instead to include wheels. The wheels are installed. The
> interpreter looks for packages in that app-specific folder
>

but a wheel is just as big as the installed package (at least a zipped
version) -- it's essentially the package compressed into a tarball.

If this Is essentially just zipapp with the ability to bundle dependencies,
>> then you could probably just do some sys.path hackery.
>>
>
> Could you please explain more. Thanks?
>

sure -- in your zip file, you have a "dependencies" directory. the
dependencies get installed there. Then that dir gets added to sys.path at
startup. I'm not so sure o=how to do that inside a zipfile, but it could be
done *somehow*

In any case, thus seems like something you could implement, and then see if
>> people find it useful.
>>
>
> That's a nice idea to have a working demo. I'm not a security
> expert but i'll try!
>

well, you'll need a consult on the security issues -- which you would want
well reviewed anyway ;-)


> Anyone interested in this thread can view this tool
> <https://github.com/linkedin/shiv> built by LinkedIn which
> attempts dependencies bundling.
>

There you go -- you've got half the job done already :-)

But: "Unlike “conventional” zipapps, shiv packs a site-packages style
directory of your tool’s dependencies into the resulting binary, and then
at bootstrap time extracts it into a ~/.shiv cache directory."

which is how they get around the "how to add a dir in a zip file to
sys.path" -- but I'll bet someone could hack that to no be neccesary

-CHB

-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Python-ideas] Re: Enhancing Zipapp

2020-01-06 Thread Christopher Barker
I’m a bit unclear on how far this goes: is it just a bit more specific with
more meta-data standards?

Or are you aiming for something that will run without a Python install?

Other issues:

Are you aiming for a bundle that can run on multiple platforms? If so, then
it’ll have to have a way to bundle multiple compiled extensions and select
the right ones at runtime.

If this Is essentially just zipapp with the ability to bundle dependencies,
then you could probably just do some sys.path hackery.

In any case, thus seems like something you could implement, and then see if
people find it useful.

BTW- I’m pretty sure we could simply specify that filenames are utf-8 and
we’d be good to go.

-CHB





On Mon, Jan 6, 2020 at 5:50 PM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

>
>
> On Tue, 7 Jan 2020, 01:57 Barry Scott,  wrote:
>
>>
>>
>> Please cover the pro's and con's of the alernatives that have been raised
>> as comments
>> on this idea, as is usually done for a PEP style document.
>>
>
> Thanks, i don't have much experience writing peps and
> if i don't bug you may i ask what "alternatives" refer to?
>
> Also beware that zip file format does not include the encoding of the
>> files that are in the
>> zip file.
>
>
> For the encoding of the contents, well since we are
> packaging python code files, it's handling will be the same
> as handling outside the zip file. It's handling is the
> same as how zipapp handles things.
>
> This means that for practical purposes only ASCII filenames are portable
>> across
>> systems. Is this limitation a problem for this proposal?
>>
>
> If we are talking about filenames, then i guess
> ascii filenames are the way to go as you'd
> unnecessarily break things otherwise.
>
>> ___
> Python-ideas mailing list -- python-id...@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-id...@python.org/message/RVGFMDP3PG6TXFQGH7ISRLYM4FS5CO64/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Mailing List Digest Project

2019-03-26 Thread Christopher Barker
 On Tue, Mar 26, 2019 at 8:32 AM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> Great! will see sphinx but if i find the html hard to customise, i'll drop
> it.
>

Sphinx has theming support, plus you can do custom CSS if you want. But
Highly discourage you from worrying about formatting — decent structure is
good enough, and content is what matters.

Search feature and tags coming.
>

Sphinx has search built in.

also, currently i'm formatting the mails rather than an article, i don't
> know if a real summary of the topic preferable ...
>

These mailing lists are really big, and the threads are long and scattered,
and they are archived and searchable already.

So I think the real value would be article-style summaries (with links to
the threads).

For Python-Ideas, I’m thinking kind of a mini rejected PEP ...

-CHB

>





> Abdur-Rahmaan Janhangeer
> Mauritius
>
-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Mailing List Digest Project

2019-03-26 Thread Christopher Barker
On Mon, Mar 25, 2019 at 10:01 PM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> As proposed on python-ideas, i setup a repo to turn mail threads into
> articles.
>

Thanks for doing this — I find myself frequently telling people about past
relevant threads on this list - it will be great to have a single place to
point people. It can be hard to find stuff in the archives if you’re not
sure what to search for.

here is the repo
>
> https://github.com/Abdur-rahmaanJ/py-mailing-list-summary
>
> i included a script to build .md to .html
>

Maybe Sphinx and  RST instead? For consistency with other Python docs?

But markup is far less important than content.

-CHB

(with syntax highlighting) here is the index
>
> https://abdur-rahmaanj.github.io/py-mailing-list-summary/
>
> included 3 articles as a start
>
> if you want to contribute an article, just follow existing .md format and
> put it in the .md folder
>
> planning to go across ideas, list and dev
>
> i can tell you, it's a really enjoyable experience.
>
> psst. we can enhance some html later
>
> --
> Abdur-Rahmaan Janhangeer
> Mauritius
>
-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python3.7 error PYQT5 - NameError: name 'self' is not defined

2018-09-21 Thread Christopher Mullins
>
> Hi when I disconnect the internet I get an error NameError: name 'self' is
> not defined. I really dont get it.. thanks all. Is that a bug? or my fault?

Exception in thread Thread-1:
> Traceback (most recent call last):
>   File "C:\programming Alon\stock market app\PROJECT\AlonStockMarket.py",
> line 93, in secret
> print(ping('google.com'))
>   File "C:\programming Alon\stock market app\PROJECT\AlonStockMarket.py",
> line 72, in ping
> conn.connect((addr, 80))
> socket.gaierror: [Errno 11001] getaddrinfo failed
> During handling of the above exception, another exception occurred:
> Traceback (most recent call last):
>   File
> "C:\Users\Alon\AppData\Local\Programs\Python\Python37-32\lib\threading.py",
> line 917, in _bootstrap_inner
> self.run()
>   File
> "C:\Users\Alon\AppData\Local\Programs\Python\Python37-32\lib\threading.py",
> line 865, in run
> self._target(*self._args, **self._kwargs)
>   File "C:\programming Alon\stock market app\PROJECT\AlonStockMarket.py",
> line 95, in secret
> self.pushButton.setDisabled(True)
> NameError: name 'self' is not defined


Looks like `self` is supposed to be referring to an instance of the class
`Ui_AlonStockMarketApp` (which has the pushButton attribute) but you've
defined the secret function outside of that class.  Try defining that
function inside your class.

HTH,
Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flask: request vs Request

2018-03-12 Thread Christopher Mullins
>
> Could you please give some context when you reply, TIA
>

Whoops, thanks for the reminder Mark.

So what for the Request is used  for then?


In general when you see that something in Python starts with a capital
letter, that indicates a class. Check out the relevant section of the PEP8
coding style [1], this is a good reference to have on hand.  (This
generalization doesn't apply to builtin types which follow a separate
convention, also outlined in [1] -- and of course there are a numerous
exceptions.)

This holds for your variable in question "request" which is an instance of
the Request class.  Check out [2] for more information on this.  PyCharm
tries to do its best but I've had this problem too.  You can always open up
a python REPL and look at the object yourself:

>>> import flask
>>> r = flask.Request
>>> r

>>> dir(r)

and so on.  When I'm working in python I like to keep one of these open for
this purpose.

HTH,
Chris

[1] https://www.python.org/dev/peps/pep-0008/#class-names
[2] http://flask.pocoo.org/docs/0.12/api/#incoming-request-data
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flask: request vs Request

2018-03-10 Thread Christopher Mullins
In the code you linked, I don't see where the *R*equest is used. The
request variable is setup by flask when you annotate the function with the
resource endpoint and POST method. It contains the content of the request
which can be converted to json if that content type was specified.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: psychocomputational analysis toolkit in Python?

2018-03-08 Thread Christopher Mullins
> Would it be possible to emulate a minimally functional brain-to-brain
coupling system entirely in Python?

I don't know what that would entail, but the links I shared have a mailing
list and a very responsive gitter, both of which would be great places to
ask about that!  (You're welcome to ask here of course, but this being the
general python mailing list, it's a shot in the dark.)  Good luck!

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


Re: psychocomputational analysis toolkit in Python?

2018-03-08 Thread Christopher Mullins
You might find MNE useful, and if what you're doing happens to fit
somewhere in their package you could contribute to it -- they're a good
group to work with.

https://www.martinos.org/mne/stable/index.html
https://github.com/mne-tools/mne-python
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: connect four (game)

2017-11-25 Thread Christopher Reimer
On Nov 25, 2017, at 9:16 AM, Ian Kelly  wrote:
> 
>> On Sat, Nov 25, 2017 at 10:02 AM, Chris Angelico  wrote:
>>> On Sun, Nov 26, 2017 at 3:36 AM, Ian Kelly  wrote:
 On Sat, Nov 25, 2017 at 6:00 AM, bartc  wrote:
 Where are your unittests for these unittests?
>>> 
>>> No, the point of having unit tests is to build confidence that the
>>> code in question works correctly. It's *possible* that the code is
>>> broken, and that the test is also broken in a way that hides the
>>> brokenness of the code, but this is much less likely than the case
>>> where just the code is broken. This is also the reason why the
>>> philosophy of test-drive development stipulates that one should write
>>> the test *first*, run it and watch it fail (this ensures that the test
>>> is actually testing *something*) and then and only then write the code
>>> to make the test pass.
>> 
>> To be fair, TDD doesn't actually prove that the test isn't broken. It
>> only protects you against one class of error: tests that actually
>> aren't testing anything. Proponents of TDD will argue that this class
>> of error is quite common; true or not, it's still only one particular
>> kind of failure. It's definitely possible for tests to be wrong in
>> such a way that they don't detect faulty code.
>> 
>> So what do we do? WE TEST BY HAND. Ultimately, unit testing is a tool,
>> not a magic wand. It's up to us to actually put it to use to improve
>> code quality.
> 
> Certainly. I wasn't trying to advocate for TDD here, which I don't
> even practice regularly myself.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

For anyone who is interested, "Test-Driven Development with Python: Obey the 
Testing Goat: Using Django, Selenium, and JavaScript" by Harry J.W. Percival. 
The second edition came out this year. A good introduction to unit and function 
testing.

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


Re: How to Generate dynamic HTML Report using Python

2017-11-21 Thread Christopher Reimer
On Nov 21, 2017, at 5:36 AM, Rustom Mody  wrote:
> 
>> On Tuesday, November 21, 2017 at 5:27:42 PM UTC+5:30, Ned Batchelder wrote:
>>> On 11/20/17 9:50 AM, Stefan Ram wrote:
>>> Ned Batchelder  writes:
 Also, why set headers that prevent the Python-List mailing list from
 archiving your messages?
>>>   I am posting to a Usenet newsgroup. I am not aware of any
>>>   "Python-List mailing list".
>>> 
>>>   I am posting specifically to the Usenet, because I am aware
>>>   of it's rules and I like it and wish to support it.
>>> 
>>>   I do not post to a "mailing list" because I do not know which
>>>   rules apply for mailing lists and whether mailing lists in
>>>   general or any specific mailing list is an environment that I
>>>   like or wish to support.
>>> 
>> 
>> The dual nature of this online community has long been confusing and 
>> complicated.  It's both a newsgroup and a mailing list.  Add in Google 
>> Groups, and you really have three different faces of the same content.
>> 
>> The fact is, posting to comp.lang.python means that your words are also 
>> being distributed as a mailing list. Because of your messages' headers, 
>> they are not in the archive of that list 
>> (https://mail.python.org/pipermail/python-list/2017-November/thread.html), 
>> or in Google Groups 
>> (https://groups.google.com/forum/#!topic/comp.lang.python/0ejrtZ6ET9g). 
>> It makes for odd reading via those channels.
>> 
>> I don't understand the motivation for limiting how words are 
>> distributed, but others on this list also do it. For example, Dennis Lee 
>> Bieber's messages are not in the Python-List archives either. If 
>> something is worth saying, why not let people find it later?
> 
> To which I would add:
> Setting headers is hardly a working method.
> Somebody quotes Stefan or Dennis and they are on the archives
> And some quote including emails some not
> etc
> -- 
> https://mail.python.org/mailman/listinfo/python-list

A troll tried to prove that I was too retarded to program in Python by claiming 
that I asked a question on this list in the archives that could have been 
answered by searching the web. The funny thing is that none of the links that 
the troll provided answered my question.

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


Re: converting numbers into words (Posting On Python-List Prohibited)

2017-11-09 Thread Christopher Reimer
On Nov 9, 2017, at 3:45 AM, John Ladasky  wrote:
> 
>> On Wednesday, November 8, 2017 at 11:40:18 PM UTC-8, Lawrence D’Oliveiro 
>> wrote:
>>> On Thursday, November 9, 2017 at 7:51:35 PM UTC+13, r16...@rguktrkv.ac.in 
>>> wrote:
>>> 
>>> How can I covert numbers into word like ex:-123 One hundred twenty three?
>> 
>> Here’s  one I 
>> did earlier, in Algol 68.
>> 
>> Conversion to Python is left as an exercise for the reader.
> 
> I think that gives away rather more than I wanted the student to see.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I thought the classic homework problem was to convert an Arabic numeral into a 
Roman numeral. Bonus points for correctly converting any number above 12 and/or 
copyright year from any old movie. Most students have seen Roman numerals on 
clocks (1-12).

Maybe that's too hard for today's kids with digital clocks.

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


Keep or drop index.html from Django?

2017-10-27 Thread Christopher Reimer
Greetings,

When I set up my static website using Pelican several years ago, many URLs 
ended with index.html. Now that I'm looking at Django, I got a small set of 
URLs working with and without index.html to point to the correct pages.

I read somewhere that the Django philosophy was to keep the URLs as clean as 
possible (i.e., no *.html at the end). I can go either way with this. What's 
the best practice for this?

Thank you,

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


Re: Python noob having a little trouble with strings

2017-10-27 Thread Christopher Reimer
On Oct 27, 2017, at 1:49 AM, Peter J. Holzer  wrote:
> 
> BTW, I find it hard to believe that PyCharm for the Mac "comes with"
> Python 2.6. Python 2.6 is quite old. The Linux version isn't bundled
> with a python interpreter and just uses whatever is already installed on
> the machine. I guess it's the same for the Mac: Your version of MacOS
> happens to include Python 2.6, so this is what PyCharm uses.

I find it hard to believe that a professor would recommend downloading an IDE 
at the start of an intro class. Students usually start off with a text editor.

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


Re: Application and package of the same name

2017-10-21 Thread Christopher Reimer
On Oct 21, 2017, at 6:08 AM, David Stanek  wrote:

> This is actually a common pattern I see when teaching the language. For
> example, when a student wants to test out a package like requests many
> seem to initially want to create a requests.py module. Then they become
> very confused when they get an AttributeError on requests.get().

For my web scraper program, I'm using "requestor.py" for requests. :)

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


Can't find latest version of 3.4.x on download page

2017-10-17 Thread Christopher Reimer
Greetings,

I'm setting up different test environments for tox. I can't find Windows 
installer for the latest version of Python 3.4 on the download page.

Versions 3.4.5 to 3.4.7 only have the source files available.

Version 3.4.4 is the last version with Windows installers.

Testing on Python 3.4 might be moot for my program. It choked on a starred 
expression in a unit test. The starred expression got changed in Python 3.5 and 
my unit tests pass in Python 3.5/3.6. I don't think I can live without that 
feature. 

Thank you,

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


Re: Best practise for passing time as arguments

2017-10-14 Thread Christopher Reimer
On Oct 14, 2017, at 10:44 AM, Thomas Jollans  wrote:
> 
>> On 14/10/17 19:34, Stefan Ram wrote:
>> r...@zedat.fu-berlin.de (Stefan Ram) writes:
>>> a post. Use whatever is appropriate in the special case
>>> given, or - to write a general library -, learn the design
>>> of a good existing library, like Time4J, first.
>> 
>>  Though in many cases, an ISO 8601 time string 
>>  represented by a (named )Python tuple should
>>  be sufficient for a time stamp.
>> 
>>  E.g., ( year, month, day, hour, minute, seconds,
>>  zone_offset ).
>> 
> 
> Python provides a datetime (also: date, time, timedelta) type. Use it.
> 
> https://docs.python.org/3/library/datetime.html
> 
> When working with time zones, the standard library needs a little help.
> Luckily, there's a module for that. https://pypi.python.org/pypi/pytz
> 
> -- Thomas
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I wrote a blog post about muddling through the timestamp problem, showing 
examples for datetime, slice-and-dice text, and pytz. Since I was dealing with 
time zone-specific timestamps, I went with pytz in the end.

https://www.kickingthebitbucket.com/2017/04/04/the-python-time-zone-rabbit-hole/

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


Re: Lies in education [was Re: The "loop and a half"]

2017-10-11 Thread Christopher Reimer
On Oct 11, 2017, at 9:07 AM, Bill  wrote:
> 
> Grant Edwards wrote:
>> On 2017-10-11, Bill  wrote:
>> 
>> 
>>> [...] I'm not here to "cast stones", I like Python. I just think
>>> that you shouldn't cast stones at C/C++.
>> Not while PHP exists.  There aren't enough stones in the world...
>> 
> 
> PHP seems (seemed?) popular for laying out web pages.  Are their vastly 
> superior options? I'm a little naive in this matter, thus my question.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

AFAIK, JavaScript frameworks has largely replaced PHP. I personally use Pelican 
to generate static web pages and use JavaScript sparingly.

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


Re: How to determine lowest version of Python 3 to run?

2017-10-06 Thread Christopher Reimer
On Oct 6, 2017, at 12:58 PM, Stephan Houben  
wrote:
> 
> Op 2017-10-06, Christopher Reimer schreef :
> 
>> So I got tox and tox-docker installed. When I went to install Docker
>> for Windows, it wouldn't work because Hyper-V wasn't available on
>> Windows 10 Home. After paying Microsoft $99 for the privilege, I got
>> Windows 10 Pro installed and Docker started working. I've read that
>> all the cool programming kids are using Docker these days. I certainly
>> hope it was worth the cost. O_o
> 
> You could have just used a Linux VM in Virtualbox for $0, and run Docker
> in that.
> 
> Stephan
> -- 
> https://mail.python.org/mailman/listinfo/python-lists 

My $200 Dell laptop couldn't handle that combo and it would add an extra layer 
of complexity to my programming setup.

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


Re: How to determine lowest version of Python 3 to run?

2017-10-06 Thread Christopher Reimer
On Oct 5, 2017, at 3:34 PM, Christopher Reimer  
wrote:
> 
>> On Oct 5, 2017, at 1:11 PM, Irmen de Jong  wrote:
>> 
>>> On 10/05/2017 04:23 AM, Christopher Reimer wrote:
>>> 
>>> I'm leaning towards installing the latest minor version of each available 
>>> major version, running tox to run the unit tests against each one, and 
>>> seeing what blows up.
>> 
>> Perhaps you can use the service of Travis (travis-ci.org) to avoid 
>> installing the Python
>> versions yourself. They have lots of older versions available to run tests 
>> on.
>> 
>> Irmen
>> -- 
>> https://mail.python.org/mailman/listinfo/python-list
> 
> Travis might be a bit of an overkill for my project. Someone suggested docker 
> containers and there is a docker plugin for tox that looks promising.
> 
> Chris R. 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

So I got tox and tox-docker installed. When I went to install Docker for 
Windows, it wouldn't work because Hyper-V wasn't available on Windows 10 Home. 
After paying Microsoft $99 for the privilege, I got Windows 10 Pro installed 
and Docker started working. I've read that all the cool programming kids are 
using Docker these days. I certainly hope it was worth the cost. O_o

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


Re: How to determine lowest version of Python 3 to run?

2017-10-05 Thread Christopher Reimer
On Oct 5, 2017, at 1:11 PM, Irmen de Jong  wrote:
> 
>> On 10/05/2017 04:23 AM, Christopher Reimer wrote:
>> 
>> I'm leaning towards installing the latest minor version of each available 
>> major version, running tox to run the unit tests against each one, and 
>> seeing what blows up.
> 
> Perhaps you can use the service of Travis (travis-ci.org) to avoid installing 
> the Python
> versions yourself. They have lots of older versions available to run tests on.
> 
> Irmen
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Travis might be a bit of an overkill for my project. Someone suggested docker 
containers and there is a docker plugin for tox that looks promising.

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


Re: Good virtualenv and packaging tutorials for beginner?

2017-10-04 Thread Christopher Reimer
On Oct 4, 2017, at 3:49 AM, Leam Hall  wrote:
> 
> Folks on IRC have suggested using virtualenv to test code under different 
> python versions. Sadly, I've not found a virtualenv tutorial I understand. 
> Anyone have a link to a good one?
> 
> The next step will be to figure out how to package a project; a good tutorial 
> URL would be appreciated on that, too.
> 
> Thanks!
> 
> Leam
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I'm looking at tox that will automatically set up virtualenv for running unit 
tests under different versions of Python. 

https://tox.readthedocs.io/en/latest/

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


How to determine lowest version of Python 3 to run?

2017-10-04 Thread Christopher Reimer
Greetings,

I've always installed the latest and greatest version of Python 3 to develop my 
own programs. I'm planning to release a program to the public. I could toss in 
a note that the program runs on the latest version of Python 3.6 but I haven't 
tested on earlier versions (i.e., 3.4 and 3.5). AFAIK, I haven't written any 
version-specific code.

How do I determine the lowest version of Python to run?

I'm leaning towards installing the latest minor version of each available major 
version, running tox to run the unit tests against each one, and seeing what 
blows up.

Thank you, 

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


Re: How best to initialize in unit tests?

2017-10-04 Thread Christopher Reimer
On Oct 4, 2017, at 6:07 AM, Skip Montanaro  wrote:
> 
> Suppose you want to test a package (in the general sense of the word,
> not necessarily a Python package). You probably have specific unit
> tests, maybe some doctests scattered around in doc strings. Further,
> suppose that package requires you call an initialize function of some
> sort. Where does that go? I know about setUp and setUpClass methods in
> unittest.TestCase. Is order of execution of doctests deterministic
> across modules (say, when tests are run through nosetests)?
> 
> In my case, I didn't know what order things would be called, so I
> added a call to initialize() at the start of every doctest and added a
> setUpClass class method to all my TestCase subclasses. Just in case.
> It worked okay because my initialize function can be called multiple
> times. What about situations where it can only be called once? Do you
> have to define some sort of super_initialize() function for your tests
> which guarantees that your initialize function is called precisely
> once?
> 
> This all seems rather messy. I'm open to better ways to do this, but
> as I've only had one cup of coffee this morning, no spark of insight
> has zapped my frontal cortex as yet.
> 
> Thx,
> 
> Skip
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Seems like you’re overthinking this. You should be able to unit test any part 
of your code in isolation. If not, you need to refactor your code. I generally 
don’t use test classes in pytest.

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


Re: Spacing conventions

2017-09-27 Thread Christopher Reimer
On Sep 27, 2017, at 12:50 AM, Bill  wrote:
> 
> Ever since I download the MyCharm IDE a few days ago, I've been noticing all 
> sort of "spacing  conventions (from PEP) that are suggested.  How do folks 
> regard these in general?
> 
> For instance,  the conventions suggest that
> 
> if x>y :
> pass
> 
> should be written
> if x > y:
>pass
> 
> Personally, I like seeing a space before the colon (:).   And then in
> 
> my_list = [ i for i in range(0, 10) ]
> it complains about my extra space inside of the brackets.
> 
> If you are teaching beginning students, do you expect them to try to follow 
> these sorts of conventions?  Is it perfectly fine to let "taste" guide you 
> (I'm just trying to get a feel for the philosophy here)?   I also notice 
> "break" and exception handling is used much more in Python than in C++, for 
> instance.  I was taught "break" and "continue" led to "unstructured 
> code"--but that was a while back.  I can still see their use  causing 
> potential trouble in (really-long) real-world code.
> 
> Bill
> 
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I came across a Python script on Github that did what I needed except for some 
trivial modifications to make it Python 3 compatible. I did consider 
contributing changes to make the script Python 2 and 3 compatible. However, the 
script was written an idiosyncratic, anti-PEP8 style that was hard to match and 
the author previously rejected all Python 3 contributions. Forking the script 
to make it Python 2/3 compatible *and* PEP8 compliant would require too much 
effort on my part, especially since I needed to use the script only once.

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


Re: errors with json.loads

2017-09-20 Thread Christopher Reimer
> On Sep 20, 2017, at 5:03 PM, Stefan Ram  wrote:
> 
> Dennis Lee Bieber  writes:
>> After removing all the \xa0 bytes
>> and trying to decode it I get...
> 
>  I did the same here, before I read your post.
>  I got the same results, but did not post them.
> 
>  Someone has posted programs with \xA0 (NBSP IIRC)
>  at the start of lines of the soure here before, in:
> 
> From: Christopher Reimer 
> Newsgroups: comp.lang.python
> Subject: Setting property for current class from property in an different 
> class...
> Date: Wed, 6 Sep 2017 19:24:40 -0700
> Message-ID: 
> 
>  , and when I removed them, I was able to execute the
>  source from his post from 2017-Sep-06 without errors.
> 
>  So I was feeling to lazy to bother this time.
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I had a NBSP in my code?! News to me...

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


Re: Even Older Man Yells At Whippersnappers

2017-09-19 Thread Christopher Reimer
> On Sep 19, 2017, at 9:09 AM, justin walters  
> wrote:
> 
> On Tue, Sep 19, 2017 at 8:59 AM, Grant Edwards 
> wrote:
> 
>>> On 2017-09-19, Rhodri James  wrote:
 On 19/09/17 16:00, Stefan Ram wrote:
 D'Arcy Cain  writes:
> of course, I use calculators and computers but I still understand the
> theory behind what I am doing.
 
   I started out programming in BASIC. Today, I use Python,
   the BASIC of the 21st century. Python has no GOTO, but when
   it is executed, its for loop eventually is implemented using
   a GOTO-like jump instruction. Thanks to my learning of BASIC,
   /I/ can have this insight. Younger people, who never learned
   GOTO, may still be able to use Python, but they will not
   understand what is going on behind the curtains. Therefore, for
   a profound understanding of Python, everyone should learn BASIC
   first, just like I did!
>>> 
>>> Tsk.  You should have learned (a fake simplified) assembler first, then
>>> you'd have an appreciation of what your processor actually did.
>>> 
>>> :-)
>> 
>> Tsk, Tsk.  Before learning assembly, you should design an instruction
>> set and implement it in hardare.  Or at least run in in a VHDL
>> simulator.  [Actually, back in my undergrad days we used AHPL and
>> implemented something like a simplified PDP-11 ISA.]
>> 
>> Alternatively, you should design an instruction set and implement it
>> using microcode and AM2900 bit-slice processors.
>> 
>> --
>> Grant Edwards   grant.b.edwardsYow! Could I have a drug
>>  at   overdose?
>>  gmail.com
>> 
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>> 
> 
> Even Assembly is easy nowadays:
> https://fresh.flatassembler.net/index.cgi?page=content/1_screenshots.txt
> -- 
> https://mail.python.org/mailman/listinfo/python-list

Is assembly still a thing today? 

I wanted to take assembly in college but I was the only student who showed up 
and the class got cancelled. I dabbled with 8-but assembly as a kid. I can't 
imagine what assembly is on a 64-bit processor.

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


Re: Old Man Yells At Cloud

2017-09-17 Thread Christopher Reimer
> On Sep 17, 2017, at 2:19 PM, Ned Batchelder  wrote:
> 
>> On 9/16/17 1:38 AM, Steve D'Aprano wrote:
>> /rant on
>> 
>> So apparently everyone who disagrees that Python should be more like 
>> Javascript
>> is an old greybeard fuddy-duddy yelling "Get off my lawn!" to the cool kids 
>> --
>> and is also too stupid to know how dumb they are.
>> 
>> "Hi, I've been programming in Python for what seems like days now, and here's
>> all the things that you guys are doing wrong. I insist that you fix them
>> immediately, it doesn't matter how much code it will break, that's not
>> important. What is important is that Javascript programmers like me shouldn't
>> be expected to learn anything new or different when they program with 
>> Python."
>> 
>> /rant off
>> 
>> And no, for once it wasn't Ranting Rick.
> 
> The thing that struck me about the interaction (on Python-Ideas, btw) was 
> that Javascript actually is adding new language features at an impressive 
> pace, and many of them seem very Pythonic.  But they sometimes choose 
> different syntax.
> 
> For example, their "spread" operator is ..., where Python uses *:
> 
> new_list = [new_start, *old_list, new_end]
> 
> vs:
> 
> new_array = [new_start, ...old_array, new_end]
> 
> Making Python more like Javascript (in this case) would have required 
> breaking existing Python programs. Javascript could have use * as the spread 
> operator without breaking anyone. But they didn't, and I wonder if anyone 
> petitioned them to keep compatibility with Python to easy the plight of the 
> multi-lingual programmer.
> 
> --Ned.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I came across a blog post that pointed out that those who advocate for a 
particular JavaScript framework probably know enough JavaScript for the 
framework but not enough JavaScript to figure out a problem with the framework. 
Since frameworks are an abstraction of JavaScript, you really need to know 
JavaScript to avoid getting stuck with a framework. I know enough JavaScript to 
get the JQuery eye candy to work and I'm confused by all the frameworks 
available. I picked up a JavaScript ebook to familiarize myself with the 
language. This isn't the same JavaScript that I learned in the early 2000's. 

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


Re: The Incredible Growth of Python (stackoverflow.blog)

2017-09-14 Thread Christopher Reimer
> On Sep 13, 2017, at 10:12 PM, Paul Rubin  wrote:
> 
> Ben Finney  writes:
>>> I've never seen one.
>> who has told you... they are working on a Python 3 code base.
> 
> Just because they've told me about it doesn't mean I saw it personally.
> The ones I've seen, including new ones, are Python 2.
> 
> Some people here use Py3 but I haven't heard (or don't remember) enough
> about what they're working on, to know if those are py3 codebases of any
> size.  If they say yes, I'll take their word for it, but this is a
> self-selected group of course.
> 
>> That simply isn't true, unless you think it more likely everyone who
>> discusses their Python 3 code base is lying.
> 
> People discuss Python language issues here a lot, but don't discuss as
> much about code bases.
> 
> I know when I install a new OS (currently Debian 9 which was released
> a month or so ago) and type "python" on the command line, I get Py2.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

FreeNAS 11 (based on FreeBSD) has Python 3.6.1 installed and uses Django for 
the web interface.

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


Re: "tkinter"

2017-09-13 Thread Christopher Reimer
> On Sep 13, 2017, at 5:28 AM, Stefan Ram  wrote:
> 
>  I presume that "tkinter" is intended to be pronounced
>  "logically":
> 
> T K inter (tee kay inter /ti keI In t%/)
> 
>  . But it would be faster to pronounce it 
> 
> T kinter (tee kinter /ti kIn t%/)
> 
>  . So far I've only ever read it, never heard it.
>  But while I am aware that the logical pronunciation should
>  be the correct one, I actually like the faster one.
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

When I started my technical career 20+ years ago, tcl/tk was pronounced 
"tickle" by the engineers.  Not sure if that was correct then or now.

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


Re: Simple board game GUI framework

2017-09-11 Thread Christopher Reimer
> On Sep 11, 2017, at 3:58 AM, Paul Moore  wrote:
> 
> I'm doing some training for a colleague on Python, and I want to look
> at a bit of object orientation. For that, I'm thinking of a small
> project to write a series of classes simulating objects moving round
> on a chess-style board of squares.
> 
> I want to concentrate on writing the classes and their behaviour, and
> not on display issues, but I would like it if the resulting program
> was reasonably interesting. To that end, I was thinking of putting
> together a frontend that displayed the objects moving round on a board
> (rather than, for example, just printing out lists of co-ordinates).
> I'd build the frontend, then my student could write the object classes
> and drop them into the framework.
> 
> My problem is that I've never written any sort of game code for
> Python, which is basically what this is. And I don't have a lot of
> time to develop something. So I was wondering - are there any
> ready-made examples of the sort of driver I'm thinking of? Something
> like a framework for a Chess or Othello game, but with the actual game
> logic isolated so I could easily rip it out and replace it with my
> own. I've done some searching around, but most of the examples I've
> seen seem to have the display and game logic intermingled (at least to
> my untrained eye).
> 
> Any suggestions? If not, I guess I'll just have to write my own. I'm
> sure I could - it's just that I don't want my training to be messed up
> because of bugs in my code...
> 
> Thanks,
> Paul
> -- 
> https://mail.python.org/mailman/listinfo/python-list

I started something similar to this and didn't get far. I wrote a base class 
called Piece that had common attributes (I.e., color and position) and abstract 
methods (i.e., move). From the base class I derived all the piece types. That's 
the easy part.

The board is a bit tricky, depending on how you set it up. The board of 64 
squares could be a list, a dictionary or a class. I went with a Board class 
that used a coordinate system (i.e., bottom row first square was (0, 0) and top 
row last square (7, 7)) and kept track of everything on the board.

The furthest I got with this was a simple text display and interface to move 
pawns and bishops forward.

Chess may look straight forward but it can get complicated in a hurry. If you 
look at the computing literature, chess has been a never ending rabbit hole for 
50+ years. 

Chris R.

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


Re: Merge pdf files using information from two files

2017-09-08 Thread Christopher Reimer
> On Sep 8, 2017, at 1:21 PM, accessnew...@gmail.com wrote:

> Ideas as to how to accomplish this?

Export your spreadsheets as Comma Separated Values (CSV) files and use the CSV 
module to read/write those files.

https://docs.python.org/3/library/csv.html

Chris R. 

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


Re: Using Python 2

2017-09-08 Thread Christopher Reimer
> On Sep 8, 2017, at 6:57 AM, Ned Batchelder  wrote:
> 
> What is it that CompSci folks want that developers don't
> want, that ruined Python 3?

Long-winded debates about obscure language features that left the layman 
programmers in the bit bucket about 50+ comments ago.

While some of this can be informative and enlightening, it can also be a bit  
tedious to read. Just saying...

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


Re: Setting property for current class from property in an different class...

2017-09-07 Thread Christopher Reimer via Python-list

On 9/6/2017 9:26 PM, Christopher Reimer wrote:


On Sep 6, 2017, at 9:14 PM, Stefan Ram  wrote:

  I can run this (your code) without an error here (Python 3.6.0),
  from a file named "Scraper1.py":

I'll check tomorrow. I recently switched from 3.5.x to 3.6.1 in the PyCharm 
IDE. It's probably FUBAR in some obscure way.


I uninstalled Python 3.6.0 (32-bit) and Python 3.6.1 (64-bit), installed 
Python 3.6.2 (64-bit), and everything now works.


Thanks,

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


Re: Setting property for current class from property in an different class...

2017-09-06 Thread Christopher Reimer
> On Sep 6, 2017, at 9:14 PM, Stefan Ram  wrote:
> 
>  I can run this (your code) without an error here (Python 3.6.0),
>  from a file named "Scraper1.py":

I'll check tomorrow. I recently switched from 3.5.x to 3.6.1 in the PyCharm 
IDE. It's probably FUBAR in some obscure way.

Thanks,

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


Re: Setting property for current class from property in an different class...

2017-09-06 Thread Christopher Reimer via Python-list

On 9/6/2017 7:41 PM, Stefan Ram wrote:

The following code runs here: 


Your code runs but that's not how I have mine code set up. Here's the 
revised code:



class Requestor(object):
    def __init__(self, user_id, user_name ):
    self._page_start = -1

    @property
    def page_start(self):
    return self._page_start

    @page_start.setter
    def page_start(self, number):
    self._page_start = number



class Scraper(object):
 def __init__(self, user_id, user_name):
 self.requestor = Requestor(user_id, user_name)
 @property
 def page_start(self):
 return self.requestor.page_start
 @page_start.setter
 def page_start(self, number):
 self.requestor.page_start = number

>>> test = Scraper(1, 1)
>>> test.page_start
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 20, in page_start
AttributeError: 'Requestor' object has no attribute 'page_start'


That's a slightly different error than what I got my code, where the 
Scraper object didn't have the attribute.


Could it be that @property item can't call another @property item?

Thank you,

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


Setting property for current class from property in an different class...

2017-09-06 Thread Christopher Reimer via Python-list

Greetings,

My web scraper program has a top-level class for managing the other 
classes. I went to set up a property for the top-level class that 
changes the corresponding property in a different class.


class Scraper(object):

    def __init__(self, user_id, user_name):
    self.requestor = Requestor(user_id, user_name)

    @property
    def page_start(self):
    return self.requestor.page_start

    @page_start.setter
    def page_start(self, number):
    self.requestor.page_start = number


I get the following error for @page_start.setter when I try to run the code.

    AttributeError: 'Scraper' object has no attribute 'requestor'

That's either a bug or I'm doing it wrong. Or maybe both?

Thank you,

Chris R.

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


Re: Have do_nothing as default action for dictionary?

2017-09-04 Thread Christopher Reimer via Python-list

Greetings,

After reading everyone's comments and doing a little more research, I 
re-implemented my function as a callable class.


    def __call__(self, key, value):
    if key not in self._methods:
    return value
    return self._methods[key](value)

This behaves like my previous function, solved the problem that I had 
with the dictionary, the dictionary is created only once, a half dozen 
functions got moved into the new class, and the old class now has less 
clutter.


Thanks everyone!

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


Have do_nothing as default action for dictionary?

2017-09-03 Thread Christopher Reimer via Python-list

Greetings,

I was playing around this piece of example code (written from memory).


def filter_text(key, value):

    def do_nothing(text): return text

    return {'this': call_this,

  'that': call_that,

  'what': do_nothing

 }[key](value)


Is there a way to refactor the code to have the inner do_nothing 
function be the default action for the dictionary?


The original code was a series of if statements. The alternatives 
include using a lambda to replace the inner function or a try-except 
block on the dictionary to return value on KeyError exception.


What's the most pythonic and fastest?

Thank you,

Chris R.

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


Re: BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list
Ah, shoot me. I had a .join() statement on the output queue but not on 
in the input queue. So the threads for the input queue got terminated 
before BeautifulSoup could get started. I went down that same rabbit 
hole with CSVWriter the other day. *sigh*


Thanks for everyone's help.

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


Re: BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list

On 8/27/2017 1:50 PM, MRAB wrote:
What if you don't sort the list? I ask because it sounds like you're 
changing 2 variables (i.e. list->queue, sorted->unsorted) at the same 
time, so you can't be sure that it's the queue that's the problem.


If I'm using a list, I'm using a for loop to input items into the parser.

If I'm using a queue, I'm using worker threads to put or get items.

The item is still the same whether in a list or a queue.

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


Re: BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list

On 8/27/2017 1:31 PM, Peter Otten wrote:


Here's a simple example that extracts titles from generated html. It seems
to work. Does it resemble what you do?
Your example is similar to my code when I'm using a list for the input 
to the parser. You have soup_threads and write_threads, but no read_threads.


The particular website I'm scraping requires checking each page for the 
sentinel value (i.e., "Sorry, no more comments") in order to determine 
when to stop requesting pages. For my comment history that's ~750 pages 
to parse ~11,000 comments.


I have 20 read_threads requesting and putting pages into the output 
queue that is the input_queue for the parser. My soup_threads can get 
items from the queue, but BeautifulSoup doesn't do anything after that.


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


Re: BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list

On 8/27/2017 1:12 PM, MRAB wrote:

What do you mean by "queue (random order)"? A queue is sequential 
order, first-in-first-out. 


With 20 threads requesting 20 different pages, they're not going into 
the queue in sequential order (i.e., 0, 1, 2, ..., 17, 18, 19) and 
coming in at different times for the parser worker threads to get for 
processing.


Similar situation with a list but I sort the list before giving it to 
the parser, so all the items are in sequential order and fed to the 
parser one at time.


Chris R.

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


Re: BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list

On 8/27/2017 11:54 AM, Peter Otten wrote:


The documentation

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup

says you can make the BeautifulSoup object from a string or file.
Can you give a few more details where the queue comes into play? A small
code sample would be ideal.


A worker thread uses a request object to get the page and puts it into 
queue as page.content (HTML).  Another worker thread gets the 
page.content from the queue to apply BeautifulSoup and nothing happens.


soup = BeautifulSoup(page_content, 'lxml')
print(soup)

No output whatsoever. If I remove 'lxml', I get the UserWarning that no 
parser wasn't explicitly set and get the reference to threading.py at 
line 80.


I verified that page.content that goes into and out of the queue is the 
same page.content that goes into and out of a list.


I read somewhere that BeautifulSoup may not be thread-safe. I've never 
had a problem with threads storing the output into a queue. Using a 
queue (random order) instead of a list (sequential order) to feed pages 
for the input is making it wonky.


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


BeautifulSoup doesn't work with a threaded input queue?

2017-08-27 Thread Christopher Reimer via Python-list

Greetings,

I have Python 3.6 script on Windows to scrape comment history from a 
website. It's currently set up this way:


Requestor (threads) -> list -> Parser (threads) -> queue -> CVSWriter 
(single thread)


It takes 15 minutes to process ~11,000 comments.

When I replaced the list with a queue between the Requestor and Parser 
to speed up things, BeautifulSoup stopped working.


When I changed BeautifulSoup(contents, "lxml") to 
BeautifulSoup(contents), I get the UserWarning that no parser wasn't 
explicitly set and a reference to line 80 in threading.py (which puts it 
in the RLock factory function).


When I switched back to using list between the Requestor and Parser, the 
Parser worked again.


BeautifulSoup doesn't work with a threaded input queue?

Thank you,

Chris Reimer

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


Re: School Management System in Python

2017-07-05 Thread Christopher Reimer
On Jul 5, 2017, at 6:34 AM, Sam Chats  wrote: 
> Just curious, is it better, performance wise, to read from a text file (css 
> or tsv) compared to reading from a binary pickle file?

I prefer CSV because I can load the file into Microsoft Excel and do a quick 
search.

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


Re: Reciprocal data structures

2017-06-19 Thread Christopher Reimer
> On Jun 18, 2017, at 11:02 PM, Chris Angelico  wrote:
> 
> On Mon, Jun 19, 2017 at 3:54 PM, Steven D'Aprano  wrote:
>>> With a list? No, I would say it's a bad idea.
>> 
>> 
>> Why a bad idea?
>> 
>> As opposed to "can't be done", or "too hard and slow".
> 
> Maintaining a record of list indices inside an object, with the
> specific proviso that:
> 
>> If the list is changed, the list updates the indices.
> 

A linked list with pointers to the next and previous items?

If this was a homework problem, a linked list is usually implemented in C. The 
list keyword in Python is not the same thing.

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


Re: Developers Who Use Spaces Make More Money!

2017-06-15 Thread Christopher Reimer
> On Jun 15, 2017, at 3:24 PM, jlada...@itu.edu wrote:
> 
> This is hilarious, I have to share:
> 
> https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/
> 
> Thanks to Guido for making us all richer!

One commentator on a tech website admonished programmers for wasting time by 
pressing the space bar four times instead of using tab. O_o

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


Re: openpyxl reads cell with format

2017-06-05 Thread Christopher Reimer

On 6/5/2017 4:55 PM, Gregory Ewing wrote:


Mahmood Naderan wrote:
from a button on a web page, I chose "export as excel" to download 
the data.


Do you get an option to export in any other format?
CSV would be best, since you can trivially read that
with Python's csv module.

If Excel is the only format available, you should
complain to the website maintainers that their
export function is broken and is corrupting data.


I had the opposite problem of converting the timestamp from a scraped 
web page into a timezone-aware timestamp to save into a CSV file that 
was sortable in Excel. It took me a while to figure out that my source 
timestamp was set to US/Eastern even though I was viewing it as 
US/Pacific on the website. I wrote down my thought process in a blog 
post that may help this situation.


https://www.kickingthebitbucket.com/2017/04/04/the-python-time-zone-rabbit-hole/

Thank you,

Chris Reimer

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


Passing yield as a function argument...

2017-05-23 Thread Christopher Reimer

Greetings,

I have two functions that I generalized to be nearly identical except 
for one line. One function has a yield statement, the other function 
appends to a queue.


If I rewrite the one line to be a function passed in as an argument -- 
i.e., func(data) -- queue.append works fine. If I create and pass an 
inner function with the yield statement, nothing happens.


Is it possible to pass a yield statement in some form as a function 
argument?


Thank you,

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


Re: Finding sentinel text when using a thread pool...

2017-05-20 Thread Christopher Reimer via Python-list

On 5/20/2017 1:19 AM, dieter wrote:


If your (590) pages are linked together (such that you must fetch
a page to get the following one) and page fetching is the limiting
factor, then this would limit the parallelizability.


The pages are not linked together. The URL requires a page number. If I 
requested 1000 pages in sequence, the first 60% will have comments and 
the remaining 40% will have the sentinel text. As more comments are 
added over time, the dividing line between the last page with the oldest 
comments and the first page with the sentinel page shifts over time. 
Since I changed the code to fetch 16 pages at the same time, the run 
time got reduced by nine minutes.



If processing a selected page takes a significant amount of time
(compared to the fetching), then you could use a work queue as follows:
a page is fetched and the following page determined; if a following
page is found, processing this page is put as a job into the work queue
and page processing is continued. Free tasks look for jobs in the work queue
and process them.


I'm looking into that now. The requester class yields one page at a 
time. If I change the code to yield a list of 16 pages, I could parse 16 
pages at a time. That change would require a bit more work but it would 
fix some problems that's been nagging me for a while about the parser class.


Thank you,

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


Finding sentinel text when using a thread pool...

2017-05-19 Thread Christopher Reimer

Greetings,

I'm developing a web scraper script. It takes 25 minutes to process 590 
pages and ~9,000 comments. I've been told that the script is taking too 
long.


The way the script currently works is that the page requester is a 
generator function that requests a page, checks if the page contains the 
sentinel text (i.e., "Sorry, no more comments."), and either yields the 
page and request the next page or exits the function. Every yielded page 
is parsed by Beautiful Soup and saved to disk.


Timing the page requester separately from the rest of the script and the 
end value set to 590, each page request takes 1.5 seconds.


If I use a thread pool of 16 threads, each request takes 0.1 seconds. 
(Higher thread numbers will result in the server forcibly closing the 
connection.)


I'm trying to figure out how I would find the sentinel text by using a 
thread pool. Seems like I need to request an arbitrary number of pages 
(perhaps one page per thread), evaluate the contents of each page for 
the sentinel text, and either request another set of pages or exit the 
function.


Is that the most efficient approach for using a thread pool?

I'm using this article for the thread pool coding example.

http://chriskiehl.com/article/parallelism-in-one-line/

Thank you,

Chris Reimer


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


Re: Python inner function parameter shadowed

2016-09-14 Thread Christopher Reimer
> On Sep 13, 2016, at 8:58 PM, Lawrence D’Oliveiro  
> wrote:
> 
>> On Wednesday, September 14, 2016 at 4:34:34 AM UTC+12, Daiyue Weng wrote:
>> PyCharm warns about "Shadows name 'func' from outer scope"
> 
> Typical piece of software trying to be too helpful and just getting in the 
> way.
> 
> Can you turn off such warnings?

IIRC, if you turn off this warning, it also turns off a more useful warning 
somewhere else.

My favorite PyCharm warning bug is creating a base class with an implemented 
getter and an unimplemented setter. When the base class is inherited and the 
setter is implemented, the IDE warns that the getter is missing. The workaround 
is to implement the getter with a super call. This bug is several years old and 
no one had fixed it because it has workaround.

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


Re: [OT] Altair

2016-08-30 Thread Christopher Reimer


> On Aug 30, 2016, at 11:51 AM, Joe  wrote:
> 
>> Am 30.08.2016 um 17:52 schrieb D'Arcy J.M. Cain:
>> On Tue, 30 Aug 2016 15:56:07 +0200
>> Joe  wrote:
>>> Am 30.08.2016 um 13:01 schrieb D'Arcy J.M. Cain:
 On Mon, 29 Aug 2016 21:21:05 -0700
 Larry Hudson via Python-list  wrote:
> I remember it well.  It's what I used to initially learn C.  I'm a
> completely self-taught, hobby programmer.  Been around since the
> MITS Altair.  How many remember that beast??
 
 Remember it and still have it in the basement.
>>> I read a lot about the Altair in Byte in those days, but never had a
>>> chance to touch it. Wasn't it horrible expensive?
>> 
>> I can't remember what is was going for but I bought mine used for
>> $1,000.  It had a number of add-ons including a keyboard and floppy
>> drives.  The power supply was also beefed up.
>> 
>> It also had a replacement bezel.  It seems that the original Altair's
>> silk screened front panel was crappy and rubbed off easily.  Some
>> company sold one but it says "Cycloid" instead of "Altair" on it.
> 
> I think the first BASIC Interpreter ever sold by Gates & Friend was for this 
> machine? How did you use your floppy drives on this machine 
> (Open-Write-Close)?

Paper tape reader. The first time I came across a paper tape reader when I 
visited the university as a teenager in 1984. A CNC machine read the paper tape 
to drill six holes in a piece of metal.

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


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jul 1, 2016, at 6:52 AM, Steven D'Aprano  wrote:
> 
>> On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:
>> 
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
> [...]
>> By using * to unpack the split line, my program no longer crashes and no
>> try/except block is needed to work around the crash. A later line of code
>> will test the expression, ignore if empty or run regex if full.
> 
> I wish you wouldn't describe this as "crash".
> 
> The Python interpreter should never crash. That would be a segmentation
> fault, and that is considered to be a very serious bug.
> 
> But *raising an exception* is another story. Raising exceptions is not a
> crash, it is the interpreter working as expected. This statement:
> 
>line_number, keyword, expr = "20 END".split(' ', 2)
> 
> is SUPPOSED to raise an exception, if it didn't, the interpreter would be
> broken. To call that a "crash" is horribly misleading.

Where did I write that the Python interpreter had "crashed"?

I wrote that *my program* crashed and I found an elegant solution to prevent 
the crashing from happening in the first place that doesn't require a 
try/except block.

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


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jul 1, 2016, at 5:46 AM, Jussi Piitulainen  
> wrote:
> 
> Christopher Reimer writes:
> 
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
>> 
>> line_number, keyword, *expression = line.split(' ', 2)
>> 
>> For a line like 10 PRINT "HELLO, WORLD!", this works as expected.
>> 
>> For a line like 20 END, which doesn't have a third element for
>> expression, an empty list is assigned.
>> 
>> By using * to unpack the split line, my program no longer crashes and
>> no try/except block is needed to work around the crash. A later line
>> of code will test the expression, ignore if empty or run regex if
>> full.
> 
> Yes.
> 
> Consider line.split(None, 2) or line.split(maxsplit=2). You may still
> need to strip the third component, but at least it will *be* the third
> component even if the user happens to type extra spaces like this:
> 
> 10   PRINT  "Hello, world."
> 
> And you won't get a spurious third component if the user types this:
> 
> 20 END   
> 
> (There's trailing spaces.)

This is a BASIC interpreter. Any extra spaces for line_number or keyword will 
raise an incomprehensible syntax error, as the line number must convert to an 
integer and the keyword much match the KEYWORDS list. As for trailing spaces 
for expression, regex will keep them whole if enclosed in double quotes or 
convert them to a list element. Depending on the keyword grammar, extra spaces 
are likely to be ignored.

A C interpreter would be more difficult as the same line of code could be 
written several different ways and be valid.

FILE *source
FILE * source
FILE* source
FILE*source

The first line is how I normally see this statement written. The last line I 
found in a 1991 book with a strange dialect of C that I've never seen before 
and doesn't always compile correctly without modification. Writing a C 
interpreter is not on my to do list. 

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


Re: Creating a calculator

2016-07-01 Thread Christopher Reimer
> On Jun 30, 2016, at 11:42 PM, Jussi Piitulainen 
>  wrote:
> 
> DFS writes:
> 
>> Here's a related program that doesn't require you to tell it what type
>> of operation to perform.  Just enter 'num1 operator num2' and hit
>> Enter, and it will parse the entry and do the math.
>> 
>> ---
>> ui=raw_input('Enter calculation to perform: ')
>> n1=float(ui.split(' ')[0])
>> op=ui.split(' ')[1]
>> n2=float(ui.split(' ')[2])
>> if op=='+':c=n1+n2
>> if op=='-':c=n1-n2
>> if op=='*':c=n1*n2
>> if op=='/':c=n1/n2
>> print(ui+' = '+str(c))
>> ---
> 
> I use multiple assignment a lot, like this:
> 
>n1, op, n2 = ui.split()
> 
> It's not only compact, it also crashes if there are more elements than
> expected, and I want it to crash when that happens. Or rather, I prefer
> a crash to silence when input is bad.
> 
> For the calculator, it may be better to split on any whitespace and
> discard empty strings, which is what ui.split() does. Splitting on a
> single space seems unnecessarily strict in a calculator (whereas
> splitting on a single tab is what I very much do in my work - the data
> formats are such).
> 
> I think multiple assignment is good even for a beginner. Perhaps do it a
> second time straight away:
> 
>n1, op, n2 = ui.split()
>n1, n2 = float(n1), float(n2)
> 
> But it's only with the split where it really pays.
> 
>n1, op, n2 = ui.split()
>n1 = float(n1)
>n2 = float(n2)
> 
> The latter might be even preferable. Hm.
> 
>n1, n2 = map(float, (n1, n2))
> 
> :)

For my BASIC interpreter, each line of BASIC is broken this way into tokens.

line_number, keyword, *expression = line.split(' ', 2)

For a line like 10 PRINT "HELLO, WORLD!", this works as expected.

For a line like 20 END, which doesn't have a third element for expression, an 
empty list is assigned.

By using * to unpack the split line, my program no longer crashes and no 
try/except block is needed to work around the crash. A later line of code will 
test the expression, ignore if empty or run regex if full. 

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


Re: Empty List

2016-06-26 Thread Christopher Reimer

On 6/26/2016 8:13 PM, Elizabeth Weiss wrote:


Hi There,

What is the point of this code?:

word=[]
print(word)

The result is []

When would I need to use something like this?

Thank you!


Sometimes you need to assign an empty list to a variable prior to using 
it in a looping structure.


Here's the load function from the BASIC interpreter/compiler I'm working 
on in Python.


def load(filename):
tokens = []
with open(filename) as source:
for line in source:
tokens.append(tokenizer(line))
return tokens

Here's the BASIC file I'm loading:

10 PRINT "HELLO WORLD!"
20 GOTO 10

This function assigns an empty list to tokens, reads a line of text from 
a file, and appends a tokenized list to tokens, and return tokens as a 
list of lists.


[['10', 'PRINT', '"HELLO WORLD!"'], ['20', 'GOTO', '10']]

Chris R.



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


Re: Assignment Versus Equality

2016-06-26 Thread Christopher Reimer

On 6/26/2016 8:41 AM, MRAB wrote:


On 2016-06-26 11:48, BartC wrote:

On 26/06/2016 08:36, Lawrence D’Oliveiro wrote:
One of Python’s few mistakes was that it copied the C convention of 
using “=” for assignment and “==” for equality comparison.


One of C's many mistakes. Unfortunately C has been very influential.

However, why couldn't Python have used "=" both for assignment, and for
equality? Since I understand assignment ops can't appear in expressions.


[snip]

Python supports chained assignments. For example, "a = b = 0" assigns 
0 to both a and b.


I'm not sure how common it is, though. I virtually never use it myself.


How can you not use chained assignments? I thought Python was the art of 
the clever one-liners. :)


Chris R.

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


Re: Assignment Versus Equality

2016-06-26 Thread Christopher Reimer

On 6/26/2016 6:21 AM, Steven D'Aprano wrote:


On Sun, 26 Jun 2016 08:48 pm, BartC wrote:


On 26/06/2016 08:36, Lawrence D’Oliveiro wrote:

One of Python’s few mistakes was that it copied the C convention of using
“=” for assignment and “==” for equality comparison.

One of C's many mistakes. Unfortunately C has been very influential.

However, why couldn't Python have used "=" both for assignment, and for
equality? Since I understand assignment ops can't appear in expressions.

Personally, I think that even if there is no *syntactical* ambiguity between
assignment and equality, programming languages should still use different
operators for them. I must admit that my first love is still Pascal's :=
for assignment and = for equality, but C's = for assignment and == for
equality it *almost* as good.

(It loses a mark because absolute beginners confuse the assignment = for the
= in mathematics, which is just different enough to cause confusion.)

But the BASIC style = for both assignment and equality is just begging for
confusion. Even though = is not ambiguous given BASIC's rules, it can still
be ambiguous to beginners who haven't yet digested those rules and made
them second nature.

And even experts don't always work with complete statements. Here is a
snippet of BASIC code:

X = Y

Is it an assignment or an equality comparison? Without seeing the context,
it is impossible to tell:

10 X = Y + 1
20 IF X = Y GOTO 50


Now obviously BASIC was a very popular and successful language, for many
years, despite that flaw. But I wouldn't repeat it in a new language.



It should have copied the old convention from Algol-like languages
(including Pascal), where “:=” was assignment, so “=” could keep a
meaning closer to its mathematical usage.

(I think Fortran and PL/I also used "=" for assignment. Both were more
commercially successful than Algol or Pascal.)

Fortran 77 used .EQ. for equality. I'm not sure about PL/I.

I'm also not sure I'd agree about the commercial success. Fortran certainly
has been extremely popular, albeit almost entirely in numerical computing.
But PL/I has virtually disappeared from the face of the earth, while Pascal
still has a small but dedicated community based on FreePascal, GNU Pascal,
and Delphi.

(Of the three, FreePascal and Delphi appear to still be getting regular
releases.)


I started writing a BASIC interpreter in Python. The rudimentary version 
for 10 PRINT "HELLO, WORLD!" and 20 GOTO 10 ran well. The next version 
to read each line into a tree structure left me feeling over my head. So 
I got "Writing Compilers & Interpreters: An Applied Approach" by Ronald 
Mak (1991 edition) from Amazon, which uses C for coding and Pascal as 
the target language.  I know a little bit of C and nothing of Pascal. 
Translating an old dialect of C into modern C, learning Pascal and 
figuring out the vagaries of BASIC should make for an interesting 
learning experience.


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


Re: Is signed zero always available?

2016-06-22 Thread Christopher Reimer
> On Jun 22, 2016, at 7:59 AM, Grant Edwards  wrote:
> 
>> On 2016-06-22, Random832  wrote:
>>> On Wed, Jun 22, 2016, at 10:19, Grant Edwards wrote:
>>> 
>>> Is that guaranteed by Python, or just a side-effect of the
>>> implementation?  Back in the days when Python used native C
>>> integers I think the latter.
>> 
>> AIUI, native C integers have never reliably supported signed zero
>> even with representations that naively seem to have it. There's no
>> well-defined way to detect it - no int version of copysign, for
>> instance - and implementations are free to erase the distinction on
>> every load/store or define one of them to be a trap representation.
> 
> It's been almost 25 years since I used hardware that supported signed
> zero integers (CDC 6600).  I don't recall there being a C compiler
> available.  We used Pascal and assembly, though I think FORTRAN was
> what most people used.  I don't recall whether the Pascal
> implementation exposed the existence of -0 to the user or not.

When I took mathematics in college, the following was true:

-1 * 0 = 0

I would probably have gotten rapped on the knuckles by my instructors if I 
answered -0. Zero was zero. No plus or minus about that. No discussion of 
signed integers ever mentioned signed zero.

Did I miss something in college?

Or did -0 represent zero volts on the negative rail of an op-amp in 
electronics? 

Thank you,

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


Re: i'm a python newbie & wrote my first script, can someone critique it?

2016-06-10 Thread Christopher Reimer


Sent from my iPhone

> On Jun 10, 2016, at 3:52 PM, mad scientist jr  
> wrote:
> . 
> Now that it's done, I am wondering what kind of things I could do better.

This is Python, not BASIC. Lay off on the CAP LOCK key and delete all the 
comments and separation blocks. No one is going to find your code in all that 
noise.

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


Re: I'm wrong or Will we fix the ducks limp?

2016-06-03 Thread Christopher Reimer

On 6/3/2016 7:31 PM, Steven D'Aprano wrote:


On Sat, 4 Jun 2016 09:06 am, Sayth Renshaw wrote:


I cant create a list with an append method pf.append(thing) in one go .

Correct. You cannot append to a list until the list exists.

Nor can you uppercase a string until the string exists:

s = "hello world"
s = s.uppercase()


>>> s = "hello world".upper()
>>> print(s)
HELLO WORLD

This works in Python 3. Not sure if s.uppercase() was meant as an 
example for a different language.


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


Re: for / while else doesn't make sense

2016-05-25 Thread Christopher Reimer
> On May 25, 2016, at 3:47 AM, Marko Rauhamaa  wrote:
> 
> Christopher Reimer :
> 
>> Back in the early 1980's, I grew up on 8-bit processors and latin-1 was
>> all we had for ASCII.
> 
> You really were very advanced. According to  https://en.wikipedia.org/wiki/ISO/IEC_8859-1#History>, ISO 8859-1 was
> standardized in 1985. "Eight-bit-cleanness" became a thing in the early
> 1990's.

Apparently, I wasn't. According to the Internet, which can't be wrong, many of 
the 8-bit computers in the early 1980's were based on 1960's ASCII with some 
non-standard characters tossed in. Latin-1 probably came during my DOS days in 
the 1990's.

As for ISO 8859-1, the standard was approved in 1985 but it was based on the 
character set for the first ANSI standard terminal, DEC VT-2200, that came out 
in 1983. Still early 1980's. ;)

Thank you,

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


Re: for / while else doesn't make sense

2016-05-25 Thread Christopher Reimer

> On May 24, 2016, at 11:38 PM, Gregory Ewing  
> wrote:
> 
> Christopher Reimer wrote:
>> Nope. I meant 8-bit ASCII (0-255).
>> http://www.ascii-code.com
> 
> That page is talking about latin-1, which is just one of many
> possible 8-bit extensions of ascii.

Back in the early 1980's, I grew up on 8-bit processors and latin-1 was all we 
had for ASCII. Over the last several days from reading this thread (and 
variations thereof), l've seen several extended characters that I have no clue 
on how to reproduce on my keyboard. I haven't embraced extended character sets 
yet, which means I still think of ASCII characters as being 0 through 255 
(8-bit).

Thank you,

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


Re: for / while else doesn't make sense

2016-05-24 Thread Christopher Reimer
On May 24, 2016, at 7:23 AM, Grant Edwards  wrote:
> 
>> On 2016-05-24, Steven D'Aprano  wrote:
>>> On Tue, 24 May 2016 08:36 am, Christopher Reimer wrote:
>>> 
>>> Those symbols are blowing my 8-bit ASCII brain. :)
>> 
>> That's certainly true, because there is no such thing as 8-bit ASCII.
> 
> He meant to say "my 8-bit, ASCII brain".  The adjectives "8-bit" and
> "ASCII" were both modifying brain.

Nope. I meant 8-bit ASCII (0-255).

http://www.ascii-code.com

Thank you,

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


Re: for / while else doesn't make sense

2016-05-23 Thread Christopher Reimer
> On May 23, 2016, at 1:22 PM, Grant Edwards  wrote:
> 
>> On 2016-05-23, Ian Kelly  wrote:
>>> On Mon, May 23, 2016 at 9:53 AM, Ian Kelly  wrote:
>>> I'm not sure where ℝ comes into this in the first place. Existing
>>> Python numeric types only represent various subsets of ℚ (in the case
>>> of fractions.Fraction, the entirety of ℚ).
>> 
>> And of course I realized after sending that I forgot about complex
>> numbers. But even there Python merely represents 2-tuples of ℚ.
> 
> OK, admit it, now you're all just showing off the fact that you know
> how to type in those fancy symbols.

Those symbols are blowing my 8-bit ASCII brain. :)

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


Re: Education [was Re: for / while else doesn't make sense]

2016-05-21 Thread Christopher Reimer

On 5/21/2016 3:05 AM, Steven D'Aprano wrote:

On Sat, 21 May 2016 03:18 pm, Rustom Mody wrote:


Given that for the most part, most of us are horribly uneducated [


http://www.creativitypost.com/education/9_elephants_in_the_classroom_that_should_unsettle_us

]
how do we go about correcting our wrong primacies?



An interesting article, but very US-centric.

Nevertheless, let's not forget that the general school system is designed to
churn out more-or-less identical workers capable of pulling the levers on
late 19th and early 20th century machines for their bosses. The fact that
it does more than that, even if badly, is a bonus.


Under various proposals in the U.S., everyone will soon learn how to 
program and/or become a computer scientist. Won't be long before some 
snotty-nosed brat graduates from preschool, takes a look at your code, 
and poops in his diapers. He will then dips his finger into his diaper, 
write on the whiteboard how your code can be written in a single line, 
and summary dismiss you with security escorting you off the premises.


Gotta love the future. :)

Thank you,

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


Re: How do I subclass the @property setter method?

2016-05-21 Thread Christopher Reimer



On 5/21/2016 1:52 AM, Dirk Bächle wrote:

Hi Christopher,

On 20.05.2016 20:50, Christopher Reimer wrote:

Greetings,

My chess engine has a Piece class with the following methods that use
the @property decorator to read and write the position value.



slightly off topic: is your chess engine available in a public repo
somewhere? I think I've started to implement something similar (display
of chess boards and wrapping different chess engines), so I'd like to
have a look. ;)


Not at this time. I'll send a post to the list when I make the code 
available. My chess engine doesn't do much beyond displaying a text-only 
board. Since a chess engine presents an unlimited number of programming 
challenges, I'm using it to learn the finer points of Python.


Thank you,

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


Re: for / while else doesn't make sense

2016-05-20 Thread Christopher Reimer

On 5/20/2016 7:31 PM, Chris Angelico wrote:


On Sat, May 21, 2016 at 11:23 AM, Christopher Reimer
 wrote:

On 5/20/2016 3:43 PM, Steven D'Aprano wrote:


But the idea that you should avoid a Python feature while programming in
Python because Javascript doesn't have it, or Ruby, or C, is surely the
height of muddleheaded thinking. You're not programming Javascript, Ruby
or
C, you're programming in Python. The whole point of picking one language
over another is to get access to the tools and features that language
offers. Otherwise you're just wasting your time.


For many years I have resisted specializing in a programming language, as I
can easily write any program in pseudo code and figure out the syntax for a
particular language. Now it does help that most languages have derived from
C and share a common feature set (i.e., string, integer, float, if/else,
while, for, etc.). From my perspective, tacking on an else block to the end
of a for or while loop looks like a bug or a not very well thought out
feature. If I was translating a Python program with for/else or while/else
statements into a different language, those statements will have to be
rewritten anyway.

That's fine, as long as you (a) restrict your programming languages to
those derived from C, and (b) restrict your programming style to the
common subset of them all. Trouble is, that "common subset" is
actually pretty small. Strings behave very differently in C and high
level languages, and for loops are *very* different in different
languages. So you'd be throwing out a large amount of expressiveness,
plus you're completely unable to use languages built on some other
model (eg LISP, or DeScribe Macro Language, or APL).


I don't have a problem with (a) because the majority of the programming 
languages I've been exposed to have derived from the C language. No 
offense to the LISPers, but LISP is a historical curiosity that I might 
blow the dust off and take a look at someday. I'll probably learn 
assembly language before I ever look at LISP. :)


But I disagree with (b) on restricting myself to a common subset of ALL 
the programming languages. Pseudo code allows me to describe a program 
in very general details. Implementing a program in a programming 
language requires getting into very specific details. Of course, there 
are major and minor differences from language to language. If an oddball 
feature gets the job done, I'll use that. Or maybe not. If I'm uncertain 
about something, I'll keep going back and forth until I'm satisfied one 
way or another.


The else block tacked on to for and while loops in Python seems very 
oddball-ish to me. I've always strive to follow best practice whenever 
possible. The one book I've read -- and so far, the only book on that 
feature -- recommends not using it. Based on my previous experience, I 
don't disagree with that author's opinion. If I have a compelling reason 
to use it, I'll use it. Or I'll simplify it to use helper functions.


If I wanted to write portable code, I would have stayed with... Java. O_o

Thank you,

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


Re: for / while else doesn't make sense

2016-05-20 Thread Christopher Reimer

On 5/20/2016 3:43 PM, Steven D'Aprano wrote:


But the idea that you should avoid a Python feature while programming in
Python because Javascript doesn't have it, or Ruby, or C, is surely the
height of muddleheaded thinking. You're not programming Javascript, Ruby or
C, you're programming in Python. The whole point of picking one language
over another is to get access to the tools and features that language
offers. Otherwise you're just wasting your time.


For many years I have resisted specializing in a programming language, 
as I can easily write any program in pseudo code and figure out the 
syntax for a particular language. Now it does help that most languages 
have derived from C and share a common feature set (i.e., string, 
integer, float, if/else, while, for, etc.). From my perspective, tacking 
on an else block to the end of a for or while loop looks like a bug or a 
not very well thought out feature. If I was translating a Python program 
with for/else or while/else statements into a different language, those 
statements will have to be rewritten anyway.


Thank you,

Chris R.


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


Re: for / while else doesn't make sense

2016-05-20 Thread Christopher Reimer

On 5/20/2016 8:59 AM, Zachary Ware wrote:


On Fri, May 20, 2016 at 3:09 AM, Erik  wrote:

On 20/05/16 00:51, Gregory Ewing wrote:

It's not so bad with "else" because you need to look back
to find out what condition the "else" refers to anyway.


With my tongue only slightly in my cheek, if it was desirable to
"fix"/clarify this syntax then I would suggest adding some optional
(existing) trailing keywords to 'else' in this context that spells it out:

for item in seq:
 if foo(item):
 break
else if not break:
 nomatch()

With tongue firmly cheeked, you can always use the special `:#` operator:

for item in seq:
if foo(item):
break
else:# if no break:
nomatch()

This has the benefit that you can use whatever syntax you like after
the `:#`, and use it in any version of Python you want.


According to "Effective Python: 59 Specific Ways to Write Better Python" 
by Brett Slatkin, Item 12 recommends against using the else block after 
for and while loops (see page 25): "Avoid using else blocks after loops 
because their behavior isn't intuitive and can be confusing."


Until I read the book, I wasn't aware of this feature (or bug). Doesn't 
seem like a feature I would use since it's not commonly found in other 
programming languages. As the author demonstrates in his book, I would 
probably write a helper function instead.


Item 13 does recommend using the else block for try/except/else/finally 
in exception handling. :)


Thank you,

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


Re: How do I subclass the @property setter method?

2016-05-20 Thread Christopher Reimer

On 5/20/2016 11:50 AM, Christopher Reimer wrote:


This code does work, blows up the unit test, and keeps PyCharm happy.

@property
def position(self):
return super().position

@position.setter
def position(self, position):
pass

Re-declaring @property and calling super seems redundant.  Not sure if 
I found a bug with the PyCharm hint feature or I'm not subclassing the 
@property setter correctly. Which is it?


Never mind. This is a known bug for PyCharm IDE.

https://youtrack.jetbrains.com/issue/PY-12803

I sent a separate email to technical support to inquire if this bug and 
similar bugs will ever get fixed. This issue was initially reported 
three years ago. Not sure if I should post my own bug report.


Thank you,

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


How do I subclass the @property setter method?

2016-05-20 Thread Christopher Reimer

Greetings,

My chess engine has a Piece class with the following methods that use 
the @property decorator to read and write the position value.


@property
def position(self):
return self._position

@position.setter
def position(self, position):
if self._first_move:
self._first_move = False
self._position = position

Blank is a subclass of the Piece class that represents an empty space on 
the board and  is a placeholder in the Board class _state dict. Since 
Blank is a placeholder and not a playable game piece, I want to make 
@position.setter non-operational (i.e, make no changes to the position 
value).


@Piece.position.setter
def position(self, position):
pass

This code works and the corresponding unit test blows up because I 
haven't changed it yet, but the PyCharm IDE complains that the 
Blank.position signature doesn't match the Piece.position signature. 
Never mind that I copy and paste the identical declaration from the 
Piece class.


This code does work, blows up the unit test, and keeps PyCharm happy.

@property
def position(self):
return super().position

@position.setter
def position(self, position):
pass

Re-declaring @property and calling super seems redundant.  Not sure if I 
found a bug with the PyCharm hint feature or I'm not subclassing the 
@property setter correctly. Which is it?


Thank you,

Chris R.

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


Re: Python PygLatin

2016-05-08 Thread Christopher Reimer

On 5/8/2016 10:53 AM, alister wrote:

On Mon, 09 May 2016 03:12:14 +1000, Steven D'Aprano wrote:


On Sun, 8 May 2016 08:21 pm, Cai Gengyang wrote:


If one looks at the Forbes List, you will see that there are 4
programmers amongst the top ten richest people in the world (Bill
Gates, Mark Zuckerberg, Larry Ellison and Jeff Bezos) , a very large
percentage. Science and Technology is in a sense the most egalitarian
field in the world, because it involves using your brains and
creativity. You don't need to have a father who is a director at
Goldman Sachs or a mother who is the admissions officer at Harvard to
succeed in this line.

Bill Gates III's father was a prominent lawyer, his mother was on the
board of directors for First Interstate BancSystem and United Way, and
one of his grandfathers was a national bank president. Gates himself
went to Harvard.

Zuckerberg's paternal grandparents were successful middle class,
described as  being the first on the block to own a colour TV. (This was
back in the days when colour TVs were an expensive toy that few could
afford.) His parents were also very successful professionals: a dentist
and a psychiatrist. And he too went to Harvard. Despite the jeans and
tee-shirts Zuckerberg is known for wearing, he's firmly from the
professional/upper class.

Bezos comes from a family of land-holders from Texas. His grandfather
was regional director of the U.S. Atomic Energy Commission, and was
financially successful enough to retire at an early age. He didn't go to
Harvard, but he did go to Princeton.

Ellison is the son of an unwed mother who gave him up for adoption by
her aunt and uncle, comfortably middle-class. That makes him the closest
out of the group as a "regular guy".

And at least 2 of the above reached their position using business
practices that could be described as less than 100% honorable & above
board.


What do you expect from people who haven't graduated from Harvard? :P

Thank you,

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


Re: Python is an Equal Opportunity Programming Language

2016-05-08 Thread Christopher Reimer

On 5/8/2016 9:27 AM, Steven D'Aprano wrote:

On Sun, 8 May 2016 08:22 pm, beliav...@aol.com wrote:


There are
far more female than male teachers. I don't attribute it to anti-male
suppression but to greater female interest in working with children.

Of course there is suppression of male teachers, particularly but not only
for very young children.


A college instructor encouraged me to become a teacher,  especially as 
boys from single mom families needed a daily role model. I looked into 
it and took some preparatory childhood classes. When the local 
university had a presentation for their teacher program, I went, saw how 
sausage got made, and ran like hell.


Thank you,

Chris R.

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


Re: Python is an Equal Opportunity Programming Language

2016-05-08 Thread Christopher Reimer

On 5/8/2016 8:09 AM, Rustom Mody wrote:

See:
https://www.washingtonpost.com/news/rampage/wp/2016/05/07/ivy-league-economist-interrogated-for-doing-math-on-american-airlines-flight/

Closing line: "In America today, the only thing more terrifying than foreigners 
is...math."


Wonder how close to terrorists pythonists are


I wonder how many Americans are aware that they use Hindu-Arabic 
numerals in daily transactions?


https://en.wikipedia.org/wiki/Hindu%E2%80%93Arabic_numeral_system

Thank you,

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


Re: Python is an Equal Opportunity Programming Language

2016-05-08 Thread Christopher Reimer

On 5/7/2016 11:58 PM, Marko Rauhamaa wrote:

Chris Angelico :


So the question is: Do we care about country equality or individual
equality? You can't have both.

That's why there's been a long-standing initiative to split California
into multiple states:

   https://en.wikipedia.org/wiki/Six_Californias>

Each state gets two senate seats, and California, being the most
populous state, suffers.


The Six Californias is a proposal to divide up the 54 electoral votes 
that California has in presidential elections, which is a solidly blue 
state for the Democrats. Half the population lives in the Los Angeles, 
San Francisco and Sacramento regions. Put these three regions into 
separate states, the other three regions will become solidly red states 
for the Republicans and tilt the presidential elections in their favor. 
The proposal is a solution for the underlying problem that the 
California Republican Party has more in common with the endangered 
spotted owl than one-tenth of the US population. It's easier to redraw 
the lines than compete for votes.


Thank you,

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


Re: Pylint prefers list comprehension over filter...

2016-05-08 Thread Christopher Reimer

On 5/8/2016 5:02 AM, Steven D'Aprano wrote:

On Sun, 8 May 2016 08:01 am, Christopher Reimer wrote:


On 5/7/2016 2:22 PM, Chris Angelico wrote:



Also, be sure you read this part of PEP 8:



https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds

Recruiters and hiring managers *are* hobgoblins with with little minds.
And definitely not PEP8-complaint. :)


Do you think that recruiters and hiring managers read your code at all, let
alone that they read it will an eye to PEP 8 compliance?


I meant more than a few technical professionals who got pushed out of 
the job to become recruiters. They tend to ask about everything on the 
resume to poke holes where they can. Each time I tightened the wording 
of my resume whenever they exposed something. If I posted a GitHub link 
on my resume, they *would* check it out. If they know Python, they 
*would* run it.


As for PEP 8 compliance, it was a joke (see the smiley). Laugh, it was 
funny.



No recruiter[1] will do this. No recruiter will even know what PEP 8 is.
They're looking for technical buzzwords ("ten years experience with
Django"), they aren't qualified to judge whether your Django code is good,
bad or indifferent. That's up to the client.


When I used to apply to Linux system admin jobs, the recruiters would 
have a checklist box for the "Red Hat GUI Thing" as an absolute 
requirement. My Linux work experience was exclusively remote command 
line. On the rare occasions that I have used the Linux GUI, I always 
used what got installed as the default GUI for Fedora or Mint.


The first time I said I didn't know what the "Red Hat GUI Thing" was and 
explained that I was fast learner, the recruiter hung up on me. I tried 
to argue with other recruiters that I knew the command line equivalent 
for the GUI. No dice. Some recruiters even accused me of making up 
techno-babble. They all hung up on me. After a dozen phone calls like 
that (all for positions at different companies), I generally stopped 
applying to Linux jobs.


This year I built an inexpensive PC to run Linux and installed the 
current Red Hat Linux. Guess what? The "Red Hat GUI Thing" wasn't 
installed. In fact, the GUI was Gnome by default. According to my 
coworkers, Red Hat started phasing out their own branded GUI several 
years ago. I guess the recruiters haven't gotten the memo yet, as I had 
a phone call about the "Red Hat GUI Thing" last year.



A hiring manager with a technical background might, once you are in
consideration for the job. More likely they will delegate any judgement to
a technical manager, or programmer, who may or may not be a hobgoblin with
a little mind.


Every hiring manager I've ever interviewed with had a technical 
background. The only exception was when the final interview was with the 
marketing director at hardware company. I declined to take the job. If 
you know your Dilbert, it's bad luck when a hardware company is run by 
the marketing department. I wasn't surprised that the company filed 
bankruptcy a few years later.


Thank you,

Chris R.

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


Re: Pylint prefers list comprehension over filter...

2016-05-07 Thread Christopher Reimer

On 5/7/2016 6:40 PM, Terry Reedy wrote:

On 5/7/2016 3:17 PM, Christopher Reimer wrote:


For my purposes, I'm using the list comprehension over filter to keep
pylint happy.


How sad.  The pylint developers arrogantly take it on themselves to
revise Python, against the wishes of Guido and the other core
developers, and you and feel obligated to follow them.

They should at least add a disclaimer "Using the default options, pylint
checks that your code complies with the pylint-approved subset of Python."


I wasn't aware that I was picking sides in a religious war by altering 
one line of code. O_o


Thank you,

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


Re: Pylint prefers list comprehension over filter...

2016-05-07 Thread Christopher Reimer

On 5/7/2016 1:31 PM, Marko Rauhamaa wrote:

Christopher Reimer :

Never know when an asshat hiring manager would reject my resume out of
hand because my code fell short with pylint.

Remember that it's not only the company checking you out but also you
checking the company out.

Would you want to work for an asshat hiring manager?

Of course, you might not have the luxury of being picky.


Most asshat managers I've dealt with often say to me, "Here's a mole 
hole, go fix it." I look at the mole hole (little problem), look at the 
mountain (big problem) in the distant, and jump over the mole hole to 
start climbing the mountain. After I reduce the mountain to a mole hole, 
the asshat manager gets promoted and I'm looking for a job again.


Thank you,

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


Re: Pylint prefers list comprehension over filter...

2016-05-07 Thread Christopher Reimer

On 5/7/2016 2:22 PM, Chris Angelico wrote:

On Sun, May 8, 2016 at 5:17 AM, Christopher Reimer
 wrote:
Since the code I'm working on is resume fodder (i.e., "Yes, I code in 
Python! Check out my chess engine code on GitHub!"), I want it to be 
as Pythonic and PEP8-compliant as possible. That includes scoring 
10/10 with pylint. Never know when an asshat hiring manager would 
reject my resume out of hand because my code fell short with pylint. 
For my purposes, I'm using the list comprehension over filter to keep 
pylint happy. 

Wrong thinking. Make it Pythonic - but don't concern yourself with
pylint's final score. Read pylint's output and learn from it, but
don't treat a 10/10 score as the ultimate in ratings, because it just
isn't.

I agree with that in principle. But...

Also, be sure you read this part of PEP 8:

https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds
Recruiters and hiring managers *are* hobgoblins with with little minds. 
And definitely not PEP8-complaint. :)


When I was out of work for two years (2009-10), underemployed for six 
months (working 20 hours per month), and filed for Chapter Seven 
bankruptcy in 2011, I  only had 20 job interviews during that time. That 
was a learning experience. I did everything possible to present myself 
and my resume as perfectly as possible. When I had another bout of 
unemployment that lasted eight months (2013-14), I had 60 job interviews 
and three job offers to pick from at the end. Of course, that was for IT 
support contracts. Maybe programming jobs will have fewer hobgoblins.


Thank you,

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


Re: python chess engines

2016-05-07 Thread Christopher Reimer

On 5/3/2016 10:13 PM, DFS wrote:

Wanted to start a new thread, rather than use the 'motivated' thread.

Can you play your game at the console?


Nope. Only displays the board on the console. An early version had the 
forward movement for pawns implemented.


The way I think about a chess engine is it doesn't even display a 
board.  It accepts a move as input, records the move, analyzes the 
positions after the move, and returns the next move.


My code has display and engine as separate classes with a main loop 
coordinating things between the two. The main loop requests the board 
state (dict) from the engine class and passes that to show board on the 
display class.



Here's the UCI protocol.
http://download.shredderchess.com/div/uci.zip


Very interesting. Something to add to my research notes. I'll muddle 
through with my code and let it grow organically for now.  If I decide 
to write a chess engine that implements the UCI protocol, I'll start 
over with a clean slate.


Thank you,

Chris R.

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


Re: pylint woes

2016-05-07 Thread Christopher Reimer

On 5/7/2016 12:52 PM, Ray Cote wrote:


I’m impressed with 10/10.
My approach is to ensure flake8 (a combination of pyflakes and pep8
checking) does not report any warnings and then run pyLint as a final
check.


I just installed pyflakes and ran it against my 10/10 files. It's not 
complaining about anything. So I ran it against my unit tests that I'm 
still writing, haven't cleaned up and checked against pylint. I got 
dinged for using a star import on a file with a common variables, which 
was an easy fix.


Thank you,

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


Re: Pylint prefers list comprehension over filter...

2016-05-07 Thread Christopher Reimer

On 5/5/2016 6:37 PM, Stephen Hansen wrote:

On Thu, May 5, 2016, at 06:26 PM, Christopher Reimer wrote:

Which is one is correct (Pythonic)? Or does it matter?

First, pylint is somewhat opinionated, and its default options shouldn't
be taken as gospel. There's no correct: filter is fine.


Since the code I'm working on is resume fodder (i.e., "Yes, I code in 
Python! Check out my chess engine code on GitHub!"), I want it to be as 
Pythonic and PEP8-compliant as possible. That includes scoring 10/10 
with pylint. Never know when an asshat hiring manager would reject my 
resume out of hand because my code fell short with pylint.


For my purposes, I'm using the list comprehension over filter to keep 
pylint happy.


Thank you,

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


Re: pylint woes

2016-05-07 Thread Christopher Reimer

On 5/7/2016 12:23 PM, Stephen Hansen wrote:

On Sat, May 7, 2016, at 11:52 AM, Christopher Reimer wrote:

You can do better.  You should strive for 10/10 whenever possible,
figure out why you fall short and ask for help on the parts that don't
make sense.

I think this is giving far too much weight to pylint's opinion on what
is "good" or "bad" programming habits.


I forgot to add the warning, "Use pylint with a dash of salt on a lemon 
slice and a shot of tequila." :)


Thank you,

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


Re: Pylint prefers list comprehension over filter...

2016-05-07 Thread Christopher Reimer

On 5/5/2016 7:57 PM, Stephen Hansen wrote:

On Thu, May 5, 2016, at 07:46 PM, Dan Sommers wrote:

On Thu, 05 May 2016 18:37:11 -0700, Stephen Hansen wrote:


 ''.join(x for x in string if x.isupper())
The difference is, both filter and your list comprehension *build a
list* which is not needed, and wasteful. The above skips building a
list, instead returning a generator ...

filter used to build a list, but now it doesn't (where "used to" means
Python 2.7 and "now" means Python 3.5; I'm too lazy to track down the
exact point(s) at which it changed):

Oh, didn't know that. Then again the OP was converting the output of
filter *into* a list, which wasted a list either way.


My line of code was something I copied off the Internet and modified it 
until it did I exactly what I wanted it to do. That means that the many 
Python 2 code examples available on the Internet are using a redundant 
list operation with Python 3. Isn't that a "smell" that pylint should 
pick up on?


Thank you,

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


Re: pylint woes

2016-05-07 Thread Christopher Reimer

On 5/7/2016 9:51 AM, DFS wrote:
Has anyone ever in history gotten 10/10 from pylint for a non-trivial 
program?


I routinely get 10/10 for my code. While pylint isn't perfect and 
idiosyncratic at times, it's a useful tool to help break bad programming 
habits. Since I came from a Java background, I had to unlearn everything 
from Java before I could write Pythonic code. It might help to use an 
IDE that offers PEP8-compliant code suggestions (I use PyCharm IDE).



That's about as good as it's gonna get!


You can do better.  You should strive for 10/10 whenever possible, 
figure out why you fall short and ask for help on the parts that don't 
make sense.


pylint says "Consider using enumerate instead of iterating with range 
and len"


the offending code is:
for j in range(len(list1)):
  do something with list1[j], list2[j], list3[j], etc.


This code is reeking with bad habits to be broken. Assigning a throwaway 
variable to walk the index is unnecessary when Python can do it for you 
behind the scenes. As Chris A. pointed out in his post, you should use 
zip() to walk through the values of each list at the same time.


Thank you,

Chris R.

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


Pylint prefers list comprehension over filter...

2016-05-05 Thread Christopher Reimer

Greetings,

Below is the code that I mentioned in an earlier thread.

string = "Whiskey Tango Foxtrot"
''.join(list(filter(str.isupper, string)))

'WTF'

That works fine and dandy. Except Pylint doesn't like it. According to 
this link, list comprehensions have replaced filters and the Pylint 
warning can be disabled.


http://stackoverflow.com/questions/3569134/why-doesnt-pylint-like-built-in-functions

Here's the replacement code using list comprehension:

''.join([x for x in string if x.isupper()])

Which is one is correct (Pythonic)? Or does it matter?

Thank you,

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


Re: How to become more motivated to learn Python

2016-05-03 Thread Christopher Reimer

On 5/3/2016 8:00 PM, DFS wrote:

How far along are you in your engine development?


I can display a text-based chess board on the console (looks better with 
a mono font).



 8   BR BN BB BQ BK BB BN BR

 7   BP BP BP BP BP BP BP BP

 6   __ __ __ __ __ __ __ __

 5   __ __ __ __ __ __ __ __

 4   __ __ __ __ __ __ __ __

 3   __ __ __ __ __ __ __ __

 2   WP WP WP WP WP WP WP WP

 1   WR WN WB WQ WK WB WN WR

 A  B  C  D  E  F  G  H


With feedback from this list, I had to break a lot of bad Java habits to 
make the code more Pythonic. Right now I'm going back and forth between 
writing documentation and unit tests. Once I finalized the code in its 
current state, I'll post it up on GitHub under the MIT license. Future 
updates will have a fuller console interface and moves for individual 
pieces implemented.


Thank you,

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


Re: How to become more motivated to learn Python

2016-05-03 Thread Christopher Reimer

On 5/3/2016 4:20 AM, Cai Gengyang wrote:

So I have completed up to CodeAcademy's Python Unit 2 , now moving on to Unit3 
: Conditionals and Control Flow.

But I feel my motivation wavering , at times I get stuck and frustrated when 
trying to learn a new programming language ?

This might not be a technical question per say, but it is a Python programming 
related one. How do you motivate a person (either yourself or your child) to 
become more interested in programming and stick with it ? Is determination in 
learning (especially in a tough field like software) partly genetic ?

Related , This is a very well written essay on determination by Paul Graham 
http://www.paulgraham.com/determination.html

Gengyang


I started out translating old BASIC games into Python. These are the 
same BASIC games that I tried to program into my Commodore 64 without 
much success when I was much younger. Many of these BASIC games are a 
good introduction to classical programming problems like rolling dice 
and playing cards.


http://www.atariarchives.org/basicgames/

When I realized that I wasn't learning enough about the Python language 
from translating BASIC games, I started coding a chess engine. If you 
ever look at the academic literature for chess programming from the last 
50+ years, you can spend a lifetime solving the programming challenges 
from implementing the game of kings.


Thank you,

Chris R.


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


Re: Not x.islower() has different output than x.isupper() in list output...

2016-04-30 Thread Christopher Reimer

On 4/30/2016 10:11 AM, Stephen Hansen wrote:
You're thinking of the whole "string", but you're operating on 
single-character substrings, and when " ".islower() is run, its false. 
Because the two-pronged test, a) if all cased characters are lowercase 
and b) there is at least one cased character. b) is failing. Ergo, 
you're getting the underscores.


I see where the problem lies in my thinking. I went looking for a single 
line solution for the whole string. If I had constructed a for loop and 
tried to reduce it to a single line, I *may* have understood the 
relationship between the different parts. Or maybe not. Blaming the 
documentation is a lot easier. ;)


Thank you,

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


Re: Not x.islower() has different output than x.isupper() in list output...

2016-04-30 Thread Christopher Reimer

On 4/29/2016 11:43 PM, Stephen Hansen wrote:
The official documentation is accurate. 


That may be true on a technical level. But the identically worded text 
in the documentation implies otherwise. Maybe I'm nitpicking this. Even 
if I submitted a bug to request a clearer explanation in the 
documentation, I doubt it would get change. The programmer still has an 
obligation to test the code to make sure that it works as expected, 
which was what I did that until I found the concise statement that 
worked exactly as I wanted it to.


Thank you,

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


Re: Not x.islower() has different output than x.isupper() in list output...

2016-04-29 Thread Christopher Reimer

On 4/29/2016 6:29 PM, Stephen Hansen wrote:
If isupper/islower were perfect opposites of each-other, there'd be no 
need for both. But since characters can be upper, lower, or *neither*, 
you run into this situation.


Based upon the official documentation, I was expecting perfect opposites.

str.islower(): "Return true if all cased characters [4] in the string 
are lowercase and there is at least one cased character, false otherwise."


https://docs.python.org/3/library/stdtypes.html?highlight=islower#str.islower

str.isupper(): "Return true if all cased characters [4] in the string 
are uppercase and there is at least one cased character, false otherwise."


https://docs.python.org/3/library/stdtypes.html?highlight=isupper#str.isupper

Here's the footnote that may or not be relevant to this discussion: "[4] 
Cased characters are those with general category property being one of 
“Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, 
titlecase)."


A bug in the docs?

Thank you,

Chris R.


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


Not x.islower() has different output than x.isupper() in list output...

2016-04-29 Thread Christopher Reimer

Greetings,

I was playing around with a piece of code to remove lowercase letters 
and leave behind uppercase letters from a string when I got unexpected 
results.


string = 'Whiskey Tango Foxtrot'

list(filter((lambda x: not x.islower()), string))

['W', ' ', 'T', ' ', 'F']

Note the space characters in the list.

list(filter((lambda x: x.isupper()), string))

['W', 'T', 'F']

Note that there are no space characters in the list.

Shouldn't the results between 'not x.islower()' and 'x.isupper()' be 
identical?


The final form of this code is this:

list(filter(str.isupper, string))

['W', 'T', 'F']

Thank you,

Chris R.


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


  1   2   3   4   5   6   >