Re: [Tutor] Python isn't working with Apache (Windows)

2017-08-01 Thread Peter Otten
Christopher McGrath wrote:

> I am trying to run a simple python web script in a browser with apache. I
> have apache installed and running perfectly. I installed Ruby and Perl

> I had Python 3.6 installed before and tried to test with these

> I also tried with #!Q:\LifeForce\Python36-32\python.exe. This one works
> worked from Window Command, but didn’t work from web browser like PERL and
> RUBY. 

> I am trying to run directly from Apache htdoc dir. Not from cgi dir. I
> think something is wrong with the shebang line. This is the error output
> in the web browser: Internal Server Error
> The server encountered an internal error or misconfiguration and was
> unable to complete your request. Please contact the server administrator
> at postmaster@localhost to inform them of the time this error occurred,
> and the actions you performed just before this error. More information
> about this error may be available in the server error log. Additionally, a
> 500 Internal Server Error error was encountered while trying to use an
> ErrorDocument to handle the request. This is what is shown in Apache’s
> error log:
> [Mon Jul 31 01:06:54.266478 2017] [cgi:error] [pid 5156:tid 1688] [client
> [98.5.128.152:51723] malformed header from script 'test.py': Bad header:
> [Mon Jul 31 01:06:54.270479 2017] [authz_core:error] [pid 5156:tid 1688]
> [[client 98.5.128.152:51723] AH01630: client denied by server
> [configuration: C:/Apache24

It looks like Apache is already running your script. It just can't make 
sense of its output. The header has to be separated from the data by an 
empty line. In your script that line contains an extra space that you must 
remove.

> I also tried with #!Q:\LifeForce\Python36-32\python.exe. This one works
> worked from Window Command, but didn’t work from web browser like PERL and
> RUBY. 

> Nothing worked. I don’t have any idea anymore. Please help!
> This is the simple code:

#!Q:\LifeForce\Python36-32\python.exe
> print ("Content-type: text/html")
  print ("")
> print ("")
> print ("")
> print ("")
> print ("Hello Python.")
> print ("")

Does it work after this small change?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How sum() works in python

2017-08-01 Thread ramakrishna reddy
Hi All,

I know

> sum([1,2,3]) returns 6.

But sum with [] 'empty list' as second parameter returns as below.

> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]
Can any one please explain this logic ? I searched in google but could not
find the suitable answer.

Thanks in advance.


Thanks,
Ram.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How sum() works in python

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 07:06, ramakrishna reddy wrote:

>> sum([1,2,3]) returns 6.
> 
> But sum with [] 'empty list' as second parameter returns as below.
> 
>> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]

An interesting question, I wasn't aware that you could
add lists with sum.

However, the results seem clear enough. Let's start with the help()
description:
#
Help on built-in function sum in module builtins:

sum(...)
sum(iterable[, start]) -> value

Return the sum of an iterable of numbers (NOT strings) plus
the value of parameter 'start' (which defaults to 0).
When the iterable is empty, return start.
#

And lets see how it behaves with integers first:
>>> sum([1,2,3])   # use start default of 0
6
>>> sum([1,2,3],0) # use explicit start=0
6
>>> sum([1,2,3],1) # use start=1
7
>>> sum([1,2,3],9) # start = 9
15

So in each case we get the sum of the items in the iterable
plus the value of start. sum() is effectively doing

result = start
for n in iterable: result += n
return result

Now lets try using a list of lists:

>>> sum([ [1,2,3],[3,4,5] ])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'list'

We get a type error because the start uses 0 and we can't
add an int and a list. So let's provide a list as the
start value:

>>> sum([ [1,2,3],[3,4,5] ], [])
[1, 2, 3, 3, 4, 5]
>>>

We now get the behaviour you saw because it adds the
three lists together using the same algorithm as above.

And if we use a non-empty start it becomes even more clear:

>>> sum([ [1,2,3],[3,4,5] ], [42])
[42, 1, 2, 3, 3, 4, 5]

We could use tuples instead of lists and get the same result.

What is interesting is that if we try the same thing with
other iterables, such as a string, it doesn't work, even
though string addition is defined. There is obviously
some type checking taking place in there.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How sum() works in python

2017-08-01 Thread Peter Otten
ramakrishna reddy wrote:

> Hi All,
> 
> I know
> 
>> sum([1,2,3]) returns 6.
> 
> But sum with [] 'empty list' as second parameter returns as below.
> 
>> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]
> Can any one please explain this logic ? I searched in google but could not
> find the suitable answer.

sum() adds up whatever you feed it (unless it's a string). A simplified 
pure-python implementation is

>>> def mysum(iterable, start=0):
... result = start
... for value in iterable:
... result = result + value
... return result
... 

When you feed it a list of numbers

>>> mysum([1, 2, 3, 4])
10

it calculates the sum, when the list is empty it returns the start value

>>> mysum([])
0

...whatever it may be:

>>> mysum([], mysum)

>>> sum([], sum)


When you feed it a list of lists it tries to add 0 + first_list and fails

>>> mysum([[1,2], [3,4]])
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in mysum
TypeError: unsupported operand type(s) for +: 'int' and 'list'

However when you provide a list as the start value that list and the lists 
in the `iterable` argument are concatenated

>>> mysum([[1,2], [3,4]], [])
[1, 2, 3, 4]
>>> mysum([[1, "a"], [3, 4.0]], [42])
[42, 1, 'a', 3, 4.0]

...because concatenation is what the + operator is written to do

>>> ["foo", "bar", "baz"] + ["ham", "spam"]
['foo', 'bar', 'baz', 'ham', 'spam']

for Python's built-in lists.

If you feed your own objects to sum() you are completely free how you 
implement + -- if you have it remove files from your hard drive then that's 
what sum() will do when you try to calculate the sum:

>>> class Remove(list):
... def __radd__(self, other):
... for name in self:
... print("Deleting file", name)
... 
>>> sum([Remove(["important.txt", "keepsafe.doc"]), 
Remove(["nice_pic.jpg"])])
Deleting file important.txt
Deleting file keepsafe.doc
Deleting file nice_pic.jpg


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error with sqlalchemy

2017-08-01 Thread rakesh sharma
Hi All


I am getting an error in python. Its a flask app that I am doing

I am getting the error

TypeError: utf_8_decode() argument 1 must be string or buffer, not long

at this point in the code

ship_schedules = ShipSchedule.query.all()

The schema definition is like that I gave below, there is no mismatch between 
the schema and the table definition in the mysql DB.

class ShipSchedule(Base):

__tablename__ = 'ship_schedule'

vessel_imo_no = Column(Integer, primary_key=True, nullable=False)
commodity_product_code = Column(String, nullable=False)
port_port_code = Column(String, nullable=False)
cargo_quantity = Column(String, nullable=False)
activity = Column(String, nullable=False)
date_from = Column(Date, nullable=False)
date_to = Column(Date, nullable=False)


"""
Ship schedule schema
"""


class ShipScheduleSchema(Schema):
vessel_imo_no = fields.Int(dump_only=True)
commodity_product_code = fields.Str()
port_port_code = fields.Str()
cargo_quantity = fields.Int()
activity = fields.Str()
date_from = fields.Date()
date_to = fields.Date()

the mysql table defintion is as follows


[cid:e101f2ac-60ca-426a-8e53-01afd9e9414d]


please help on this, do not know the whats causing the issue.

I dint find any good answers in stackoverflow as all points to schema mismatch

thanks

rakesh
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error with sqlalchemy

2017-08-01 Thread Mats Wichmann
On 08/01/2017 05:13 AM, rakesh sharma wrote:
> Hi All
> 
> 
> I am getting an error in python. Its a flask app that I am doing
> 
> I am getting the error
> 
> TypeError: utf_8_decode() argument 1 must be string or buffer, not long
> 
> at this point in the code
> 
> ship_schedules = ShipSchedule.query.all()
> 
> The schema definition is like that I gave below, there is no mismatch between 
> the schema and the table definition in the mysql DB.
> 
> class ShipSchedule(Base):
> 
> __tablename__ = 'ship_schedule'
> 
> vessel_imo_no = Column(Integer, primary_key=True, nullable=False)
> commodity_product_code = Column(String, nullable=False)
> port_port_code = Column(String, nullable=False)
> cargo_quantity = Column(String, nullable=False)
> activity = Column(String, nullable=False)
> date_from = Column(Date, nullable=False)
> date_to = Column(Date, nullable=False)
> 
> 
> """
> Ship schedule schema
> """
> 
> 
> class ShipScheduleSchema(Schema):
> vessel_imo_no = fields.Int(dump_only=True)
> commodity_product_code = fields.Str()
> port_port_code = fields.Str()
> cargo_quantity = fields.Int()
> activity = fields.Str()
> date_from = fields.Date()
> date_to = fields.Date()
> 
> the mysql table defintion is as follows
> 
> 
> [cid:e101f2ac-60ca-426a-8e53-01afd9e9414d]

this is not viewable, at least not here.

you've potentially got an issue in your cargo quantity definition in the
two classes, possibly take a closer look at that (String vs fields.Int()).

this is a pretty specialized sort of query, probably the sqlalchemy
community would be more expert in this stuff (given you said you've
exhausted stackoverflow already). maybe they have knowledge of some
consistency-checking tool that could detect mismatches?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommended Python Compiler

2017-08-01 Thread Abdur-Rahmaan Janhangeer
Yes indeed geany is a nice editor. I used it when i was beginning and even
wrote a post about it, Feel free to check it !

https://abdurrahmaanjanhangeer.wordpress.com/2016/11/02/python-getting-rid-of-identation-errors-quickly-checking-for-errors-and-the-use-of-editors/

On Tue, Aug 1, 2017 at 9:43 AM, Asokan Pichai  wrote:

> For a simple beginners editor -- geany is a great choice.
>
> It can be used with minimal or no configuration/set up; and once
> you know your way around  you can tweak it as much as you want.
>
> It is easily installable on Debian/Ubuntu
>
>
> --
> Asokan Pichai
> *---*
> We will find a way. Or, make one. (Hannibal)
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How sum() works in python

2017-08-01 Thread ramakrishna reddy
nice explanation .. thanks

this cleared my doubt
>>> k = [20]
>>> for i in [[1,2,3],[3,4,5]]:
... k += i
...
>>> k
[20, 1, 2, 3, 3, 4, 5]

On Tue, Aug 1, 2017 at 1:35 AM, Alan Gauld via Tutor 
wrote:

> On 01/08/17 07:06, ramakrishna reddy wrote:
>
> >> sum([1,2,3]) returns 6.
> >
> > But sum with [] 'empty list' as second parameter returns as below.
> >
> >> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]
>
> An interesting question, I wasn't aware that you could
> add lists with sum.
>
> However, the results seem clear enough. Let's start with the help()
> description:
> #
> Help on built-in function sum in module builtins:
>
> sum(...)
> sum(iterable[, start]) -> value
>
> Return the sum of an iterable of numbers (NOT strings) plus
> the value of parameter 'start' (which defaults to 0).
> When the iterable is empty, return start.
> #
>
> And lets see how it behaves with integers first:
> >>> sum([1,2,3])   # use start default of 0
> 6
> >>> sum([1,2,3],0) # use explicit start=0
> 6
> >>> sum([1,2,3],1) # use start=1
> 7
> >>> sum([1,2,3],9) # start = 9
> 15
>
> So in each case we get the sum of the items in the iterable
> plus the value of start. sum() is effectively doing
>
> result = start
> for n in iterable: result += n
> return result
>
> Now lets try using a list of lists:
>
> >>> sum([ [1,2,3],[3,4,5] ])
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: unsupported operand type(s) for +: 'int' and 'list'
>
> We get a type error because the start uses 0 and we can't
> add an int and a list. So let's provide a list as the
> start value:
>
> >>> sum([ [1,2,3],[3,4,5] ], [])
> [1, 2, 3, 3, 4, 5]
> >>>
>
> We now get the behaviour you saw because it adds the
> three lists together using the same algorithm as above.
>
> And if we use a non-empty start it becomes even more clear:
>
> >>> sum([ [1,2,3],[3,4,5] ], [42])
> [42, 1, 2, 3, 3, 4, 5]
>
> We could use tuples instead of lists and get the same result.
>
> What is interesting is that if we try the same thing with
> other iterables, such as a string, it doesn't work, even
> though string addition is defined. There is obviously
> some type checking taking place in there.
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How sum() works in python

2017-08-01 Thread Abdur-Rahmaan Janhangeer
i guess it adds / sort of concatenates the list

On Tue, Aug 1, 2017 at 10:06 AM, ramakrishna reddy 
wrote:

> Hi All,
>
> I know
>
> > sum([1,2,3]) returns 6.
>
> But sum with [] 'empty list' as second parameter returns as below.
>
> > sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]
> Can any one please explain this logic ? I searched in google but could not
> find the suitable answer.
>
> Thanks in advance.
>
>
> Thanks,
> Ram.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error with sqlalchemy

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 12:13, rakesh sharma wrote:

> I am getting the error
> 
> TypeError: utf_8_decode() argument 1 must be string or buffer, not long

That's not too helpful out of context, can you show us more
of the error trace? Can you show us the method that generates
it? Do you have any indication about which field is generating
the error?

> at this point in the code
> 
> ship_schedules = ShipSchedule.query.all()

One line out of context doesn't really help.
I'm assuming query is a class attribute in
the inherited Base class? Do you have to create
any overridden methods/attribute values to
make it work for your subclass?

I can't comment on the schemas because I don't know MySql
or Flask's ORM well enough to understand what may be happening.
But a bit more detail on the actual code triggering the
error and the error message itself would certainly not hurt.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Thomas Güttler

I have a friend who is a talented shell script writer. He is a linux guru since
several years.

He asked me if "if __name__=='main':" is state of the art if you want
to translate a shell script to python.

I started to stutter and did not know how to reply.

I use Python since several years and I use console_script in entry_points of 
setup.py.

I am very unsure if this is the right way if you want to teach a new comers the 
joy of python.

In the current context we want to translate a bunch of shell scripts to python 
scripts.

What do you think?

Regards,
  Thomas Güttler


--
Thomas Guettler http://www.thomas-guettler.de/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Zachary Ware
On Tue, Aug 1, 2017 at 9:54 AM, Thomas Güttler
 wrote:
> I have a friend who is a talented shell script writer. He is a linux guru
> since
> several years.
>
> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.
>
> I started to stutter and did not know how to reply.

The ~~correct~~ pedantic answer is "No, it's `if __name__ == '__main__':`" :)

> I use Python since several years and I use console_script in entry_points of
> setup.py.
>
> I am very unsure if this is the right way if you want to teach a new comers
> the joy of python.
>
> In the current context we want to translate a bunch of shell scripts to
> python scripts.
>
> What do you think?

It depends on whether you're packaging them up as real Python packages
(sdist, wheel, etc.) to be installed in site-packages or similar, or
if they're just going to be standalone scripts (single file with a
shebang, possibly not even a `.py` extension).  If the former, go for
the entry points.  If the latter, go for `if __name__ == '__main__':`.
And there's no real reason not to do both in the former case anyway;
it's very convenient to not have to install your script somehow to be
able to run it.

-- 
Zach
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Chris Warrick
On 1 August 2017 at 16:54, Thomas Güttler  wrote:
> I have a friend who is a talented shell script writer. He is a linux guru
> since
> several years.
>
> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.
>
> I started to stutter and did not know how to reply.
>
> I use Python since several years and I use console_script in entry_points of
> setup.py.
>
> I am very unsure if this is the right way if you want to teach a new comers
> the joy of python.
>
> In the current context we want to translate a bunch of shell scripts to
> python scripts.
>
> What do you think?
>
> Regards,
>   Thomas Güttler
>
>
> --
> Thomas Guettler http://www.thomas-guettler.de/
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Do both. If you’re making a package, create a __main__.py file as well
so your package is usable with `python -m somepackage`. On the other
hand, if you’re making things more akin to shell scripts, using just
entry_points makes stuff harder, because you need to install the code
(and write a setup.py), as opposed to just putting the script
somewhere in $PATH.

-- 
Chris Warrick 
PGP: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Alan Gauld via Tutor
On 01/08/17 15:54, Thomas Güttler wrote:

> He asked me if "if __name__=='main':" is state of the art if you want
> to translate a shell script to python.

It all depends what you plan to do with the script.
If you literally just want to translate a shell script such
that it will always be executed directly then you don't
even need an 'if name' clause, just hard code the script.

But if you plan in writing some functions that could be
reused by importing the script as a module then you really
should use 'if main'...

And if you intend to use your script only as a module
you should still use 'if name'... but this time call a
test function that runs some regression tests and/or
demo code.

But if you want to write a distributable package that
users can install into their Python infrastructure then
you should *additionally* create setup scripts with
entry points etc.

> you want to teach a new comers the joy of python.

For a newcomer I'd ignore packaging for now and focus
on the benefits of 'if name' over hard coding. One of the
great things about Python is how insanely easy it is to
create a file that can act as both a module and
executable. That can be crazy complex in some other
languages by comparison.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Daemons

2017-08-01 Thread Daniel Bosah
I'm following an online tutorial about threading. This is the code I've
used so far:

import socket
import threading
from queue import Queue



print_lock = threading.Lock()

target = 'pythonprogramming.net'

def portscan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
   con = s.connect((target,port)) # con for connect
   with print_lock: # if sucessful run with statement
  print 'port', port, 'is open'
   con.close() # closes connection
except:
   pass #if it doesn't work pass the method

def threader():
while True:
worker = q.get()
portscan(worker)
q.task_done
q = Queue()
for x in range(30):
t = threading.Thread(target = threader() #creates a thread, gets
workers from q, set them to work on portscanning
t.daemon() = True # want it to be a daemon
t.start()
#jobs = ports
for worker in range(1,101): # port zero invalid port
q.put(worker) # puts worker to work
q.join() #waits till thread terminiates


I don't know what a Daemon is, and I also don't know how to use it in
Python 2.7. Apparently its built in Python 3, but  I don't know how to use
it in Python 2.7. Any help would be appreciated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Daemons

2017-08-01 Thread Steven D'Aprano
Hi Daniel,

My responses below.

On Tue, Aug 01, 2017 at 02:48:19PM -0400, Daniel Bosah wrote:
> I'm following an online tutorial about threading. This is the code I've
> used so far:

Can you give us a link to the tutorial?

[...]
> def portscan(port):
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> try:
>con = s.connect((target,port)) # con for connect
>with print_lock: # if sucessful run with statement
>   print 'port', port, 'is open'
>con.close() # closes connection
> except:
>pass #if it doesn't work pass the method

I'm very concerned about that bare "except" line. I'm not absolutely 
saying that it is wrong, but in general bare excepts are a terrible 
idea.

https://realpython.com/blog/python/the-most-diabolical-python-antipattern/


> def threader():
> while True:
> worker = q.get()
> portscan(worker)
> q.task_done
> q = Queue()
> for x in range(30):
> t = threading.Thread(target = threader() #creates a thread, gets
> workers from q, set them to work on portscanning
> t.daemon() = True # want it to be a daemon
> t.start()
> #jobs = ports
> for worker in range(1,101): # port zero invalid port
> q.put(worker) # puts worker to work
> q.join() #waits till thread terminiates
> 
> 
> I don't know what a Daemon is, 

https://en.wikipedia.org/wiki/Daemon_(computing)




> and I also don't know how to use it in
> Python 2.7. Apparently its built in Python 3, but  I don't know how to use
> it in Python 2.7. Any help would be appreciated.

What happens when you try?



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How sum() works in python

2017-08-01 Thread Steven D'Aprano
On Mon, Jul 31, 2017 at 11:06:18PM -0700, ramakrishna reddy wrote:

> > sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5]

[] + [1,2,3] + [3,4,5]

returns [1, 2, 3, 3, 4, 5].


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Daemons

2017-08-01 Thread Ben Finney
Daniel Bosah  writes:

> I'm following an online tutorial about threading.

Can you point to it so we can understand your specific situation?

> I don't know what a Daemon is

The package ‘python-daemon’ is a library to build your program as a
daemon https://pypi.org/project/python-daemon/>.

The referenced PEP http://www.python.org/dev/peps/pep-3143>
describes what a daemon process is, and how the library provides what
you need to implement a daemon process.

> and I also don't know how to use it in Python 2.7. Apparently its
> built in Python 3, but I don't know how to use it in Python 2.7.

If you are learning Python, you should not use Python 2 unless there is
no other option. Python 2 is on the way out – it will stop receiving all
support after 2020, and is already far behind Python 3.

There are, of course, tutorials for Python 3 and threading. For example
https://www.tutorialspoint.com/python3/python_multithreading.htm>.

> Any help would be appreciated.

I hope that helps.

-- 
 \“The supreme vice is shallowness.” —Oscar Wilde, _De |
  `\  Profundis_, 1897 |
_o__)  |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread boB Stepp
I had typed help(pow) in the interpreter and got:


py3: help(pow)
Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.


A quick scan of some of my Python books does not turn up the use of
"/" as a function argument.  I have a nagging feeling I've read about
this somewhere previously, but I cannot bring it to mind, and I have
yet to stumble on a search that brings up an answer (Yet.).

TIA!
-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Steven D'Aprano
On Tue, Aug 01, 2017 at 04:54:40PM +0200, Thomas Güttler wrote:

[...]
> I use Python since several years and I use console_script in entry_points 
> of setup.py.

What's console_script in entry_points of setup.py?

In particular, what does that have to do with writing an executable 
script?

setup.py is used for packaging Python code, so it can be distributed and 
installed easily.


> I am very unsure if this is the right way if you want to teach a new comers 
> the joy of python.

I think if you are teaching newcomers about packaging and setup.py, they 
will probably decide that Python is too complicated and hard to use.

For beginners, the best way to write a script is to just put your code 
in a file with a hashbang line.


#!/usr/local/bin/python3
print("Hello world!")



chmod the file to executable, and the script is ready.


For slightly more advanced use, move the script's executable code into a 
function, and test whether we're being imported or run as a script 
before calling the function:


#!/usr/local/bin/python3
def main():
print("Hello world!")

if __name__ = '__main__':
main()



This is considered best practice because it allows you to import the 
script for testing without the main() function automatically running.

When Python imports your script, the special variable __name__ will be 
set to the name of the script. When Python executes the script, __name__ 
will be set to the literal string '__main__'.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread Ben Finney
boB Stepp  writes:

> A quick scan of some of my Python books does not turn up the use of
> "/" as a function argument.

The appearance of this in Python's documentation and dfunction signature
descriptions, without a clear description of what it means, is
troubling.

The best I can find is this informational draft PEP
https://www.python.org/dev/peps/pep-0457/>, which *proposes* it as
syntax for some future Python.

-- 
 \  “The process by which banks create money is so simple that the |
  `\ mind is repelled.” —John Kenneth Galbraith, _Money: Whence It |
_o__)   Came, Where It Went_, 1975 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread Steven D'Aprano
On Tue, Aug 01, 2017 at 08:06:58PM -0500, boB Stepp wrote:

> pow(x, y, z=None, /)
> Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

It means that the arguments are positional-only, the names "x", "y" and 
"z" are for documentation purposes only. You cannot write:

pow(x=2, y=3)

but only

pow(2, 3)


> A quick scan of some of my Python books does not turn up the use of
> "/" as a function argument.

Its quite new. Up until recently, the documentation didn't distinguish 
between function parameters which can take optional keywords and those 
that can't.


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Ben Finney
Steven D'Aprano  writes:

> On Tue, Aug 01, 2017 at 04:54:40PM +0200, Thomas Güttler wrote:
>
> [...]
> > I use Python since several years and I use console_script in
> > entry_points of setup.py.
>
> What's console_script in entry_points of setup.py?

It is an advanced feature in Setuptools, that allows defining a function
in the code base as the entry point for external use.

The “console_scripts” entry points tell Setuptools to, at installation
time, create a wrapper script that invokes that function as a
command-line program.


https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation>

> I think if you are teaching newcomers about packaging and setup.py,
> they will probably decide that Python is too complicated and hard to
> use.

Also, if you are teaching packaging and you introduce Setuptools
entry_points, they will probably decide that Setuptools is too
complicated and hard to use.

So I agree with Steven that teaching *newcomers to Python* how to use
Setuptools entry points is far too advanced level.

> For slightly more advanced use, move the script's executable code into
> a function, and test whether we're being imported or run as a script
> before calling the function:
>
>
> #!/usr/local/bin/python3
> def main():
> print("Hello world!")
>
> if __name__ = '__main__':
> main()

That's the best, I agree. Teach them early on to put all functionality
into functions, and (since the OP informs us these are accustomed to
writing command-line programs) the ‘if __name__ == '__main__'’ idiom
will be easy enough.

They should definitely learn it from you, along with the admonition to
*always* keep that block as small as possible.

Better than learning the idiom independently later on, and cramming half
their program into that block :-/

-- 
 \“But it is permissible to make a judgment after you have |
  `\examined the evidence. In some circles it is even encouraged.” |
_o__)—Carl Sagan, _The Burden of Skepticism_, 1987 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread Ben Finney
Steven D'Aprano  writes:

> Its quite new. Up until recently, the documentation didn't distinguish
> between function parameters which can take optional keywords and those
> that can't.

Where does the documentation describe this distinction? How is the
reader, coming across a link to documentation for a function, expected
to know what that symbol means in that context?

I am dismayed that the documentation has gone from describing function
signatures in Python syntax, to describing function signatures that
don't have the expected effect in Python code.

Python 3.6.2 (default, Jul 17 2017, 16:44:45)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(lorem, /, ipsum):
  File "", line 1
def foo(lorem, /, ipsum):
   ^
SyntaxError: invalid syntax

-- 
 \  “Ignorance more frequently begets confidence than does |
  `\   knowledge.” —Charles Darwin, _The Descent of Man_, 1871 |
_o__)  |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread boB Stepp
On Tue, Aug 1, 2017 at 8:25 PM, Ben Finney  wrote:
> Steven D'Aprano  writes:
>
>> Its quite new. Up until recently, the documentation didn't distinguish
>> between function parameters which can take optional keywords and those
>> that can't.
>
> Where does the documentation describe this distinction? How is the
> reader, coming across a link to documentation for a function, expected
> to know what that symbol means in that context?

I also would like to know where this is documented.  The PEP Ben
linked to in his first response (PEP 457) is what I had looked at some
time in the past, but could not bring it to mind.  I obviously failed
the "expected to know ..." test, and I don't count myself a raw
beginner in Python anymore.  I imagine many would find the "/"
puzzling, perhaps even more experienced Python programmers?

> I am dismayed that the documentation has gone from describing function
> signatures in Python syntax, to describing function signatures that
> don't have the expected effect in Python code.
>
> Python 3.6.2 (default, Jul 17 2017, 16:44:45)
> [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def foo(lorem, /, ipsum):
>   File "", line 1
> def foo(lorem, /, ipsum):
>^
> SyntaxError: invalid syntax

I gather from this example that "/" is *not* a syntactical element,
but is instead meant to augment natural English explanation.

Anyway, thanks very much Steve and Ben!

-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is meaning of "/" in "pow(x, y, z=None, /)"?

2017-08-01 Thread Steven D'Aprano
On Wed, Aug 02, 2017 at 11:25:34AM +1000, Ben Finney wrote:
> Steven D'Aprano  writes:
> 
> > Its quite new. Up until recently, the documentation didn't distinguish
> > between function parameters which can take optional keywords and those
> > that can't.
> 
> Where does the documentation describe this distinction? How is the
> reader, coming across a link to documentation for a function, expected
> to know what that symbol means in that context?

I don't know if it is already documented somewhere. I would have 
expected it to be listed in the Glossary under "parameter":

https://docs.python.org/3/glossary.html#term-parameter

but it isn't, even though positional-only parameters are listed. So 
that's a documentation bug.

But in general, there are certain conventions which the reader is just 
expected to know as background knowledge. Such as "->" meaning the 
return result, and [...] used for optional arguments:

Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object


That's from Python 3.5. But to prove this isn't a new issue, here's the 
start of the output of help(range) from Python 2.4:

Help on built-in function range in module __builtin__:

range(...)
range([start,] stop[, step]) -> list of integers

As far as I know, the [...] convention for optional arguments is not 
documented anywhere.


> I am dismayed that the documentation has gone from describing function
> signatures in Python syntax, to describing function signatures that
> don't have the expected effect in Python code.

That's not new. If a naive user writes:

range(1, 10[, 2])

they will get a SyntaxError. For that matter, if a naive user writes:

range(stop)

they will probably get a NameError. A certain amount of domain knowledge 
has to be assumed.

"/" as a parameter is currently reserved for future use, and doesn't 
work in Python functions created with def or lambda. But it can be added 
to the signature for functions written in C.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if __name__=='main' vs entry points: What to teach new comers?

2017-08-01 Thread Steven D'Aprano
On Wed, Aug 02, 2017 at 11:22:00AM +1000, Ben Finney wrote:
> Steven D'Aprano  writes:
> 
> > On Tue, Aug 01, 2017 at 04:54:40PM +0200, Thomas Güttler wrote:
> >
> > [...]
> > > I use Python since several years and I use console_script in
> > > entry_points of setup.py.
> >
> > What's console_script in entry_points of setup.py?
> 
> It is an advanced feature in Setuptools, that allows defining a function
> in the code base as the entry point for external use.
> 
> The “console_scripts” entry points tell Setuptools to, at installation
> time, create a wrapper script that invokes that function as a
> command-line program.
> 
> 
> https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation>

Thanks.

Now that I have learned that, I shall do my best to forget it :-)



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Daemons

2017-08-01 Thread Steven D'Aprano
On Tue, Aug 01, 2017 at 09:05:02PM -0400, dbosah wrote:
> Also here's the link to the tutorial
> https://youtu.be/WrtebUkUssc

That is clearly marked as "Python 3 Programming Tutorial". Why are you 
using Python 2? When you have a problem, you won't know if the problem 
is with your code, or a difference between Python 2 and 3. You're just 
making a rod for your own back by using Python 2.7 with a 3 tutorial.

Save yourself a lot of heartache and either stick to Python 2 tutorials 
or upgrade to Python 3.

-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Daemons

2017-08-01 Thread Steven D'Aprano
On Tue, Aug 01, 2017 at 09:03:30PM -0400, dbosah wrote:

> It usually says that it's an error.

Sorry, my crystal ball is at the shop being repaired and I don't know 
what "an error" means or how to fix it.

Please COPY AND PASTE the full text of the error, starting with the 
line "Traceback" and ending with the error message. Don't summarise it, 
or re-type it from memory.

The Python interpreter provides a lot of useful debugging information in 
these tracebacks. If you ignore it, and just say "An error occurred", it 
is impossible to tell what the error is and why it happened. Your code 
has over 20 lines in it. Assuming a minimum of ten things could go wrong 
with each line, that's 200 possible errors. At minimum.

It is a waste of my time, and confusing for you, to try to guess which 
of those is the error, when you have the information right there in 
front of you.

If you post the actual Traceback, we can help. If you don't, we can't.

> And I'm still confused by the definition of a Daemon. Is there another 
> resource you know that I can look at to break it down even further?

Have you tried googling for "daemon"?

In summary, and Ben will correct me if I'm wrong, a daemon is a computer 
program that runs as a background task. If you come from Windows, think 
of your anti-virus scanner which scans every file when you double-click 
on it, before the file runs. That will probably be a daemon, or the 
closest equivalent.


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Daemons

2017-08-01 Thread Ben Finney
Steven D'Aprano  writes:

> On Tue, Aug 01, 2017 at 09:03:30PM -0400, dbosah wrote:

(I am not seeing your replies in this forum, dbosah. Please address your
replies to the mailing list – not to an individual – if you want the
discussion to continue.)

> > And I'm still confused by the definition of a Daemon.

The term is intended to distinguish a daemon from a typical process.

What understanding do you already have of a typical process on the
operating system? Does the term “process” mean anything? How about
“terminal”?

If you don't have a solid understanding of that, the definition is
unlikely to help because it's making distinctions below the level you're
used to thinking about.

Did the Wikipedia article help?

> In summary, and Ben will correct me if I'm wrong, a daemon is a
> computer program that runs as a background task.

That's not wrong, but “background task” is vague. I don't know what to
assume about dbosah's understanding of processes to know how to help.

I'd say: what characterises a daemon process is that it has no
controlling terminal (it is “detached” from the terminal that initiated
it).

-- 
 \  “As soon as we abandon our own reason, and are content to rely |
  `\   upon authority, there is no end to our troubles.” —Bertrand |
_o__)Russell, _Unpopular Essays_, 1950 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor