[Tutor] introspection

2015-04-20 Thread Alex Kleider
Does python provide the introspective ability to retrieve the name to 
which an object is bound?


For example:
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.

a = 69
print("Identifier <{}> is bound to {}.".format(a.__name__, a))

Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute '__name__'





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


Re: [Tutor] introspection

2015-04-20 Thread Alex Kleider

On 2015-04-20 09:15, Joel Goldstick wrote:
On Mon, Apr 20, 2015 at 11:24 AM, Alex Kleider  
wrote:
Does python provide the introspective ability to retrieve the name to 
which

an object is bound?

For example:
$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.


a = 69
print("Identifier <{}> is bound to {}.".format(a.__name__, a))


Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute '__name__'



An object can be bound to multiple names.  Within a namespace you can
use locals to see names, then compare various names like so:



a = 3
b = 6
c = a
locals()

{'a': 3, 'c': 3, 'b': 6, '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__':
None}

a is b

False

a is c

True


Showing my desired use case might make my question more understandable:
def debug(var_name):
if args["--debug"]:
print("Identifier <{}> is bound to: {}"
.format(var_name.__name__, repr(var_name)))
I don't think the built in locals() can help me.
Thanks all the same.
Alex


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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Alex Kleider

On 2015-04-20 09:21, Alan Gauld wrote:

On 20/04/15 08:44, Jim Mooney wrote:

I can't seem to get my head around this 'simple' book example of
binary-to-decimal conversion, which goes from left to right:

B = '11011101'
I = 0
while B:
 I = I * 2 + int(B[0])
 B = B[1:]

...

Both methods work but I just can't see how the first one does.


The key is that the result gets multiplied by 2 each time
so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.


Shouldn't that be 2**(N-1)?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] introspection

2015-04-20 Thread Alex Kleider

On 2015-04-20 13:24, Ben Finney wrote:

Alex Kleider  writes:


Does python provide the introspective ability to retrieve the name to
which an object is bound?


Objects aren't bound to names. So, no.

The binding from a reference (a name is a reference) to objects is
one-way.

See this excellent presentation from PyCon US 2015 by Ned Batchelder
https://www.youtube.com/watch?v=_AEJHKGk9ns>.


But my code knows the name. The code is provided the name; I want the 
code to tell me that name.

..but it seems unable to do so.
;-(

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


Re: [Tutor] introspection

2015-04-21 Thread Alex Kleider

On 2015-04-20 22:21, Danny Yoo wrote:

What's supposed to happen in this situation?


##
class Person(object):
def __init__(self): pass

j = Person()
john = j
jack = j
##

What single name should we get back from the single Person object
here?  "j", "john", or "jack"?


I was hoping that it would be possible to create a function
that would do the following:

def my_name(some_object):
  return some_object.__name__

so, using what you entered above..

my_name(j)

'j'

my_name(john)

'john'

my_name(jack)

'jack'

But I see what I think you and others have been trying to explain to me: 
that the expression some_object.__name__, if it existed, would indeed be 
schizophrenic since it would be an attribute of the object, not the 
name(s) to which  it is bound.


Thanks all for your replies.
ak
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] introspection

2015-04-21 Thread Alex Kleider

On 2015-04-21 16:48, Cameron Simpson wrote:


But it would not be schizophrenic to write a function that returned a
name arbitrarily, by inspecting locals(). It depends whether you only
need a name, or if you need "the" name.


In my use case there'd probably be only one name for the given object so
I believe you've given me my next exercise!



Write yourself a "find_name_from_locals(local_map, value)" function
that reports. That will (a) get you a partial answer and (b) cement in
your mind what is possible and why. Easy and useful!


I'll get working on that!




Cheers,
Cameron Simpson 

Technique will get you through times of no strength a lot better than
strength will get you through times of no technique.- the 
Nealomatic

Wonderful quote by the way!

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


Re: [Tutor] introspection

2015-04-21 Thread Alex Kleider

On 2015-04-21 16:38, Ben Finney wrote:


That hope is understandable.


Your "understanding" is appreciated.


It is also easy to be confused 


So true, but with the help of "Python Tutors" things are being 
rectified!


about why such a feature doesn't exist;


So why not arbitrary objects?




The answer is that functions, classes, and modules are all *defined*,
and (normally) have exactly one canonical name established at 
definition

time.

Arbitrary objects are merely *instantiated*, without that definition
step. Quite commonly they are used with no name bound to them; so the
behaviour of most objects does not have ‘__name__’ in the API.

If you would like to make a class that has that attribute on all its
instances, feel free. But you need to figure out how the instance
detects its own name!

class LockeanThing:
""" An object that knows the name by which others refer to it. 
"""


def __init__(self):
self.__name__ = ???


But I see what I think you and others have been trying to explain to
me: that the expression some_object.__name__, if it existed, would
indeed be schizophrenic since it would be an attribute of the object,
not the name(s) to which it is bound.


That's why I prefer to be clear that the binding operation is one-way
only.

A reference (such as a name) is bound to an object, the object is not
bound to the reference — indeed, the object knows nothing about that
relationship.


It's sinking in.  Thank you.
ak
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-22 Thread Alex Kleider

On 2015-04-22 05:40, Ben Finney wrote:

Albert-Jan Roskam  writes:


- Original Message -
> From: Ben Finney 
> You'll need a working implementation first. Put it on BullCodes
> https://bull.codes/> for bonus Python-based free-software
> repository hosting points!

Is bull.codes better than Github or Bitbucket?


Yes, because those are not free software.

http://mako.cc/writing/hill-free_tools.html>

Kallithea (which is what powers BullCodes) is free software, meaning
anyone is free to see how it works and change it and run their own
instance and share changes.

http://kallithea-scm.org/>


There seems to be much documentation on how to set up Kallithea as a 
server,
but I've been unable to find anything resembling a user (i.e. someone 
who

wants to keep a project hosted on bull.code) 'howto' with regard to
bull.code.  Any suggestions?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-22 Thread Alex Kleider

On 2015-04-22 12:22, Ben Finney wrote:

Alex Kleider  writes:


On 2015-04-22 05:40, Ben Finney wrote:
> http://mako.cc/writing/hill-free_tools.html>
>
> Kallithea (which is what powers BullCodes) is free software, meaning
> anyone is free to see how it works and change it and run their own
> instance and share changes.
>
> http://kallithea-scm.org/>

[…] I've been unable to find anything resembling a user (i.e. someone
who wants to keep a project hosted on bull.code) 'howto' with regard
to bull.code. Any suggestions?


I don't think BullCodes has a pointer to it yet, but: Kallithea's
documentation contains a “General Kallithea usage” section
https://docs.kallithea-scm.org/en/latest/usage/general.html>, is
that what you're looking for?


I already looked through that page and indeed perhaps the information is 
there

but not in a way that I can understand.
No where can I find what steps to take to push a git repository that I 
have on my lap top to bullcode.
But perhaps this is the wrong venue since it isn't Python related.  
Sorry.


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


Re: [Tutor] Introductory questions on test-driven development and implementing Git version control.

2015-04-25 Thread Alex Kleider

On 2015-04-25 08:34, boB Stepp wrote:
On Sat, Apr 25, 2015 at 3:21 AM, Alan Gauld  
wrote:

Having looked at this thread and its early responses I think it
would be good to break it up into its two natural parts. TDD
and version control are pretty much separate concepts and
should be on separate threads.

Bob, could you please ask your version control questions again,
taking account of early responses, on a new thread? That way
we can keep the TDD stuff together and the version control
stuff in a separate place.


Done! I do not know if what I did matches your intent, but I hope so!
I stuffed everything relevant to version control into a single email,
trying my best to keep attributions, etc., accurate. It makes for a
long post, but it has everything nicely in place. I just hope Gmail
did not mangle anything!

In retrospect, I wish I had copied and pasted every post so far into
Vim, did my editing there, and re-copy and paste into a new email. I
keep forgetting that text is text...


This might be of interest to you:
https://addons.mozilla.org/en-us/firefox/addon/its-all-text/

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


Re: [Tutor] Questions (and initial responses) on using version control: Why cannot I push my single (master) branch to origin without an error occurring?

2015-04-30 Thread Alex Kleider

On 2015-04-30 20:39, boB Stepp wrote:

I created my remote repository on, say my C-drive, with "git init". I
then copied and pasted a file to that location and put it under
version control with "git add filename.py". Next I went to my E-drive,
which is where I intend to be my working directories. After setting up
a similar directory structure (/Projects/), I typed "git clone
C:/Projects/project_name" and the desired result appeared on E:
E:/Projects/project_name/filename.py. All seemed well with the world!

Now I made some edits to filename.py in my working directory,
added/committed and then attempted to push to the remote repository
and got this:


I would suggest the following work flow to set up two parallel 
repositories:


cd 
git init

git add 
git commit

cd 
git clone 
# the above command brings in a copy of all that was committed in the 
first repo.


Once this is done, I believe your subsequent commits can be pushed 
without the errors.




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


Re: [Tutor] key detection

2015-05-05 Thread Alex Kleider

On 2015-05-05 15:36, Alan Gauld wrote:

On 05/05/15 22:30, Jim Mooney Py3.4.3winXP wrote:

Can python detect a keypress?


The following works for my (on my Ubuntu platform) system
although probably won't be of much use on a Redmond OS.

#!/usr/bin/env python3
# file: 'readchar.py'
"""
Provides readchar()
Implementation of a way to get a single character of input
without waiting for the user to hit .
(OS is Linux, Ubuntu 14.04)
"""

import tty, sys, termios

class ReadChar():
def __enter__(self):
self.fd = sys.stdin.fileno()
self.old_settings = termios.tcgetattr(self.fd)
tty.setraw(sys.stdin.fileno())
return sys.stdin.read(1)
def __exit__(self, type, value, traceback):
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def readchar():
with ReadChar() as rc:
return rc

def testrc():
print\
("Testing ReadChar: enter a character and we'll report what it is.")
while True:
char = readchar()
if ord(char) <= 32:
print("You entered character with ordinal {}, aka {}."
.format(ord(char), repr(char)))
else:
print("You entered character '{}'."
.format(char))
if char in "^C^D":
break

if __name__ == "__main__":
testrc()

To give credit where credit is due: I seem to remember cobbling this 
together
based on something that was discussed on this mailing list quite some 
time ago.

i.e. it's not original work:-)


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


Re: [Tutor] introspection

2015-05-07 Thread Alex Kleider

On 2015-04-21 16:48, Cameron Simpson wrote:


But it would not be schizophrenic to write a function that returned a
name arbitrarily, by inspecting locals(). It depends whether you only
need a name, or if you need "the" name.

Write yourself a "find_name_from_locals(local_map, value)" function
that reports. That will (a) get you a partial answer and (b) cement in
your mind what is possible and why. Easy and useful!

Cheers,
Cameron Simpson 


Well I finally got around to tackling this little challenge and you are 
right:

It was illuminating.

For what it's worth, here's the code that made the light go on:
#!../venv/bin/python3
# -*- coding: utf-8 -*-
# vim: set file encoding=utf-8 :
#
# file: 'getname.py'
"""
Following through on:
Write yourself a "find_name_from_locals(local_map, value)" function that
reports. That will (a) get you a partial answer and (b) cement in your
mind what is possible and why. Easy and useful!
Cheers, Cameron Simpson 
"""
a = 'Alex'
j = 'June'
ssn = 681769931  # Totally ficticious!
# print(locals())
def get_name_1st_version(item):
"""What I naively thought would work."""
for name in locals():
if name == item:
return name

def get_name(localmap, item):
"""As suggested.
Returns 'a' name, not necessarily 'the' name."""
for name in localmap:
if localmap[name] == item:
return name

if __name__ == '__main__':  # code block to run the application
# First attempt:
print(get_name_1st_version(a))
print(get_name_1st_version(j))
print(get_name_1st_version(ssn))
print(get_name_1st_version('Alex'))
print(get_name_1st_version('June'))
print(get_name_1st_version(681769931))

# Second attempt:
localmap = locals()
# Lesson learned: must use localmap created within the namespace
# under scrutiny.
print(get_name(localmap, a))
print(get_name(localmap, j))
print(get_name(localmap, ssn))
print(get_name(localmap, 'Alex'))
print(get_name(localmap, 'June'))
print(get_name(localmap, 681769931))

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


Re: [Tutor] introspection

2015-05-07 Thread Alex Kleider

On 2015-05-07 19:10, Dave Angel wrote:


def get_name(localmap, item):
 """As suggested.
 Returns 'a' name, not necessarily 'the' name."""
 for name in localmap:
 if localmap[name] == item:


This is not likely to be what was intended.  You want
   if localmap[name] is item:
That can identify if one of the names happens to be bound to the SAME
object being examined.  Rather than one that happens to have the same
value.


Correction noted.  Thank you for that.  The distinction is important. 
('==' vs 'is')


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


Re: [Tutor] introspection

2015-05-07 Thread Alex Kleider

On 2015-05-07 20:45, Dave Angel wrote:


You also only showed it working on module globals.  (For code at
top-level, locals() returns the same as globals() )

You could also try it inside functions, where locals() really makes
sense as a name.  And you could try it in a nested function where
there may very well be non-locals (eg. closure items) that aren't
local or global.


You've taken me to new territory:
http://www.shutupandship.com/2012/01/python-closures-explained.html
I wasn't familiar with 'closures' and to be truthful, still am not,
although thanks to you I am at least aware of the idea.


But more interestingly, you could try it on items of a list, or
members of a dictionary, where there's no name at all associated with
the object.


It simply returns None.  I assume that's the point you are making?
(That it has no name, or perhaps more accurately expressed: there is
no name to discover.)

alex

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


Re: [Tutor] split a string inside a list

2015-05-09 Thread Alex Kleider

On 2015-05-08 20:24, Kayla Hiltermann wrote:

hi,

i am trying to make a pythagorean triples checker (a^2 + b^2 = c^2).
the user enters three sides to a triangle and my code determines if it
is a pythagorean triple (aka right triangle) or not. i have the entire
code pretty much done, except i want to account for variability in
user input, like using commas or just spaces. the user input is
initially a string, but is converted to a list once run through
.split() . I would like to split the user input by commas or spaces,
so:
3 4 5
3,4,5
3, 4, 5
all become: [“3", “4", “5"].


Several solutions have been suggested (of which the re.findall approach 
appeals to me the most) but one that hasn't and might be worth 
considering is use of str.maketrans() and s.translate().

https://docs.python.org/2/library/string.html#string.maketrans
https://docs.python.org/2/library/string.html#string.translate

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


Re: [Tutor] Help Learn python - Step by Step

2015-05-09 Thread Alex Kleider



On Sat, May 9, 2015 at 3:23 AM, acolta  wrote:


Hi guys,

I want to start coding in python. My background is Linux/Bash/Perl 
(begginner).
My appreciate if somebody will recommend books/tutorials + exercises 
to practice.


I first cut my Python teeth using
http://www.greenteapress.com/thinkpython/
and would highly recommend it as a starting point.
The only reservation to be made is that it covers Python 2.x (probably 
2.7)

but not Python3

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


[Tutor] reading lines from a list of files

2015-05-11 Thread Alex Kleider

Is there a better (more 'Pythonic') way to do the following?

for f_name in f_names:
with open(f_name, 'r') as f:
for line in f:

As always, thank you, tutors, for all you are doing.

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


Re: [Tutor] reading lines from a list of files

2015-05-12 Thread Alex Kleider

On 2015-05-11 23:48, Peter Otten wrote:

Alex Kleider wrote:


Is there a better (more 'Pythonic') way to do the following?

 for f_name in f_names:
 with open(f_name, 'r') as f:
 for line in f:


There's the fileinput module

<https://docs.python.org/dev/library/fileinput.html#fileinput.input>

but personally I prefer the way you show above.


Then I'll stick with what you prefer and what I know.
It seems silly to import yet another module for the sole
purpose of saving one line of code although the reason
for my inquiry was more to diminish levels of indentation
than number of lines.
Thanks,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading lines from a list of files

2015-05-13 Thread Alex Kleider



On 2015-05-11 23:48, Peter Otten wrote:

Alex Kleider wrote:


Is there a better (more 'Pythonic') way to do the following?

 for f_name in f_names:
 with open(f_name, 'r') as f:
 for line in f:


There's the fileinput module

<https://docs.python.org/dev/library/fileinput.html#fileinput.input>

but personally I prefer the way you show above.


As a follow up question:
The following seems to work-

for f_name in list_of_file_names:
for line in open(f_name, 'r'):
process(line)

but should I be worried that the file doesn't get explicitly closed?

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


Re: [Tutor] reading lines from a list of files

2015-05-14 Thread Alex Kleider

On 2015-05-14 00:15, Laura Creighton wrote:

In a message of Wed, 13 May 2015 22:27:11 -0700, Alex Kleider writes:

As a follow up question:
The following seems to work-

for f_name in list_of_file_names:
for line in open(f_name, 'r'):
process(line)

but should I be worried that the file doesn't get explicitly closed?

Alex


If you use the with statement you will guarantee that the file closes
as soon as you are done with it. It will also handle exceptions nicely 
for you.

See: https://www.python.org/dev/peps/pep-0343/

In practice, Cpython's ref counting semantics means that running out
of file descriptors doesn't happen (unless you put that code in a
loop that gets called a whole lot).  But the gc used by a Python
version is not part of the language specification, but is a
language implementation detail.  If you are writing for PyPy or
Jython you will need to use the with statement or close your files
explicitly, so the gc knows you are done with them.  Relying on
'the last reference to them went away' to close your file won't
work if the gc isn't counting references.

See: http://pypy.org/compat.html
or for more detail:
http://pypy.readthedocs.org/en/latest/cpython_differences.html#differences-related-to-garbage-collection-strategies

Laura


Thanks, Laura, for your analysis.  I'll happily include the one extra 
line and
let 'with' do its magic rather than depend on implementation details (or 
 worry

about their shortcomings:-)

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


Re: [Tutor] reading lines from a list of files

2015-05-14 Thread Alex Kleider

On 2015-05-14 00:01, Alan Gauld wrote:

On 14/05/15 06:27, Alex Kleider wrote:


The following seems to work-

 for f_name in list_of_file_names:
 for line in open(f_name, 'r'):
 process(line)

but should I be worried that the file doesn't get explicitly closed?


If you are only ever reading from the file then no, I'd not worry
too much. But in the general case, where you might be making
changes then yes, you should worry.

It will work 99% of the time but if things go wrong there's always
a chance that a file has not been closed yet and your changes have
not been written to the file. But if you are not changing the file
it doesn't matter too much.

The only other consideration is that some OS might put a lock
on the file even if it's only read access, so in those cases
closing will release the lock sooner. But I don't think any of
the popular OS do that any more.


Thank you, Alan; I hadn't appreciated the important difference in risk
with write vs read.  It's clear that 'best practice' would be to use
'with' so as to 'cover all bases.'
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading lines from a list of files

2015-05-14 Thread Alex Kleider

On 2015-05-13 23:24, Danny Yoo wrote:

As a follow up question:
The following seems to work-

for f_name in list_of_file_names:
for line in open(f_name, 'r'):
process(line)

but should I be worried that the file doesn't get explicitly closed?



It depends on context.  Personally, I'd write it with the 'with' to
make it very clear that the loop will manage its resource.  That being
said, it sounds like there might be concerned about the nesting.
We're nesting three or four levels deep, at the very least!

I'd agree with that.  Because of this, it might be worthwile to
consider refactoring the processing of the file in a separate
function, something like this:

###
def processFile(f):
for line in f:
...

for f_name in list_of_file_names:
 with open(f_name, 'r') as f:
 processFile(f)
###

The primary reason is to reduce the nesting.  But there's also a
potential side benefit: processFile() has a better chance of being
unit-testable, since we can pass in instances of other file-like
objects, such as io.StringIO(), to spot-check the behavior of the
process.


Thanks, Danny.  This is particularly germane since the issue has come up 
in the
midst of my first attempt to do test driven development.  I'll try 
refactoring per

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


Re: [Tutor] string delimiters

2015-06-03 Thread Alex Kleider

On 2015-06-03 12:53, Alan Gauld wrote:
...

If this is really about parsing dates and times have
you looked at the datetime module and its parsing/formatting
functions (ie strptime/strftime)?


I asssume strftime gets its name from 'string from time.'
What about strptime? How did that get its name?

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


Re: [Tutor] string delimiters

2015-06-03 Thread Alex Kleider

On 2015-06-03 15:13, Mark Lawrence wrote:


'f' for format, 'p' for parse, having originally come from plain old
C.  More here
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior


So I was wrong about the 'f' as well as having no clue about the 'p'!
Thank you very much for clearing that up for me.
cheers,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python 3.4 documentation

2015-06-14 Thread Alex Kleider
I'm using python 3.4 on an ubuntu 14.4 LTS OS and frequently find myself 
'off line'.
I'd like to download the standard library documentation to have at hand 
on my hard drive.

I tried
prompt> wget -r https://docs.python.org/3/library/index.html
but links appear to be broken.
I'd be grateful for advice as to the way to do this.
Thanks in advance.
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python 3.4 documentation

2015-06-14 Thread Alex Kleider

On 2015-06-14 12:36, Hilton Fernandes wrote:

Hello, Alex !

I believe that maybe in the page
https://docs.python.org/3/download.html


Thank you Hilton, Laura and Peter for pointing me in the right 
direction.

Being 'off line' will no longer be such a hardship.


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


Re: [Tutor] python 3.4 documentation

2015-06-14 Thread Alex Kleider

On 2015-06-14 17:13, Laura Creighton wrote:

In a message of Sun, 14 Jun 2015 15:50:38 -0700, Alex Kleider writes:

On 2015-06-14 12:36, Hilton Fernandes wrote:

Hello, Alex !

I believe that maybe in the page
https://docs.python.org/3/download.html


Thank you Hilton, Laura and Peter for pointing me in the right
direction.
Being 'off line' will no longer be such a hardship.


You are most welcome, but I want to go fix this for the next person
who comes along.  Where did you find the bad link?  Or, if you just
assumed that the one you tried would work, what can we do to keep the
next person from assuming the same thing?

Laura


Here's the command I initially used:
prompt>  wget -r https://docs.python.org/3/library/index.html

The directory that resulted seemed to have everything but when I tried 
to use links, none worked.
I have since deleted the above and downloaded (and 'untared') as 
follows:

prompt>  tar -xvjf python-3.4.3-docs-html.tar.bz2
All is now well.

I could repeat the (wget) process and give you more detailed information 
if that would be helpful.

(Let me know.)
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python 3.4 documentation

2015-06-15 Thread Alex Kleider

On 2015-06-14 20:49, Steven D'Aprano wrote:


The Python interactive interpreter comes with a powerful interactive
help system. At the Python prompt, you can enter:

help()

help("keyword")  # e.g. "raise"

help(any_object)


to get help and documentation.



Thank you for this tip.  I sort of was aware of it but had no idea
of how much help was there.  I certainly had no idea that modules
were documented as well:

alex@t61p:~$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.

help('key words')

no Python documentation found for 'key words'


help('keywords')


Here is a list of the Python keywords.  Enter any keyword to get more 
help.


False   def if  raise
Nonedel import  return
Trueelifin  try
and elseis  while
as  except  lambda  with
assert  finally nonlocalyield
break   for not
class   fromor
continueglobal  pass


import csv
help('csv')

...and documentation of the modules appears in the pager!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python and Beautiful soup question

2015-06-21 Thread Alex Kleider

On 2015-06-21 15:55, Mark Lawrence wrote:

On 21/06/2015 21:04, Joshua Valdez wrote:
I'm having trouble making this script work to scrape information from 
a

series of Wikipedia articles.

What I'm trying to do is iterate over a series of wiki URLs and pull 
out

the page links on a wiki portal category (e.g.
https://en.wikipedia.org/wiki/Category:Electronic_design).

I know that all the wiki pages I'm going through have a page links 
section.

However when I try to iterate through them I get this error message:

Traceback (most recent call last):
   File "./wiki_parent.py", line 37, in 
 cleaned = pages.get_text()AttributeError: 'NoneType' object has 
no

attribute 'get_text'


Presumably because this line


 pages = soup.find("div" , { "id" : "mw-pages" })


doesn't find anything, pages is set to None and hence the attribute
error on the next line.  I'm suspicious of { "id" : "mw-pages" } as
it's a Python dict comprehension with one entry of key "id" and value
"mw-pages".


Why do you refer to { "id" : "mw-pages" } as a dict comprehension?
Is that what a simple dict declaration is?

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


Re: [Tutor] Pep 8, about indentation

2015-08-07 Thread Alex Kleider

On Aug 7, 2015 1:18 AM, Cameron Simpson  wrote:
>
> 
> However, when _editing_ I tell vi that when I press TAB it is to insert 
> enough 
> SPACE characters to get to the next 4 column position. 

How do you do that?
I've got vim set up so a CTRL-T while in insert mode does that (and CTRL-D does 
the opposite) but don't know how to make use of the tab key.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pep 8, about indentation

2015-08-07 Thread Alex Kleider

On 2015-08-07 20:56, Cameron Simpson wrote:

On 07Aug2015 12:19, Alex Kleider  wrote:

On Aug 7, 2015 1:18 AM, Cameron Simpson  wrote:
However, when _editing_ I tell vi that when I press TAB it is to 
insert enough

SPACE characters to get to the next 4 column position.


How do you do that?
I've got vim set up so a CTRL-T while in insert mode does that (and 
CTRL-D does the opposite) but don't know how to make use of the tab 
key.


^T and ^D have done that since time immemorial in vi, no special setup
required.  I pretty much never use ^T but I do use ^D to back out an
indent level.

These are my settings relevant to tabs and indenting:

 set autoindent
 set expandtab
 set shiftwidth=2
 set tabstop=4

In order:

 autoindent: start the next line's text on the same indent as this one

 expandtab: write spaces instead of a TAB character

 shiftwidth: how far the < and > shift-text operations move

 tabstop: the multiple used to tabstops - every 4 columns for me


Thanks!

Here is what I've got in my ~/.vimrc file:
set autoindent
set shiftwidth=4
set expandtab
set textwidth=72
set scrolljump=2
set scrolloff=2

I'll add
set tabstop=4




Happy to post my other settings should anyone care.


... and yes, I for one certainly do "care."
I'd very much like to see your other settings.

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


Re: [Tutor] Pep 8, about indentation

2015-08-10 Thread Alex Kleider

On 2015-08-10 08:33, David Rock wrote:


You might want to add softtabstop as well.
  set softtabstop=4

It's very handy for allowing the delete key to go back TAB number of
spaces (ie, deletes those 4 spaces you just inserted).


I got it working but the key needs to be the 'backspace' key, not the 
'delete' key.

Either way, very handy (replacing the need to use CTRL-D.)
Thanks,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2015-08-10 Thread Alex Kleider

On 2015-08-10 11:13, Emile van Sebille wrote:

On 8/10/2015 10:07 AM, Alan Gauld wrote:


PS.
What is SDSU?



San Diego State University I'd guess.

Emile


South Dakota State is the other possibility.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cannot get a label message to display immediately

2015-08-14 Thread Alex Kleider

On 2015-08-14 09:32, Bill Allen wrote:

I am working in Tkinter.   The scenario is that I click a button that
starts a function running.   No problem there.   However, the function 
may

take some time to run and I do not want the user to be worried.   I am
wanting to immediately set a label when the function starts to say 
"Please
Wait".  However, the label does not show up until the function 
completes.

How do I get both actions to happen essentially at the same time, the
writing of the label and the execution of the function?  I have no code 
to
show on this one because I am lost in the weeds, not sure of the 
general

way to go on this.


Thanks,
--Bill Allen


Might it be possible to insert the code that posts the 'label' into the
beginning of the function's code block?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where should unit test files go in a project directory structure and some related questions?

2015-08-16 Thread Alex Kleider

On 2015-08-16 01:28, Alan Gauld wrote:


Here is my default structure

project
- doc   project documents: contracts reqs, designs, test specs etc
- man(*)   user docs
- bin(*)   the master exe or main.py type files
- lib(*)   the shipping libraries
- src  the code
-- lang  folder per language used - sql, python, C, bash, etc
--- lib  modules/packages - subfolder per package
--- test test code - sub-tree under this, depends on test tools.
--- toolstools used but not shipped - db load/reset etc
--- main folder in some languages, a file in others


Alan,
Assuming the above structure and further assuming that your python test 
suite is under test,

how do you arrange to import code that is under main?
I have only been able to figure out how to import code that is at the 
same or lower level in the file structure.
If one's test code was in --- test/test.py, an import of --- main or 
main/mycode.py would have to 'find' the latter by traveling up the tree 
to test and then over to main, or over to main and then down to 
mycode.py.

I've not been able to do that.  Is there a way?
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where should unit test files go in a project directory structure and some related questions?

2015-08-16 Thread Alex Kleider

On 2015-08-16 10:45, Alan Gauld wrote:


Thee are several options.
1) create links from, main to the test files needed
2) alter sys.path so imports can see the test folder
3) alter the PYTHONPATH environment var



I suspect in this case the easiest solution is a link


Thanks Alan.

Creating a link is familiar to me but your answer brings up
another question:
Where/how is the best place/way to set PYTHONPATH?
I've never been clear to me if it's part of the shell (bash)
environment or part of the python interpreter's environment.
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where should unit test files go in a project directory structure and some related questions?

2015-08-16 Thread Alex Kleider

On 2015-08-16 12:45, Laura Creighton wrote:


We have a new mechanism for test discovery in 2.7 and 3.x
https://docs.python.org/3/library/unittest.html
see 26.3.3

It's been backported.
see: https://pypi.python.org/pypi/unittest2

Also, if you are on Python2 and you put your tests in a test 
subdirectory

you need to remember to make an __init__.py file there.

Laura


I've got it working.
Thanks, Laura.

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


Re: [Tutor] pip install in a virtualenv *without* internet?

2015-08-19 Thread Alex Kleider

On 2015-08-18 19:32, Mike C. Fletcher wrote:

To install without going out to the internet, you can use these 
arguments:


pip install --no-index --find-links=/path/to/download/directory 




For this to work, /path/to/download/directory would, I assume, first 
have to be populated.
I further assume that running wget from within that directory might do 
the trick.

Can you suggest the correct parameter(s) that need to be provided?
If anyone happens to know approximately how much file space would be 
required, that would be helpful.

Thanks,
Alex
(using python 3.4, Linux- Ubuntu LTS (14.4))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pip install in a virtualenv *without* internet?

2015-08-19 Thread Alex Kleider

On 2015-08-19 04:28, Albert-Jan Roskam wrote:

Date: Wed, 19 Aug 2015 02:27:41 -0700
From: aklei...@sonic.net
To: tutor@python.org
Subject: Re: [Tutor] pip install in a virtualenv *without* internet?

On 2015-08-18 19:32, Mike C. Fletcher wrote:

> To install without going out to the internet, you can use these
> arguments:
>
> pip install --no-index --find-links=/path/to/download/directory
> 


For this to work, /path/to/download/directory would, I assume, first
have to be populated.
I further assume that running wget from within that directory might do
the trick.



..but, but wget requires an internet connection, which I do not have
(at least not a normal one).
But if you do have internet I think you could simply copy the
URL-with-sha1, then for each package do
wget 

regards,
Albert-Jan



I guess if you 'never' have an internet connection what I'm trying to do 
won't work,
but I'm addressing a different use case:  I have connectivity in some 
environments
but would like to be able to do a pip install at times when there is no 
connectivity.

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


Re: [Tutor] Do not understand why test is running.

2015-08-21 Thread Alex Kleider

On 2015-08-20 23:16, Peter Otten wrote:



Yea, breaking things is an art form ;)




$ python3 -m unittest -h
usage: python3 -m unittest [-h] [-v] [-q] [-f] [-c] [-b] [tests [tests 
...]]



.


For test discovery all test modules must be importable from the top 
level

directory of the project.


How is "top level directory of the project" defined in this context?
Is it as far up as one can travel while passing through directories
containing an __init__.py file?


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


[Tutor] how to unittest cli input

2015-10-10 Thread Alex Kleider

"""
I'm trying to follow a test driven development paradigm (using
unittest) but can't figure out how to test functions that collect
info from the command line such as the following.
"""
# collect.py
def collect_data():
ret = {}
ret['first'] = input("Enter your first name: ")
ret['last'] = input("Enter your last name: ")
ret['phone'] = input("Your mobile phone #: ")
return ret

def main():
print(collect_data())

if __name__ == "__main__":
main()

The following works:
$ python3 collect.py < cli_input

# cli_input
Alex
Kleider
415/868-1920

... but I don't know how to make it a unittest.

Thanks in advance for any suggestions.

Alex

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


Re: [Tutor] how to unittest cli input

2015-10-11 Thread Alex Kleider

On 2015-10-10 18:10, Cameron Simpson wrote:

On 10Oct2015 17:41, Alex Kleider  wrote:

I'm tOn 2015-10-10 18:10, Cameron Simpson wrote:

On 10Oct2015 17:41, Alex Kleider  wrote:

I'm trying to follow a test driven development paradigm (using
unittest) but can't figure out how to test functions that 
collect

info from the command line such as the following.


Aside: I'd say "the standard input" , not "the command line"; to me
the latter connotes to command line arguments fro sys.argv.


Point well taken!   stdin it is.  Ben suggested I should have used the 
term "interactive" which certainly fits well.


Anyway, ...

..

However, you'r eusing input(), which unconditionally uses stdin and
stdout. In that circumstance I'd consider this:

 def collect_data(src=None, out=None):
 if src is None:
 src = sys.stdin
 if out is None:
 out = sys.stdout
 ostdin = sys.stdin
 sys.stdin = src
 ostdout = sys.stdout
 sys.stdout = out
 ret = {}
 ret['first'] = input("Enter your first name: ")
 ... etc ...
 sys.stdout = ostdout
 sys.stdin = ostdin

Note that this is not thread safe because sys.stdin is a global, but
it should work for testing.

Anyway, perhap that gives you some way forward.


Yes indeed, and thank you for your input.
Here's where I'm going with your suggestion:

# collect.py

test_data = 'test_src.txt'

def data_collection_wrapper(collect, source=None):
"""
"""
if source:
ostdin = sys.stdin
ostdout = sys.stdout
src = open(source, 'r')
sys.stdin = src
out = open('/dev/null', 'w')  # Dump the prompts.
sys.stdout = out

ret = collect()

if source:
src.close()
out.close()
sys.stdin = ostdin
sys.stdout = ostdout

return ret


def collect_data():
ret = {}
ret['first'] = input("Enter your first name: ")
ret['last'] = input("Enter your last name: ")
ret['phone'] = input("Your mobile phone #: ")
return ret

def main():
print(collect_data())  # < check that user input works
# then check that can test can be automated >
print(data_collection_wrapper(collect_data,
src=test_data))

if __name__ == "__main__":
main()

Perhaps data_collection_wrapper could be made into a decorator (about
which I am still pretty naive.)

It'll take more studying on my part before I'll be able to implement 
Ben's suggestion.


Alex
ps I was tempted to change the "Subject:" to remove 'cli' and replace it 
with 'interactive' but remember many admonitions to not do that so have 
left it as is.


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


Re: [Tutor] how to unittest cli input

2015-10-12 Thread Alex Kleider

On 2015-10-11 14:52, Cameron Simpson wrote:


Minor remark: I would write "if src is not None:". In principle the
empty string is also "falsey" like None, making your plain "if src:"
slightly unreliable. Be precise!


'precise' is good!

Any comments about when/if to use 'if src != None:' vs 'if src is not 
None:'?

(or 'if src == None:' vs 'if src is None:')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to unittest cli input

2015-10-13 Thread Alex Kleider

On 2015-10-13 12:11, Danny Yoo wrote:



##
def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
return d.get
##


This last line got my attention ("a dict has no such attribute"
but rather "it has a 'get' method")
but then the light went on: you've created a function that
returns a function. So many levels of abstraction!

Thanks for making things fall into place.
cheers,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to unittest cli input

2015-10-14 Thread Alex Kleider

On 2015-10-13 14:44, Alex Kleider wrote:

On 2015-10-13 12:11, Danny Yoo wrote:



##
def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
return d.get
##


This is an example of a 'closure' is it not?
ak
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to unittest cli input

2015-10-14 Thread Alex Kleider

On 2015-10-14 11:29, Danny Yoo wrote:

##
def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
return d.get
##



This is an example of a 'closure' is it not?



Yes, though I try not to use the word "closure" because it's a
technical distinction that isn't really that useful for beginners
because it focuses on the implementation details.  That is, when we
say the word "closure", we're emphasizing the fact that it's a
combination of code and the data that it needs to resolve the code's
free variables.  And for this discussion, all I really cared about was
that we needed something that knows how to be "called".  Anything that
distracts from that point is something I'm actively trying to avoid,
at least at first.


We could try to make the code look clever by doing something like:


make_ask = lambda f, l, p: (lambda key: {'Enter your first name: ' :
f, 'Enter your last name: ' : l, 'Your mobile phone #: ' : p}[key])


But this would be death to the point I was trying to make.  :P


Thank you for 'making the point' and explaining it so well!
ak
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to unittest cli input

2015-10-14 Thread Alex Kleider

On 2015-10-14 12:27, Peter Otten wrote:

Alex Kleider wrote:


On 2015-10-13 14:44, Alex Kleider wrote:

On 2015-10-13 12:11, Danny Yoo wrote:



##
def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
return d.get
##


This is an example of a 'closure' is it not?


It does not make big difference, but I would call the return value 
"bound
method" rather than "closure". For me closure implies access to the 
local

namespace of the enclosing function, e. g.

def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
def get(key):
return d.get(key)
return get

Here d is looked up when get() is invoked. Let's make a modification to
demonstrate that the current binding of d is used:


def make_ask(f, l, p):

... d = {'Enter your first name: ' : f,
...'Enter your last name: ' : l,
...'Your mobile phone #: ' : p}
... def get(key):
... return d.get(key)
... def set_d(new_d):
... nonlocal d
... d = new_d
... return get, set_d
...

get, set_d = make_ask(*"abc")
get("Enter your first name: ")

'a'

class WontTell:

... def get(self, key): return "won't tell"
...

set_d(WontTell())
get("Enter your first name: ")

"won't tell"


Thank you, Peter, for your continued efforts to explain.
It is all getting pretty convoluted for my poor brain!
It took a very long time for me to figure out what the
class WontTell was all about.
I probably should follow Danny Yoo's advice and not concern
myself with this but my curiosity is roused.
ak

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


Re: [Tutor] how to unittest cli input

2015-10-15 Thread Alex Kleider

On 2015-10-14 11:29, Danny Yoo wrote:

##
def make_ask(f, l, p):
d = {'Enter your first name: ' : f,
   'Enter your last name: ' : l,
   'Your mobile phone #: ' : p}
return d.get
##



This is an example of a 'closure' is it not?



Yes, though I try not to use the word "closure" because it's a
technical distinction that isn't really that useful for beginners
because it focuses on the implementation details.  That is, when we
say the word "closure", we're emphasizing the fact that it's a
combination of code and the data that it needs to resolve the code's
free variables.


I've been pondering the above and am wondering why the use of
"...and the data that it needs to resolve the code's free variables."
rather than simply "...and the data needed by the code to do its job."
I think what I'm asking is what exactly is meant by 'free variables'
or put another way, what makes a variable 'free' or otherwise?

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


Re: [Tutor] accessing modules found throughout a package?

2015-10-18 Thread Alex Kleider

On 2015-10-17 19:49, Steven D'Aprano wrote:

which will work from your package's callers, and from within the 
package

itself provided the top level directory can be found within Python's
path. Within the package you can also use relative imports, see the
docs for more detail.


How does one arrange so "the top level directory _can_ be found within 
Python's path."?



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


Re: [Tutor] accessing modules found throughout a package?

2015-10-18 Thread Alex Kleider

On 2015-10-18 08:07, Alex Kleider wrote:

On 2015-10-17 19:49, Steven D'Aprano wrote:

which will work from your package's callers, and from within the 
package

itself provided the top level directory can be found within Python's
path. Within the package you can also use relative imports, see the
docs for more detail.


How does one arrange so "the top level directory _can_ be found within
Python's path."?



Is the answer to include the following at the beginning of each file?

if not 'path/to/top/level/package/directory' in sys.path:
sys.path.append('path/to/top/level/package/directory')


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


Re: [Tutor] accessing modules found throughout a package?

2015-10-18 Thread Alex Kleider

On 2015-10-18 10:26, Alan Gauld wrote:

On 18/10/15 16:33, Alex Kleider wrote:

How does one arrange so "the top level directory _can_ be found 
within

Python's path."?


Is the answer to include the following at the beginning of each file?

if not 'path/to/top/level/package/directory' in sys.path:
 sys.path.append('path/to/top/level/package/directory')


You could, but you can also add it to your PYTHONPATH environment 
variable.


It seems to not exist:
(venv)alex@x301:~/Py/CSV/debk$ echo $PYTHONPATH

Should I add the following to the end of my ~/.bashrc file?
export PYTHONPATH="$PYTHONPATH:/home/alex/Py"

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


Re: [Tutor] accessing modules found throughout a package?

2015-10-19 Thread Alex Kleider

On 2015-10-18 18:01, Steven D'Aprano wrote:

On Sun, Oct 18, 2015 at 08:07:07AM -0700, Alex Kleider wrote:

On 2015-10-17 19:49, Steven D'Aprano wrote:

>which will work from your package's callers, and from within the
>package
>itself provided the top level directory can be found within Python's
>path. Within the package you can also use relative imports, see the
>docs for more detail.

How does one arrange so "the top level directory _can_ be found within
Python's path."?


Thank you, Alan, Martin, Ben and Steve.
I'm a long way from distributing packages!  Rather I'm simply
writing scripts for personal use and would like to do it using
Test Driven Development- hence my wish to be able to reference
modules within my development directory.
I've been able to satisfy my needs by adding
export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/home/alex/Py"
to the end of my ~/.bashrc
although use of a setup.py file is probably the more 'pythonic'
way of doing it.  From my reading so far [1] it's not clear to
me exactly how this works but a bit of experimentation might
rectify that.
Again, thank you.
Alex

[1]
https://docs.python.org/3/distutils/introduction.html#distutils-simple-example


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


Re: [Tutor] Working collaboratively (was: accessing modules found throughout a package?)

2015-10-19 Thread Alex Kleider

On 2015-10-19 12:37, Ben Finney wrote:

Alex Kleider  writes:


I'm a long way from distributing packages!


You can keep working at your own pace, and that's good. But even 
better,

I would strongly recommend that you work with other people early and
frequently.

Programming is fundamentally a process of collaboration and
communication with other human programmers.

The habits you form alone can be eccentric and unhelpful, with no-one 
to
comment on strange habits you may be forming without even noticing 
until

they are too deeply entrenched to easily avoid.

Working frequently with others on the same code base will not only 
flush

out these oddities, but also help you to appreciate the consensus
decisions made in the past by the Python community as a whole.

So, while it's not essential, I would heartily encourage you to pick
some of the PyPI projects you are enjoying, or want to improve, and
contact their maintainers with your offer to fix specific things. Work
with other Python programmers on a common code base, and watch your
skills broaden and improve!


How I wish I could find such collaborator!
Are there any "starter level" PyPi projects the maintainer of which
might consider a novice collaborator?  I would have assumed that
such an animal doesn't exist.

I do appreciate the advice.

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


Re: [Tutor] Working collaboratively

2015-10-19 Thread Alex Kleider

On 2015-10-19 13:08, Emile van Sebille wrote:


This looks like the list of identified issues:
  https://bitbucket.org/pypa/pypi/issues

Browse through and see if anything looks interesting/doable.



On 2015-10-19 13:34, Mark Lawrence wrote:


How about https://mail.python.org/mailman/listinfo/core-mentorship ?


Thank you Emile and Mark for your suggestions.
I fear that both are better suited to someone much more advanced than I!

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


Re: [Tutor] Working collaboratively

2015-10-19 Thread Alex Kleider

On 2015-10-19 15:18, Emile van Sebille wrote:

On 10/19/2015 3:04 PM, Alex Kleider wrote:

On 2015-10-19 13:08, Emile van Sebille wrote:


This looks like the list of identified issues:
  https://bitbucket.org/pypa/pypi/issues

Browse through and see if anything looks interesting/doable.



On 2015-10-19 13:34, Mark Lawrence wrote:


How about https://mail.python.org/mailman/listinfo/core-mentorship ?


Thank you Emile and Mark for your suggestions.
I fear that both are better suited to someone much more advanced than 
I!


You'd think so, but digging into any of the issues shown there and
simply trying to locate where a change may help resolve the issue is
itself a learning experience that'll do more for you taking your first
step then watching from the sidelines.

For example, take a look at http://bugs.python.org/issue25417 -- can
you figure out what file this change may impact?  (Note -- I haven't
looked)

Emile


Inspired by your encouragement (for which I'm grateful,) I had a look:
Here's the content of issue25417:
"""
The output of pydoc for Path.samefile currently reads

pathlib.Path.samefile = samefile(self, other_path)
Return whether `other_file` is the same or not as this file.
(as returned by os.path.samefile(file, other_file)).

It should arguably be something like

pathlib.Path.samefile = samefile(self, other_path)
Return whether `other_path` is the same or not as this file.
(as returned by os.path.samefile(file, other_file)).

or

pathlib.Path.samefile = samefile(self, other_path)
Return whether `other_path` is the same or not as this file.
(as returned by os.path.samefile(str(self), str(other_path))).
"""
The author suggests that the output A should in fact be more along the 
lines of

B or C but to my reading A==B==C!

Am I missing something?

I did look at the source: 
https://hg.python.org/cpython/file/3.5/Lib/pydoc.py
How would one download the source? (i.e. the equivalent of git clone 
...)


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


Re: [Tutor] Working collaboratively

2015-10-20 Thread Alex Kleider

On 2015-10-20 01:02, Alan Gauld wrote:

On 20/10/15 07:33, Alex Kleider wrote:



Look closely at what the return value is called in each case.
And see how it compares to the names in the signature.


OOPS!
Should have run over them with diff _before_ posting rather than after.
Sorry about that.
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Create complex dictionary :p:

2015-10-22 Thread Alex Kleider

On 2015-10-22 14:50, Thomas C. Hicks wrote:

On 10/23/2015 05:19 AM, jarod_v6--- via Tutor wrote:

Hi!!I would like to prepare a dictionary with complex structure:

complex = {name ="value",surname="po",age=poi)
  What is the most pythonic way to build   a dictionary of 
dictionary?thanks for any help!



This doesn't look too complex so I am probably missing something.

The normal dictionary construction would look something like this:

mydict = dict('name'='value', 'surname'='po','age'='poi')

Then you can access any given item in mydict with the get method:

mydict.get('name')

SDG,

tom


alex@x301:~$ python3
Python 3.4.3 (default, Jul 28 2015, 18:24:59)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

mydict = dict('name'='value', 'surname'='po','age'='poi')

  File "", line 1
SyntaxError: keyword can't be an expression




my understanding is that you could have done it in either of the 
following two ways:

1:mydict = dict(name='value', surname='po',age='poi')
2:mydict = {'name': 'value', 'surname': 'po','age': 'poi'}

Also, accessing any given item might be done as follows:
mydict['name']
rather than calling the get method, n'est pas?


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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alex Kleider

On 2015-10-28 08:09, Vusa Moyo wrote:

Hi Guys,

I've written a script to remove vowels from a string/sentence.

the while loop I'm using below is to take care of duplicate vowels 
found in

a sentence, ie

anti_vowel('The cow moos louder than the frog')

It works, but obviously its messy and n00by. Any suggestions on how I 
can

write this code better?



def anti_vowel(text):
vowel = ['a', 'e', 'i', 'o', 'u']
VOWEL = ['A', 'E', 'I', 'O', 'U']
manip = []

for i in text:
manip.append(i)
fufu = 0
#
while fufu < 16:
for x in vowel:
if x in manip:
manip.remove(x)

for y in VOWEL:
if y in manip:
manip.remove(y)

fufu = fufu + 2

strong = ''.join(manip)
return strong



Thanks - Vusa


This struck me as a good place to utilize list comprehension.


VOWELS = 'aeiouAEIOU'

def remove_chars(s, chars2remove=VOWELS):
"""Returns the string s but without any of
the characters found in chars2remove.
If given only one parameter, defaults to removing vowels.
"""
s_as_list = [char for char in s]
without_chars2remove = [
char for char in s_as_list if char not in chars2remove]
#   print(s_as_list)  # for testing
#   print(without_chars2remove)   #ditto
return "".join(without_chars2remove)

if __name__ == "__main__":
print(remove_chars(
'The cow moos louder than the frog'))



There may be some other constructs (the string join method on the empty 
string)

to which you haven't yet been exposed.
Confession: I'm submitting it probably as much to garner comments from 
the

pundits as to help you.
cheers,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alex Kleider

On 2015-10-28 09:37, Peter Otten wrote:

Vusa Moyo wrote:


I've written a script to remove vowels from a string/sentence.

the while loop I'm using below is to take care of duplicate vowels 
found

in a sentence, ie

anti_vowel('The cow moos louder than the frog')

It works, but obviously its messy and n00by. Any suggestions on how I 
can

write this code better?


(I'm assuming Python3)


'The cow moos louder than the frog'.translate(str.maketrans("", "",

"aeiouAEIOU"))
'Th cw ms ldr thn th frg'



I didn't know about the possibility of a third argument.  Thanks, Peter.

from the docs:
"""
static str.maketrans(x[, y[, z]])

This static method returns a translation table usable for 
str.translate().


If there is only one argument, it must be a dictionary mapping 
Unicode ordinals (integers) or characters (strings of length 1) to 
Unicode ordinals, strings (of arbitrary lengths) or None. Character keys 
will then be converted to ordinals.


If there are two arguments, they must be strings of equal length, 
and in the resulting dictionary, each character in x will be mapped to 
the character at the same position in y. If there is a third argument, 
it must be a string, whose characters will be mapped to None in the 
result.

"""

Although not explicitly stated, I assume that if there is a third 
argument, the first 2 will be ignored.

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


[Tutor] interface

2015-12-14 Thread Alex Kleider
So far all my python programming has been done using print for output 
and

(raw)input whenever user input is required.  I'd like to learn how to
provide a graphical interface.  There are several choices with pros and
cons to each but an alternative more general approach might be to use a
web based interface which I believe would make the code less platform
dependent.

I'd be interested in any comments regarding this idea and would be
grateful for any suggestions as to frameworks that might be helpful.
I've been looking at django but finding the learning curve to be steep
and it may not be the best solution.

Of late I've been using Python3; my platform is Ubuntu 14.4.

Thanks in advance for any guidance.

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


Re: [Tutor] interface

2015-12-14 Thread Alex Kleider

Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
The consensus seems to be in favour of tkinter
so I'll head in that direction.
Cheers,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] interface

2015-12-18 Thread Alex Kleider

On 2015-12-16 17:42, boB Stepp wrote:
On Mon, Dec 14, 2015 at 10:08 PM, Alex Kleider  
wrote:

Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
The consensus seems to be in favour of tkinter
so I'll head in that direction.


If you are into books, "Programming Python, 4th ed." by Mark Lutz, has
an extensive section on tkinter (Alan had pointed this out to me, and
I have found Lutz's coverage very helpful).  Plus the book (very
thick!) has lots of other goodies.  Also, the now old book, "Python
and Tkinter Programming" by John E. Grayson is just about Tkinter
(with a capital "T") as it is copyrighted 2000.  Despite this I think
it is still quite useful even if you are working in Python 3 as, as
far as I can tell, t/Tkinter has not changed substantially in how the
coding goes.



I've settled on "Modern Tkinter" by Mark Roseman.
His is the most recently published of the various references recommended
and he makes the point that the "themed" (ttk) component is recent
(and I assume not covered in the other sources.)
I'd prefer a real book but have had to settle for the kindle edition:-)
A pdf version may also be available.


Another issue about which I'd like to hear comments has to do with
how the imports are done.
Roseman indicates that
from tkinter import *
from tkinter import ttk
is the generally accepted way of doing the importing but the first line
uses a syntax that is strongly discouraged so my inclination is to use
import tkinter as tk
from tkinter import ttk
instead.

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


Re: [Tutor] interface

2015-12-18 Thread Alex Kleider

On 2015-12-18 14:13, Mark Lawrence wrote:

On 18/12/2015 18:38, Alex Kleider wrote:



Another issue about which I'd like to hear comments has to do with
how the imports are done.
Roseman indicates that
 from tkinter import *
 from tkinter import ttk
is the generally accepted way of doing the importing but the first 
line

uses a syntax that is strongly discouraged so my inclination is to use
 import tkinter as tk
 from tkinter import ttk
instead.

Comments?



from xyz import * is The Road To Hell.

Sticking with the explicit way of importing modules makes life so much
easier in the long term that there is IMHO nothing to discuss.


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


Re: [Tutor] interface

2015-12-19 Thread Alex Kleider

On 2015-12-18 17:22, Alan Gauld wrote:


FWIW My recent book Python Projects includes coverage of
both ttk and Tix as well as core tkinter. But it's only
designed to be a taster, it's not a complete reference.
It's more about the general approach to putting a UI on
an app than about any specific toolkit.


I have it (the book by Laura Cassell and you!)
The first chapter still has me stumbling! (Super, slots and property() 
were new to me.)
Hadn't yet noticed the Tkinter section- thanks for pointing it out to 
me.






 import tkinter as tk
 from tkinter import ttk


For production code this is better.
And you can swap out Tkinter for Tix by just changing
one line:

import tkinter.tixix as tk   # v3

or

import Tix as tk# v2

So all  the existing tk code carries on working but
you now have access to the extra widgets in Tix too.


First I've heard of Tix!
Much to learn.

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


Re: [Tutor] interface

2015-12-20 Thread Alex Kleider

On 2015-12-20 06:11, Alan Gauld wrote:

On 20/12/15 02:21, Alex Kleider wrote:


First I've heard of Tix!


A potentially useful set of extra widgets on top of Tkinter.
Unfortunately the Tkinter port of the original Tcl/Tk TIX
package is incomplete and only reliable for about half the
extended widgets (thankfully the most common ones such
as scrolledList and a tabbed Notebook etc).

The biggest disappointment is the Grid widget which
theoretically should work but despite many attempts I've
failed to get anything useful. It's on my todo list to spend
some time either fixing it, or documenting how it works,
or both...

But because Tix is a superset of Tkinter I rarely use
raw Tkinter nowadays I usually just start with Tix.


Thanks for the background insight.
How does Ttk (T for 'themed' I assume) fit in? is it used in addition to 
Tix

(as it would be used in addition to tkinter)
or is it an either/or situation?

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


Re: [Tutor] Using python 3 on Ubuntu 14.04

2015-12-23 Thread Alex Kleider

On 2015-12-23 14:58, Jim Byrnes wrote:

I am in the process of moving from unbutu 12.04 to 14.04. I was doing
some testing and got this:

jfb@Jims-1404:~$ cd MyProgs
jfb@Jims-1404:~/MyProgs$ cd passwords
jfb@Jims-1404:~/MyProgs/passwords$ python3 passwords.py
Traceback (most recent call last):
  File "passwords.py", line 8, in 
from PythonCard import  model,clipboard
ImportError: No module named 'PythonCard'

If I simply start it with  python passwords.py  it runs fine. There is
no need to use python 3 on this particular program but if I wanted to
write for python 3 in the future what do I need to do to run programs
with it?

Thanks,  Jim


Jim, make

#!/usr/bin/env python3

the very first line in your myscript.py file
and change it's permissions with the following command:

chmod 775 myscript.py

Then you'll be able to run it simply by entering

./password.py

on the command line.

PS I don't think this will fix your current problem which is
probably the result of importing something that exists with
Python 2 but not 3- specifically PythonCard.

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


[Tutor] method, type?

2016-01-05 Thread Alex Kleider

#!/usr/bin/env python3
# OS: Ubuntu 10.4LTS

# My code:

class JournalLineItem(object):
"""
"""

def __init__(self, account, debit_or_credit, amount):
self.account = account
self.debit_or_credit = debit_or_credit
self.amount = float(amount)

def show(self):
return ("ACNT: {}  ${:0.2f} {}".
format(self.account, self.amount, self.debit_or_credit))

def get_line_item(text):
return JournalLineItem(*text.split())

def test():
print(
JournalLineItem.get_line_item("2435 Dr 25.33").show())

if __name__ == "__main__":
test()

myquestion = """
What kind of a method/function is get_line_item?
From what I've read (and not fully understood)
static methods and class methods must have
@staticmethod and @classmethod on the line above them.
get_line_item works as I wanted but it's clearly not the
usual type of method and I don't know how to categorize it.
It's an instance creator- is there a better term?
Is this 'Pythonic' code?
"""
as_always = """Thanks,

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


Re: [Tutor] method, type?

2016-01-05 Thread Alex Kleider



Hoping this helps rather than confuses,
Cameron Simpson 


It is no more confusing than what I had already read about static and 
class methods.
I guess I was hoping for an easy explanation but such a thing probably 
doesn't exist.

I'll have to slog through the explanation.

Thank you for taking the trouble to help.  It's much appreciated.

Alex


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


Re: [Tutor] method, type?

2016-01-07 Thread Alex Kleider

Thank you to all who contributed to this thread.
It has helped me immensely and I enjoyed some of the spirited 
discussion.


Some of my notes follow (in case corrections are in order:-)

my_notes = """

@staticmethod
def s_method(param_but_no_self_or_cls):
# An ordinary function that resides in the class to associate
# its functionality with the class.
pass

Instance methods expect 'self'.| arranged implicitly when called
Class methods expect 'cls'.| via instance or class.

"factory" methods (typically called '.from_*') can be:
1. a normal function outside the class, or
2. a class method (would allow subclassing.)
"alternative constructor" (what Petter Otten and Steven DAprano
call it,) would be best placed immediately after __init__.
Alan Gauld indicates that as initially written (without
'@staticmethod') "it is not" ?a method/function?
but a 'named constructor' which is not supported by Python, so
it could be a 'class method.'  He recommends making it a factory
function (defined at the module level, outside the class.)
Steven DAprano calls it a Python3 regular function/ a Python2
broken method and mentions the Descriptor protocol and how
'methods' are initially simply functions that are then converted
to methods (bound) as required. In my case it would be an
'unbound' method which works in 3 but not in Python2.

Cameron Simpson indicated that putting @staticmethod above my 'method'
would be OK (although not preferred.)  Present or absent, my method
still functions the same way.
The table provided by Peter Otten (very helpful:)
-
invoked with | @staticmethod  | @classmethod| no decorator
--
class| args unchanged | class as 1st arg | args unchanged
instance | args unchanged | class as 1st arg | inst as 1st arg
---
It suggests that use of the @staticmethod serves to protect one should
the 'method' be called via an instance rather than the class.  Has it
any other effect?

"""

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


Re: [Tutor] Organizing files

2016-01-11 Thread Alex Kleider

On 2016-01-11 04:51, Rene Werner wrote:

Hello list,

right now I am working on a couple of programming-related challenges. 
The
challenges are sorted into problem sets, where each set contains a 
number

of problems.

Because a lot of these problems rely on code that is often the same, I 
have

put these parts into a seperate file, util.py, and I simply do

from util import *

in each solution. I have my solutions organized in different folders, 
one

for each problem set:

set1/prob1.py
set1/prob2.py
set2/prob3.py

and so on. So far, I keep symlinking util.py in each set folder, so 
e.g.
set1/util.py is a symlink to ../util.py. The same goes for set2, set3 
and

so on. This works, but I get the feeling that it is clumsy and could be
done better.

What is the usual way in python do realize this in a way so that I 
don't
have to symlink util.py for every problem set, but still have it 
available?


Thank you very much for your time.
Kind regards

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


I used to do it with symlinks as well but what I do now I believe
is the preferred way.

I have all my Python work under a ~/Py directory (in my /home/alex 
folder)
For each project I create a subfolder there: ~/Py/CurrentProject, or 
~/Py/CP for short.
Under ~/Py/CP you can put all your other code organized in what ever way 
suits you best.
The CP directory and every directory under it should contain an empty 
file called __init__.py.

For example:
~/Py/CP
__init__.py
src
__init__.py
main.py
tests
__init__.py
test.py

test.py can import main.py with the following import statement:
import CP.src.main as main
as long as ~/Py is in your PYTHONPATH environment variable.
This can be set dynamically in your code but I do it by having the 
following in my ~/.bashrc file:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/home/alex/Py"

I'm submitting this not because I am an expert, but because this is the 
way I've learned to do it from postings on this list (for which I would 
like again to express gratitude) and would be interested in hearing if I 
got it right.  So in a sense, it is a question rather than an answer.

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


Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me

2016-01-16 Thread Alex Kleider

On 2016-01-16 16:08, Alan Gauld wrote:

On 16/01/16 23:56, Alan Gauld wrote:

On 16/01/16 22:39, boB Stepp wrote:

So in this model of understanding negative list indexing, should it 
be:


mylist = [ 100, 200, 300, 400, 500 ]
  ^^^^^   ^
  -5   -4   -3   -2   -1  ?

Well, it has to be this; otherwise, the off-by-one error exist.  This
also continues to explain why

mylist.insert(-1, x)

inserts x *before* 500.  But in this model, what should go in the 
place of "?"?


-0



alex@x301:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:33:09)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

mylist = [1, 2, 3, 4, 5]
mylist[0:None]

[1, 2, 3, 4, 5]

mylist[0:-0]

[]

-0

0




It appears that None provides a surrogate for -0 which itself evaluates 
to 0.





I should have added a :-/ to that in case it wasn't obvious...


It wasn't to me; could you please explain what you mean by ":-/" and/or 
where you should have added it?



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


Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me

2016-01-16 Thread Alex Kleider

On 2016-01-16 18:02, Cameron Simpson wrote:

On 16Jan2016 18:43, boB Stepp  wrote:

This led me to try:


mylist[:None]

[100, 200, 300, 400, 500]

So, in effect, None is acting as a place holder for that final
position in slices.  Also, I would never have thought to be able to
use a logical "or" inside an index in Peter's "[:-i or None]".


Yah, like the default value for many missing parameters. When you
don't need an expression after the ":" you can of course write:

 mylist[:]

much like writing a function "def f(x, y=None)"; None is a sentinel
value - specially recognised as nor in the normal domain for that
value.



Can you please clarify the last bit:
"specially recognised as nor in the normal domain for that value."

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


Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me

2016-01-17 Thread Alex Kleider


On 2016-01-17 02:18, Cameron Simpson wrote:

On 16Jan2016 22:42, Alex Kleider  wrote:

On 2016-01-16 18:02, Cameron Simpson wrote:

much like writing a function "def f(x, y=None)"; None is a sentinel
value - specially recognised as nor in the normal domain for that
value.


Can you please clarify the last bit:
"specially recognised as nor in the normal domain for that value."


s/nor/not/

The domain of a function (or value) is the set of valid values it may
take. The range is the set of values it may produce.

A sentinel value is a special value you may encounter in a data set
(or as a value) which is _not_ part of the normal domain; often it
indicates the end of a sequence (hence the name, like a border guard).
 In Python the special value None is often used as a sentinel value.
Since all names have _some_ value, if you need to indicate that this
name "isn't set" or "doesn't specify a valid value", you need a
sentinal value, often "None".

So the common idiom for default values in Python function definitions:

 def func(a, b, c=None):
   if c is None:
 c = default-value-for-c
   ...

indicates that the parameters "a" and "b must be supplied, and "c" is
optional.  If not supplied it will have the value "None". This is a
sentinel value so that "func" can distinguish a valid value from a
value not supplied.

You can also use them to indicate the end of data in some sense. If
you're looking at a text file as lines of printable characters, the
newline character at the end of the line could be considered a
sentinel. Also consider a Queue: there's no notion of "closed" in the
stdlib version, so one might put a None on the queue to indicate to
the consumer that there will be no more items.

It isn't always None. Sometimes you may want to pass None as normal
data, or you have no control over what is passed around. In that case
you might need to make a unique sentinel value entirely for your
object. The normal way to do this is simply to make a new object:

 sentinel = object()

This is a minimal Python object which nobody else is using. Its value
is nothing special (or even meaningful), so you merely want to check
whether what you've got is that particular object, using "is".
Untested example sketch:

 class SomethingLikeAQueue:

   def __init__(self,..):
 self.things = []
 # private value to use as a sentinel, unique per instance
 self._sentinel = object()
 ... whatever else ...

   def put(self, value):
 # public method to put a new value
 if value is self._sentinel:
   raise ValueError("you may not put the sentinel value")
 self._put(value)

   def _put(self, value):
 # private method accepting any value including the sentinel
 # we will use receipt of the sentinel to process the things and
stop  # further acceptance of more things
 if value is self._sentinel:
   things = self.things
   self.things = None  # will make the .append blow up
   ... process things here maybe ...
 else:
   things.append(value)  ??? self.things.append(value)

   def close(self):
 # send the sentinel to indicate no more things
 self._put(self._sentinel)

Cheers,
Cameron Simpson 


Thanks, Cameron; use of 'sentinel = object()' is a whole new (and 
useful) concept for me.
May I trouble you further by specifically asking about 's/nor/not/'- I 
don't get what that's about.
Has it to do with this 'nor': 
http://www.merriam-webster.com/dictionary/nor?

Sincerely,
Alex

ps Am I correct that towards the end of your code it should have been
self.things.append(value)
(about 17 lines above?? )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] s.insert(i, x) explanation in docs for Python 3.4 confusing to me

2016-01-17 Thread Alex Kleider


Again, a personal thank you.
More often than not, when answering one thing, you teach me about
other things.  The 'thing' thing is only the latest.  Of course
I knew that using a name bound to a collection would effect the
contents of the collection but it would never have occurred to me
to use it to advantage as you describe.
Another "Ah, Ha!" experience.
Alex

On 2016-01-17 13:48, Cameron Simpson wrote:

On 17Jan2016 10:49, Alex Kleider  wrote:

Can you please clarify the last bit:
"specially recognised as nor in the normal domain for that value."


s/nor/not/


May I trouble you further by specifically asking about 's/nor/not/'- I 
don't get what that's about.


Ah. Ed, sed, vi, vim speak. Substitute: replace "nor" with "not". The
"nor" is a typo. I meant "not in the normal domain".

Has it to do with this 'nor': 
http://www.merriam-webster.com/dictionary/nor?


"Nor" is indeed a useful word, but it wasn't the word I intended.

[...]

It isn't always None. [...]
you might need to make a unique sentinel value entirely for your
object. The normal way to do this is simply to make a new object:

sentinel = object()

This is a minimal Python object which nobody else is using. Its value
is nothing special (or even meaningful), so you merely want to check
whether what you've got is that particular object, using "is".
Untested example sketch:

class SomethingLikeAQueue:

  def __init__(self,..):
self.things = []
# private value to use as a sentinel, unique per instance
self._sentinel = object()
... whatever else ...

  def put(self, value):
# public method to put a new value
if value is self._sentinel:
  raise ValueError("you may not put the sentinel value")
self._put(value)

  def _put(self, value):
# private method accepting any value including the sentinel
# we will use receipt of the sentinel to process the things and
stop  # further acceptance of more things
if value is self._sentinel:
  things = self.things
  self.things = None  # will make the .append blow up
  ... process things here maybe ...
else:
  things.append(value)  ??? self.things.append(value)

  def close(self):
# send the sentinel to indicate no more things
self._put(self._sentinel)

[...]

ps Am I correct that towards the end of your code it should have been
   self.things.append(value)


Yes. I probably let myself be lazy because of the earlier "things =
self.things" in the "true" branch of the "if", where I did it to keep
the former value of "things" for processing before scrubbing
self.things. Of course, that way lies buggy code.

I do occasionally pull various object attributes into local variables
for performance and readability; when I do that it really should be
right at the top of the function just after any parameter processing,
thus:

 class Foo:
   def method(self, foo, bar):
 things = self.things
 for item in foo:
   things.append(item) # or whatever

There are usually two reasons I would do that ("things = self.things"
at the top): (a) for readability if I'm going to be saying "things" a
lot - "self.things" may be cumbersome/wordy, making the code very
verbose or (b) for performance.

To the latter: saying "self.things" requires Python to look up the
things attribute in "self" every time you use it; if you put it into a
local variable then Python has direct access to it from the function
scope - in CPython his is very efficient, and likely so in other
Python implementations.

Don't forget that because both "self.things" and "things" refer to the
same list object (in the example earlier) there's no need to have any
final "self.things = things" because both are acting on the same list.

Cheers,
Cameron Simpson 

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


[Tutor] mock

2016-01-22 Thread Alex Kleider

Some weeks (perhaps months) ago, I posted a question about testing
and got many responses but had trouble grasping the concepts
so I settled on the suggestion that I thought would be the easiest
to implement (using unittest.mock.) Here it is-

"""
from Peter Otten:
I find Ben's example instructive, but when you're just starting you
might prefer a simpler approach:

import unittest
from unittest import mock
import mycode

class TestCollectData(unittest.TestCase):
def test(self):
with mock.patch(
"builtins.input",
side_effect=["foo", "bar", "baz"]):
self.assertEqual(
mycode.collect_data(),
dict(first="foo", last="bar", phone="baz"))

if __name__ == "__main__":
unittest.main()
"""

I've successfully implemented mock.patch parameters but don't
understand how to implement the parameters for the assertEqual
call as it pertains to my particular situation.

My current code sort of does the job but determinating success or
failure is not really automated.

It's Python 3 on Ubuntu 14.4LTS.
My test code and the tested code follow.  Any suggestions would be
most welcome.  Thanks in advance.
Alex

Test Code:
#!../../venv/bin/python
# -*- coding: utf-8 -*-
# vim: set file encoding=utf-8
"""
Attempt to automate testing of menu module.
"""
import unittest
from unittest import mock
import menu

class MenuTests(unittest.TestCase):

def test_create_new(self):
with mock.patch("builtins.input",
side_effect=['1', 'testentity', '', '0']):
menu.menu()

if __name__ == '__main__':  # code block to run the application
unittest.main()


Tested code:

#!../../venv/bin/python
# -*- coding: utf-8 -*-
# vim: set file encoding=utf-8
"""
A simple menu model used to format a question
about how to test using unittest.mock.
"""

class Entities(object):
"""
Keep track of the entities including a default.
Expect only one instance which will be a global.
"""

def __init__(self, list_of_entities, default=''):
self._list = list_of_entities
self.default = default

def get_default(self):
return self.default

def reset_default(self, default=''):
self.default = default

def get_list(self):
return self._list

def add(self, new_entity, set_default=False):
"""
Adds another entity returning it to signal success.
Returns None if entity is unacceptable.
"""
if (not new_entity in self._list
and new_entity.isalnum()
and new_entity[0:1].isalpha()):
self._list.append(new_entity)
if set_default:
self.reset_default(new_entity)
return new_entity
else:
print("Failing to add an invalid entity: '{}'."
.format(new_entity))

def get_new_entity(self):
"""
Prompts user for a new entity which, if valid, is
returned after being appended to list and set as default.
Returns None if fails to create a new entity.
"""
while True:
new_entity = input("Pick name for new entity: ")
if not new_entity: return
if new_entity != self.add(new_entity, set_default=True):
continue
else:
return new_entity

def remove(self, entity2remove):
if not entity2remove in self.get_list():
print("Can't remove '{}': not in the list."
.format(entity2remove))
return
if entity2remove == self.get_default():
self.reset_default()
self._list = [entity for entity in self._list
if entity!=entity2remove]

def show_listing(self):
"""
Returns a string listing the available entities.
Empty string if there are no entities.
"""
return ''.join(["\n\t{}".format(entity)
for entity in self.get_list()])

def entity_choice(self, set_default=False):
"""
Prompts the user to choose from the list.
Returns a valid choice or None.
Can optionally set the default to the chosen entity.
"""
list_of_entities= self.get_list()
if not list_of_entities:
print("There are no entities from which to choose.")
return
default_line = ''
 if self.default:
default_line = ("\n\t_: Default is '{}', just hit enter."
.format(self.default))
menu = ('\n'.join(["\t{}: {}".format(n, entity)
for (n, entity) in enumerate(list_of_entities, 1)])
+ default_line)
while True:
option = input(
"""Choose one of the following:
{}
\t0: to exit.
Pick an entity: """.format(menu))
default = self.get_default()
if (option=='' or option=='_') and default:
  

Re: [Tutor] Enumerate vs DictReader object manipulation:

2016-02-03 Thread Alex Kleider

On 2016-02-03 13:24, Ben Finney wrote:



You have discovered the difference between an iterable (an object you
can iterate over with ‘for’), versus a sequence (an object whose items
remain in place and can be iterated many times).

Every sequence is an iterable, but not vice versa.

File objects are iterables, but not sequences. Each time you ask for 
the

next item, you can't ask the file object for that item again; it is
“consumed” by the act of iteration.


How does a dict fit into this scheme?
Is it a sequence?  It is an iterable (in that for key in d: works 
although not in a predictable manner and for this reason I tend NOT to 
think of it as a sequence.)

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


Re: [Tutor] Enumerate vs DictReader object manipulation:

2016-02-04 Thread Alex Kleider

On 2016-02-04 01:46, Oscar Benjamin wrote:


You can see an explanation of the different collection terminology 
here:

https://docs.python.org/2/library/collections.html#collections-abstract-base-classes

A dict is a Mapping and a set is a Set. Both also comes under the
categories Sized, Iterable, and Container.

--
Oscar


Thanks for the clarification.  It caused me to go down the path a bit 
farther...

The following link might be helpful in this context:
http://blog.wachowicz.eu/?p=132
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommendations for best tool to write/run Python

2016-03-02 Thread Alex Kleider


I've not noticed anyone mention vimtutor which might be helpful.

On a Mac or Linux system, from the command line simply type "vimtutor"
and with in 1/2 to 1 hour you'll know enough to use vim _and_ be in a
position to decide if it's the editor for you.  I've been told vim can
also be had on the Redmond OS but I've no experience there.
Alex


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


[Tutor] Object-Oriented Analysis by Peter Coad & Edward Yourdon

2016-03-23 Thread Alex Kleider

The above cited book was mentioned in a recent thread (by Alan I think.)
I acquired the book but it isn't at all what I expected and I've no use
for it.  If he or anyone else would like it, I'm happy to send it along.
Just let me know an address[1] to which to send it.
Cheers,
Alex

[1] I'm happy to pay for postage for US
and could also send to GB (a friend is visiting
and could carry it back and mail locally.)
Else where might be more expensive than it's worth.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Detect the folder of a file

2016-04-26 Thread Alex Kleider



On 2016-04-26 16:16, Oliver Bestwalter wrote:


sys.executable

'/home/obestwalter/.pyenv/versions/3.4.4/envs/tmp/bin/python3.4'


Not sure if this helps but perhaps:

alex@X301:~/Py$ which python
/usr/bin/python
alex@X301:~/Py$ . venv/bin/activate
(venv)alex@X301:~/Py$ which python
/home/alex/Py/venv/bin/python
(venv)alex@X301:~/Py$

[Ubuntu 14.04 LTS]

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


Re: [Tutor] "List" object is not callable

2016-04-30 Thread Alex Kleider



On 2016-04-30 11:51, Jason N. via Tutor wrote:

Hello,
I found this simple script online but when I execute it I get the
following error: "TypeError: 'list' object is not callable"
Here is the code sample:import subprocess

ls_output= subprocess.check_output(['dir'])

It works on my system: Ubuntu 14.04LTS

(venv)alex@X301:~$ python
Python 3.4.3 (default, Oct 14 2015, 20:33:09)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

import subprocess
ls_output= subprocess.check_output(['dir'])
ls_output
b'Airbnb\tBookSite  CURRENT  Documents  examples.desktop\tJs\t   
nextWIFI\t OpenWRT   Py\t   Solar  ToDo\t  WARNING\nARM\tC\t  debk\t 
  double gnupg.other\tLEFTOFFnode_modules  Pathagar  Rachel  
Templates  toDoAtLoft  wishes\nAVR\tclosures  Desktop  Downloads  
GPL\t\tLibreboot  Notes\t Pictures  SaskTest   Videos\t  
WWW\nbin\tContacts  Docbook  Encrypted  HTML5\t\tMusic\t   OLPC\t\t 
Publicski\t   tmp\t  vim_rewrap\n'

exit()

(venv)alex@X301:~$ dir
Airbnb	BookSite  CURRENT  Documents  examples.desktop	Js	   nextWIFI	 
OpenWRT   Py	   Solar  ToDo	  WARNING
ARM	C	  debk	   double gnupg.other	LEFTOFFnode_modules  Pathagar 
 Rachel  Templates  toDoAtLoft  wishes
AVR	closures  Desktop  Downloads  GPL		Libreboot  Notes	 Pictures  Sask  
  Test   Videos	  WWW
bin	Contacts  Docbook  Encrypted  HTML5		Music	   OLPC		 Publicski	  
 tmp	  vim_rewrap

(venv)alex@X301:~$ man dir


Perhaps you are using a linux command on a non linux (?Windows) system.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Study Tips

2016-05-30 Thread Alex Kleider


On 2016-05-30 12:02, boB Stepp wrote:
...

Are you totally new to programming in *any* language?  If yes, you
have much more to learn than *just* a programming language.  I am
going to assume that you are very new to programming in general.
Forgive me if I am mistaken!  But if you are, then some of the things
you must learn that are language-independent:



With the above comments in mind, this might be worth looking at:
http://openbookproject.net/thinkcs/python/english3e/

I cut my teeth on the original version which was Python 2.7 based and
was just the thing meeting the criteria mentioned by Bob.
I assume the Python 3 version has the same merits.
Best wishes,
Alex

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


Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit

2016-06-28 Thread Alex Kleider



On 2016-06-27 20:48, Steven D'Aprano wrote:


Also Debian. Not Ubuntu.


Can you elaborate why you specifically exclude Ubuntu?

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


Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit

2016-06-28 Thread Alex Kleider



On 2016-06-28 11:46, David Rock wrote:

Here’s my take on a lot of this (it’s similar to what’s been said
already, so this is more of a general philosophy of distros).


Very interesting reading for which I thank you.
I'd be interested in knowing if you'd make a distinction between 'the 
latest

Ubuntu' and their LTS releases?
My approach has been to use LTS releases only and not bother with the 
ones

in between.

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


[Tutor] project directory structure

2016-08-25 Thread Alex Kleider

I'm still struggling with what is the best way to set up a project
directory.

All the sources I've read seem to agree that one should have a top
level project directory under which one might expect to find the 
following:

COPYING.txt # or LICENSE.txt
README.rst
setup.py
and if the project consists of only one .py file, it also goes here
but if there is to be more than one module, the code should be in a
subdirectory of the same name as the top level one so we now have
something like the following:
MyProject
COPYING.txt # or LICENSE.txt
MyProject
data/
src/
module1.py
module2.py
tests/
test1.py
test1.py
README.rst
setup.py


Assuming the latter scenario, where should one run
virtualenv -p python3 venv?
... at the top level or within the second level?

During development I would expect to have MyProject/MyProject
as my working directory most of the time and hence think venv should
be there but perhaps it should be the level above so that it
encompasses setup.py.

The main reason I want to get this right is because all my .py files
begin with a shebang line of the form
#!../venv/bin/python3
which uses a relative path so the choice I make will determine
if I use the above or
#!../../venv/bin/python3


Any advice would be appreciated.

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


Re: [Tutor] project directory structure

2016-08-25 Thread Alex Kleider

On 2016-08-25 21:27, Ben Finney wrote:


That's exactly the wrong thing to do. Your shebang line should *not*
assume a custom location of the Python interpreter.

It's the responsibility of the operating system or virtualenv to 
provide

the Python interpreter command in a standard place.

Instead, use:

#! /usr/bin/env python3

or:

#! /usr/bin/python3

and leave it to the operating system and the virtualenv to provide the
Python interpreter correctly.


Thanks, Ben, for your input.
Am I to assume that if I have activated a virtualenv, then the following 
shebang

#!/usr/bin/env python
will use the python specified in the venv/bin/?

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


Re: [Tutor] project directory structure

2016-08-27 Thread Alex Kleider

On 2016-08-26 21:58, Ben Finney wrote:

Alex Kleider  writes:


Am I to assume that if I have activated a virtualenv, then the
following shebang
#!/usr/bin/env python
will use the python specified in the venv/bin/?


Yes, the purpose of that shebang is to tell the OS that *whichever*
‘python’ command is found first, is the one to use.



Thanks for clarifying.
It was only after poking around and experimenting that I discovered that 
what the virtualenv activate command actually does is place its bin 
directory at the beginning of the PYTHONPATH environment variable- 
something I've no where seen explicitly documented.

cheers,
Alex

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


Re: [Tutor] project directory structure

2016-08-28 Thread Alex Kleider

On 2016-08-27 15:23, c...@zip.com.au wrote:

On 27Aug2016 09:06, Alex Kleider  wrote:

On 2016-08-26 21:58, Ben Finney wrote:

Alex Kleider  writes:

Am I to assume that if I have activated a virtualenv, then the
following shebang
#!/usr/bin/env python
will use the python specified in the venv/bin/?


Yes, the purpose of that shebang is to tell the OS that *whichever*
‘python’ command is found first, is the one to use.


Thanks for clarifying.
It was only after poking around and experimenting that I discovered 
that what the virtualenv activate command actually does is place its 
bin directory at the beginning of the PYTHONPATH environment variable- 
something I've no where seen explicitly documented.


Shouldn't that be $PATH?
Yes indeed- typing too quickly short circuiting the brain! Good that 
it's been pointed out.



It does this so that running "python" will
find the virtulenv "python" command ahead of others, which is its
design requirement.  The venv "python" then does essentially the same
thing internally with sys.path to achieve the same effect for python
module imports.

Cheers,
Cameron Simpson 

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


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Alex Kleider

On 2016-09-09 11:50, Pooja Bhalode wrote:

Hi everyone,

I was getting this error which read ' 'IndexedVar' object is not 
callable '

for a variable type.


You haven't provided much information but it seems to me you are calling 
IndexedVar as though it were a function but it probably isn't a 
function.


some_name(zero_or_more_parameters)

is a function call, calling some_name.

If some_name hasn't been defined as a function:
def some_name():
  do something

then you can expect the error you got.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error: 'IndexedVar' object is not callable

2016-09-09 Thread Alex Kleider

On 2016-09-09 18:13, Steven D'Aprano wrote:

Please read this article first for
how you can improve the chances of getting good answers to your
questions:

http://sscce.org/


In addition to the link Seven provides above, I've also found the 
following to be worth perusing:

http://www.catb.org/esr/faqs/smart-questions.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python help

2016-10-16 Thread Alex Kleider

On 2016-10-15 15:48, Nicholas Hopkins wrote:

Hello
Please tell me what is wrong with my code and how I can put an if else
statement inside of another if else statement
This is my code:
path = input('Which path number will you take?')
if path == '1':
 print('You took the first path')
elif path == '2':
 print('You choose to take the second path')
 print('You see a rock')
  rock == input('Do you want to pick up the rock')
  if rock == 'yes':
  print('you picked up the rock')
  else:
  print('You left the rock')
elif path == '3':
 print('You choose to take the third path')
else:
 print('You must choose a number between 1 and 3')


it comes up with this error
[cid:image001.png@01D22792.63CCF290]


Can't see your error (text only list) but it's probably due to 
indentation problems.

Why do you have only the first line not indented?
Also check indentation of lines 7, 8 and 10.



Thanks
Sent from Mail for 
Windows 10


___
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


[Tutor] run local script on a remote machine

2016-10-26 Thread Alex Kleider


I've got three files as follows:

1:
#!/usr/bin/env python3
#
# file: experiment.py
#
# A simple python program that takes parameters.

import sys
info = sys.argv[1:]
print(info)
with open("/home/alex/junk.txt", 'w') as file_object:
for item in info:
file_object.write(''.join((item,'\n')))

2:
#!/bin/bash
#
# file: call.sh

# Demonstrates running a local python script on another host
# with command line arguments specified locally.

ssh -p22 alex@10.10.10.10 python3 -u - one two three < 
/home/alex/Py/BackUp/Sandbox/Scripted/experiment.py


3:
#!/usr/bin/env python3
#
# file: call.py

import os
import shlex
import subprocess

script = "/home/alex/Py/BackUp/Sandbox/Scripted/experiment.py"
if os.path.isfile(script):
print("File exists on local machine.")
else:
print("No such file.")

command = (
"ssh -p22 alex@10.10.10.10 python3 -u - one two three < {}"
.format(script))

ret = subprocess.call(shlex.split(command))

if ret:
print("Command failed!!")
else:
print("All's well.")


Running the shell script (2) executes a single shell command and leaves 
the junk.txt file at 10.10.10.10 as desired.
Calling the same shell command using the subprocess module from with in 
a python script (3) does not work:

alex@X301n3:~/Py/BackUp/Sandbox/Scripted$ ./call.py
File exists on local machine.
bash: /home/alex/Py/BackUp/Sandbox/Scripted/experiment.py: No such file 
or directory

Command failed!!

I'm doing this using Ubuntu14.04LTS.

Thanks in advance for any suggestions as to how to proceed.

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


Re: [Tutor] run local script on a remote machine

2016-10-27 Thread Alex Kleider

On 2016-10-27 00:57, Wolfgang Maier wrote:


The structure of the command you are trying to execute would require
you to set the "shell" argument of subprocess.call to True.
Specifically, the "<" redirection operator is shell functionality.


Thank you Wolfgang.  Simply eliminating the call to shlex.split() made 
everything work as desired.


.



as long as you promise to NEVER use that code in production with user
input. The problem with it is that it may allow users to inject shell
commands as they like exactly because whatever ends up in the command
string gets interpreted by the shell.


I promise!

Thanks again.
Alex


_

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] run local script on a remote machine

2016-10-27 Thread Alex Kleider

On 2016-10-27 00:22, Cameron Simpson wrote:

On 26Oct2016 10:44, Alex Kleider  wrote:

command = (
"ssh -p22 alex@10.10.10.10 python3 -u - one two three < {}"
   .format(script))
ret = subprocess.call(shlex.split(command))


This is not fine.

..

 http://bobby-tables.com/


Thanks for the warning.  I'm aware of the injection problem and should 
have mentioned that the code exposed itself to this only because I was 
trying to make it as short as possible to demonstrate the problem.




The second problem, and the one causing your immediate issue, is the
use of shlex.split.


Eliminating it made things work as desired.


Hoping this clarifies what's going on and how to go forward.


It does that indeed.  Thank you very much.


Please feel free to ask any questions that occur.


Also gratitude to you and the others on this list that are so generous 
with your advice.


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


Re: [Tutor] how to move an executable into path

2016-11-27 Thread Alex Kleider

On 2016-11-27 16:26, Steven D'Aprano wrote:

snip..


I fully admit some snark about Firefox.


snip..

I've been using Firefox on Ubuntu for years and haven't recognized any 
difficulties although I don't use it for much other than email, 
searching, and occasionally shopping.


I would be interested in knowing your browser of choice- obviously not 
Safari!


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


Re: [Tutor] help :making window

2016-12-31 Thread Alex Kleider

On 2016-12-31 09:35, Joel Goldstick wrote:


Semicolon (;) isn't used in python
as a statement separator


alex@X301n3:/mnt$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

gee = "really"; print(gee)

really





Considered 'bad style' by many, but it does appear to be part of the 
language.

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


Re: [Tutor] Basic Tutorial for Python

2017-02-06 Thread Alex Kleider

On 2017-02-06 08:13, Hüseyin Ertuğrul wrote:

Hello all,
I am a system engineer and I want to learn python language. I don't
know any program language and I need tutorial for beginner or for
dummies.
By the way I want to see basic example codes for practice.

What is your suggestion for that case.


Allen B. Downey's book served me very well when I first got interested 
in Python; he's now got a Python 3 version as well.
It's available free on the web, or you can buy the book on Amazon and 
elsewhere.

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


Re: [Tutor] Error when trying to use classes

2017-02-07 Thread Alex Kleider

On 2017-02-07 07:34, Rafael Skovron wrote:
I'm trying to learn how to use Classes but I keep getting  NameErrors 
no

matter what code I put into the script.

Any ideas why?


Assuming the code you've edited using vim is in a file mymodule.py
And after invoking the interpreter you issue the following:

import mymodule.py

your instantiation statement needs to be

rafael = mymodule.Customer('rafael', 100.0)


Alternatively you can use the following import statement (not generally 
recommended:)

from mymodule import Customer





My general workflow is I edit in vim, then invoke python3 interpreter,
import the module and try to use the Class and methods from the class.

For example, importing customer.py and assigning this object yields:


rafael = Customer('rafael',100.0)

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'Customer' is not defined



class Customer(object):
"""A customer of ABC Bank with a checking account. Customers have
thefollowing properties:
Attributes:name: A string representing the customer's
name.balance: A float tracking the current balance of the
customer's account."""

def __init__(self, name, balance=0.0):
"""Return a Customer object whose name is *name* and starting
  balance is *balance*."""
self.name = name
self.balance = balance

def withdraw(self, amount):
"""Return the balance remaining after withdrawing *amount*
   dollars."""
if amount > self.balance:
raise RuntimeError('Amount greater than available 
balance.')

self.balance -= amount
return self.balance

def deposit(self, amount):
"""Return the balance remaining after depositing *amount*
  dollars."""
self.balance += amount
return self.balance
___
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] Test for type(object) == ???

2017-02-10 Thread Alex Kleider

On 2017-02-10 17:34, boB Stepp wrote:

I was playing around with type() tonight.  .


I've also "played around" with this subject-
Here's a source:
http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python

... and a successful experiment:
alex@X301n3:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

type(5) is int

True

isinstance(5, int)

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


  1   2   3   >