Re: [Tutor] Learning Objectives?

2017-02-27 Thread Mats Wichmann
On 02/27/2017 07:57 AM, leam hall wrote:

> When I was coming up as a Linux guy I took the old SAGE guidelines and
> studied each "level" in turn. It was useful for making me a well-rounded
> admin and helped me put off some higher end stuff I wasn't really ready
> for.
> 
> Things like Testing and documentation are useful, but only learning what
> seems to bee needed for this one project seems harder for the new coder.
> Most of us didn't know TDD was useful until we started doing it. Same for
> documentation. It's sort of the "if we hired a junior or senior coder, what
> basics would we want them to know?"
> 
> Thanks!
> 
> Leam

Just as a suggestion,

I think if you look at the curriculum of various training courses,
books, online tutorial series you will get each author's view of what a
logical progression is. There are probably as many different
progressions as there are people expressing an opinion, but it seems to
me the flow is at least roughly aligned when I glance at these from time
to time.

For example (this is no endorsement, just a site I do peer at now and
then and so remember it), look here:

http://www.python-course.eu/python3_course.php

the left bar has a kind of order that's not insane (except I'd be
looking at files in the first 10 minutes, but that's just me); then
there's a tab called "advanced topics": forking, threads, etc. and then
some stuff you look at if you need it: wsgi, mod_python, sql connectors.
And then another tab for a great big "external" topics like NumPy,
Machine Learning and there are lots more in that category like Django,
Flask, SciPy, and so on - all can be considered "advanced" because
they're not the language itself, but stuff some people might expect you
to be proficient in for a given job that's billed as a "Python Job".

If you're looking at abstract base classes in your first few days,
that's probably not the right order ;)

I even have a bit of a bone to pick with the TDD movement, not that it's
a bad idea by itself, but when treated as a "religion" it seems to lead
to a mindset that unit tests alone are sufficient to prove a codebase,
when integration testing is just as important.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] looping - beginner question

2017-03-02 Thread Mats Wichmann
On 03/02/2017 08:06 AM, Alan Gauld via Tutor wrote:
> On 02/03/17 13:42, Rafael Knuth wrote:
> 
>> bar = ["beer", "coke", "wine"]
>>
>> customer_order = input("What would you like to drink, dear guest? ")
>>
>> for drink in bar:
>> if customer_order != drink:
>> print ("Sorry, we don't serve %s." % customer_order)
>> else:
>> print ("Sure, your %s will be served in a minute!" % customer_order)
>>
>> What I want the program to do is to "silently" loop through the list
> 
> So you only want the sorry... message if the loop completes without
> finding a drink. That means you need to put that print statement after
> the loop. Python includes a feature for that - a for/else construct.
> 
> for drink in bar:
> if drink == customer_order:
>print(Sure...)
>break  #exit loop and avoid else
> else:
> # only if the loop completes normally
> 
> However, there is another way to do this that doesn't
> use an explicit loop: the 'in' operator
> 
> if customer_order in bar:
> print("sure)
> else:
> print ("Sorry)

To follow on to what Alan said, you don't need to loop over a list (or
tuple, or dictionary, or other "iterable") to find out if it contains an
item. You can just test membership directly.




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


Re: [Tutor] printing items form list

2017-03-03 Thread Mats Wichmann
On 03/03/2017 05:12 AM, Rafael Knuth wrote:
> I want to print individual items from a list like this:
> 
> You have a book, towel, shirt, pants in your luggage.
> 
> This is my code:
> 
> suitcase = ["book", "towel", "shirt", "pants"]
> print ("You have a %s in your luggage." % suitcase)
> 
> Instead of printing out the items on the list, my code appends the
> list to the string. How do I need to modify my code?
> 
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py ==
> You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.


By way of explanation:

suitcase = ["book", "towel", "shirt", "pants"]
print(type(suitcase))
print ("You have a %s in your luggage." % suitcase)


===

You have a ['book', 'towel', 'shirt', 'pants'] in your luggage.

suitcase is a list.  You explicitly ask for it to be shown a string with
"%s", so the list class's string representation method is called to
produce what the class thinks is the best way to show what the list
contents looks like.  that conversion to a string someone else's idea
(Python default), but not what you wanted, though; joining with commas
is the right choice based on what you said you wanted.


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


Re: [Tutor] Is this a scope issue?

2017-03-06 Thread Mats Wichmann
On 03/05/2017 06:33 PM, Rafael Skovron wrote:
> This project compares two text files with parcel numbers. I think I'm
> messing up the function call. I'm getting this error:
> 
> Traceback (most recent call last):
>   File "amador.py", line 48, in 
> remaining_parcels(auctionlist,removedlist)
> NameError: name 'auctionlist' is not defined
> 

In this code I'd note a couple of things besides "the answer" which was
already given.

- you seem to have an indentation problem with the last line of each
function.  Not sure if that was just a paste problem; but the way the
"return" statements are placed, they would execute on the first match,
not after the whole loop. Indeed, as posted I'd expect you would get an
IndentationError because they don't line up with any block; do make sure
in your real code they're indented at a level that places them outside
the scope of the "with" statement in the first two and outside the "for"
loop in the third.

- you've got one-liner comments at the beginning of each function
definition. Might as well follow convention and turn those into
docstrings. As in for example:

def get_removed_number(removed):
'''this grabs the removed parcel numbers and stores to a list'''

- assuming you're a beginner since you are posting here, you could keep
in mind as you learn more that many loop+condition test constructs to
populate a list can be recoded as a list comprehension. That is:

remainingparcels =[]
for parcel in auctionlist:
if parcel not in removedlist:
remainingparcels.append(parcel)

is able to be rewritten as:

remainingparcels = [parcel for parcel in auctionlist if parcel not
in removedlist]

at that point you might question whether you even want to have a
separate remaining_parcels function, this one-liner could just go in
your main body.  That's up to you, of course!  When I first learned
"list comprehensions" I didn't find them more readable than what they
can replace; now I definitely do.



> 
> import re
> 
> fname = 'saclisting.txt'
> removed = 'removed.txt'
> 
> def get_parcel_number(fname):
> #this retrieves parcel numbers from the saclisting file and stores to
> auctionlist
> 
> 
> pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})'
> auctionlist = []
> 
> 
> with open(fname,'r') as file:
> text = file.readlines()
> for index,line in enumerate(text):
> if re.search(pattern,line):
> #add line to auctionlist if the pattern is found
> auctionlist.append(line)
> return auctionlist
> 
> def get_removed_number(removed):
> #this grabs the removed parcel numbers and stores to a list
> pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})'
> removedlist = []
> 
> with open(removed,'r') as file:
> text = file.readlines()
> for index,line in enumerate(text):
> if re.search(pattern,line):
> # add  line to removedlist
> removedlist.append(line)
> return removedlist
> 
> def remaining_parcels(auctionlist,removedlist):
> #compares parcels in auctionlist to removedlist and returns parcels that
> have not bee removed
> remainingparcels =[]
> for parcel in auctionlist:
> if parcel not in removedlist:
> remainingparcels.append(parcel)
> return remainingparcels
> 
> 
> 
> 
> get_parcel_number(fname)
> get_removed_number(removed)
> remaining_parcels(auctionlist,removedlist)
> ___
> 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] Socket error in class

2017-03-06 Thread Mats Wichmann
On 03/06/2017 10:35 AM, leam hall wrote:
> What am I missing?
> 
> 
> class mysocket():
>   import socket
>   def __init__(self, sock=None);
> if sock is None:
>   self.sock = socket.socket(socket.socket.AF_NET,
> socket.socket.SOCK_STREAM)
> else:
>   self.sock = sock
> 
> 
> 
> Error:
> NameError: global name "socket" is not defined.

The Python style guide, "PEP8", says this:

Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.


an import statement creates a module object (if it hasn't been
previously imported, that is), and then executes it, leaving the name
you imported it as bound to the module object. That means when you do
what you did above, "socket" is a name inside the "mysocket" scope, and
it's no different than if you defined a class variable - you need to
qualify it to access it, it should be available as as self.socket inside
a method or as mysocket.socket.  But it seems better to do the import at
the top instead, then it really looks like a global and there won't be a
complaint.

Note also in your code (I'm assuming you typed stuff, and did not paste
directly from the code you were trying):

- your __init__ definition ends with semicolon, not colon
- it's AF_INET, not AF_NET
- you've doubled "socket" in referring to constants AF_INET and SOCK_STREAM





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


Re: [Tutor] Lists of duplicates

2017-03-09 Thread Mats Wichmann
On 03/08/2017 12:56 PM, Sri Kavi wrote:
> As part of my learning, I was participating in a discussion at:
> 
> 
> 
> https://discuss.codecademy.com/t/python-lists-of-duplicated-elements/78151
> 
> 
> 
> It’s about making a function that returns a list of lists, with each list
> being all of the elements that are the same as another element in the
> original list.
> 
> 
> 
> function([1, 2, 3, 4, 1, 1, 2, 3]) should return [[1, 1, 1], [2, 2], [3,
> 3], [4]]
> 
> 
> I wrote and submitted the following function:
> 
> def sublist_duplicates(lst):
> sublists = []
> 
> for item in set(lst):
> sublists.append([item] * lst.count(item))
> 
> return sublists
> 
> lst_of_duplicates = [1, 2, 10, 3, 4, 1, 's', 2, 3, 1, 4, 's']
> 
> print sublist_duplicates(lst_of_duplicates)
> 
> A participant told me that that'll grind into a near-halt if there are many
> different elements, for example range(1_000_000) (1 million unique values,
> so it checks the whole list (length 1 million) for the count, a million
> times, a total of 1000 billion operations…
> 
> 
> I thought he was right. I wrote another version of the function, this time
> using collections.Counter.
> 
> from collections import Counter
> 
> def sublist_duplicates(lst):
> counts = Counter(lst)
> sublists = [[k] * counts[k] for k in counts]
> return sublists
> 
> _lst = list(range(100))
> 
> import timeit
> 
> time = timeit.timeit("sublist_duplicates(_lst)", setup = "from __main__
> import sublist_duplicates, _lst", number=1)
> 
> print("Number of elements in the list: {}".format(len(_lst)))
> print("Execution time of the function: {} seconds".format(round(time, 2)))
> 
> I found that the first version works better with a small list, but the
> second version outperforms the first one when it’s given a considerably big
> list of data.
> 
> 
> I’m asking for your comments on these two functions. I’m not even sure if
> this is how it should be coded.


Well, my thought was to go for simple. collections.Counter is really
designed for this, so why not?

First decompose problem:
1. count occurrence of elements in a list
2. emit a list of element/count pairs, each pair as a list
   repeating the element "count" times as long as count is
   at least two ("elements that are the same as another element")
3. decide if problem constraints warrant optimization

without getting into 3 (there were none in the problem statement),
here's what came to mind, looks a lot like your second solution:


import random
import collections

# generate some sample data to work on:
nums = [random.randint(1,10) for _ in range(50)]
print("list to process:", nums)

counted = collections.Counter(nums)
print("counts:", counted)

countlists = [[item] * counted[item] for item in counted if
counted[item] > 1]
print("countlists: ", countlists)


When I ran this I got:

list to process: [2, 6, 1, 2, 2, 5, 6, 6, 10, 2, 3, 8, 6, 6, 4, 2, 8, 2,
1, 1, 8, 4, 3, 5, 6, 6, 6, 4, 5, 1, 1, 8, 6, 3, 6, 10, 2, 7, 9, 4, 3, 6,
2, 4, 10, 4, 5, 1, 2, 7]
counts: Counter({6: 11, 2: 9, 1: 6, 4: 6, 3: 4, 5: 4, 8: 4, 10: 3, 7: 2,
9: 1})
countlists:  [[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3,
3], [4, 4, 4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
[7, 7], [8, 8, 8, 8], [10, 10, 10]]


notice value 9 missing from result line, as the count was only 1.


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


Re: [Tutor] Help!! Code ridden with Bugs

2017-03-09 Thread Mats Wichmann
On 03/09/2017 12:32 PM, Joel Goldstick wrote:
> On Thu, Mar 9, 2017 at 8:28 AM, Eloka Chima via Tutor  
> wrote:
>> I am new to programming but an immersive  study in the past few weeks have 
>> brought me to speed so I can play around with codes but not really mastered 
>> them.My assignment below is ridden with bugs and I've done so much to get 
>> rid of them but to no avail.
>> Below is the project :
>>
>> Create a class called ShoppingCart.
>>
>> Create a constructor that takes no arguments and sets the total attribute to 
>> zero, and initializes an empty dict attribute named items.
>>
>> Create a method add_item that requires item_name, quantity and price 
>> arguments. This method should add the cost of the added items to the current 
>> value of total. It should also add an entry to the items dict such that the 
>> key is the item_name and the value is the quantity of the item.
>>
>> Create a method remove_item that requires similar arguments as add_item. It 
>> should remove items that have been added to the shopping cart and are not 
>> required. This method should deduct the cost of the removed items from the 
>> current total and also update the items dict accordingly.
>>
>> If the quantity of an item to be removed exceeds the current quantity of 
>> that item in the cart, assume that all entries of that item are to be 
>> removed.
>>
>> Create a method checkout that takes in cash_paid and returns the value of 
>> balance from the payment. If cash_paid is not enough to cover the total, 
>> return "Cash paid not enough".
>>
>> Create a class called Shop that has a constructor which takes no arguments 
>> and initializes an attribute called quantity at 100.
>>
>> Make sure Shop inherits from ShoppingCart.

that is an odd relationship (I realize it's part of the assignment as
you've posted it)... a "Shop" is conceptually a bigger thing than a
Shopping Cart what with overall inventories, item descriptions as well
as an overall financial picture; you'd almost think the shopping cart
would be the subclass.

>>
>> In the Shop class, override the remove_item method, such that calling Shop's 
>> remove_item with no arguments decrements quantity by one'''
>>
>>
>


>>   def checkout(self, cash_paid):
>>
>> self.cash_paid = cash_paid
>>
>> if self.cash_paid < self.total:
>>
>>   self.total -= self.cash_paid
>>
>>   return self.total
>>
>>   return "Cash paid is not enough"

Here you can't return two things, once you return, you are out of the
function, there's no chance to return a second time. Perhaps you meant
to have the second return be behind an "else:" statement? I think you
must not be expected to take this part of the description this
literally, because a financial total amount and a text string are
different types of objects, while Python's typing system makes it
possible to return either, that doesn't make it a good idea in your API
- how are you going to describe to users of this function that it might
be a totel, but then again it might be an error message? Giving some
thought to how to have a consistent return value and still meet the
requirements seems a good idea.

Have some other thoughts as well... in your Shop derived class (see
above), were you expecting the base class (ShoppingCart) initializer to
also run? If so, you better call it.


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


Re: [Tutor] While until the end of a list

2017-03-13 Thread Mats Wichmann
On 03/13/2017 10:48 AM, Toni Fuente via Tutor wrote:
> * David Rock  [2017-03-13 11:28:57 -0500]:

>> You just need to make a list or a dict to store the information for each 
>> site, and add the results to it.  If you use a list, it would be 
>> list.append(), for example.
>>
>> I don’t really follow what you expect the output to be, though.
>> What do you want the results of running the script to look like?
> 
> At the moment I am writing to a file:
> 
> with open("/tmp/afm/etc/httpd/conf.d/vhosts.inc/%s.conf" % site, "a") 
> as cfile:
> cfile.write("".join(new_config))
> 
> and whenever finds the first chunck in total_configs.txt writes to it, and
> doesn't carry on searching for other chunks that contain "site", foo.com, so 
> it
> won't find the site in port 80.

There's an existing project you might be able to make use of...

https://pypi.python.org/pypi/parse_apache_configs/0.0.2

it's somewhere on github, I think the PyPi page links to that.



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


Re: [Tutor] Using Class Properly - early beginner question

2017-03-23 Thread Mats Wichmann
On 03/22/2017 06:30 AM, Rafael Knuth wrote:
> thanks for your feedback! @boB
> 
> I wrote a function that does exactly what I want, and that is:
> Create a shopping list and then let the user decide which items (food)
> are supposed to be instantly consumed and which ones stored.
> 
> def ManageFood():
> create_shopping_list = []
> prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. 
> ")
> food = input(prompt)
> 
> while food != "quit":
> create_shopping_list.append(food)
> food = input(prompt)
> 
> print("These are your foods on your shopping list: %s." % ", "
> .join(create_shopping_list))
> eat_food = []
> store_food = []
> for food in create_shopping_list:
> print("You bought this item: %s. " % (food))
> prompt = input("What would you like to do with it?\nEnter
> 'eat' or 'store'. ")
> if prompt == "eat":
> eat_food.append(food)
> elif prompt == "store":
> store_food.append(food)
> print("Food you want to eat now: %s." % ", " .join(eat_food))
> print("Food you want to store: %s." % ", " .join(store_food))
> 
> ManageFood()
> 
> PS: Please let me know if you have any suggestions how to write my
> code above in a shorter, more elegant fashion (it does what it's
> supposed to do, but not sure if a pro would write it same way I did).

You could think here about how you described the food items: they have
an attribute which is either eat or store... it's not just a (string)
name, but also how you intend to categorize tht tiem.  It's possible a
dictionary - a collection of name/value pairs - could be a more natural
way to capture the data than multiple lists. So perhaps a datastructure
like:

{ ('asparagus', 'eat'), ('beans', 'store'), ... }

Up to you, just an observation.

> 
> Besides that, I want to take it a step further and rewrite the
> function above as a class, and I don't know how exactly how to do
> this.
> (coding newbie pains ... I just learned the basics about classes in
> Python, but nowhere could I find examples of how to properly
> initialize classes, given that it operates solely with user input -
> same goes with with calling that class properly). Here's how far I got
> on my own:

Rule 1: Python is not specifically an object-oriented language. If the
problem you're trying to solve is best served by a class-based approach,
by all means, it will work fine that way.  But there's nothing /forcing/
you (unless it's a learning assignment, that is: "how do I do this using
classes") to turn an implementation into a class.

After that thought, what do you want the class to represent? The whole
shopping cart? A single food item?  The latter actually feels a bit more
natural to me, but I'm not the one inventing the problem.

On to some details.

> 
> class FoodShopping(object):
> def __init__ (self, create_shoppping_list, prompt, food, eat_food,
> store_food):
> self.create_shopping_list = create_shopping_list
> self.prompt = prompt
> self.food = food
> self.eat_food = eat_food
> self.store_food = store_food

(a) you can store the prompt in the instance, sure, but the prompt is
neither unique to the instance (which means it doesn't need to be
there), nor is it really anything to do with the class, which means it
doesn't really need to be a class variable either.
(b) see above: eat vs store isn't really two different things, it's one
- and maybe it's a boolean: eat = True vs eat = False. Though you might
think of other states later, and then it's not a boolean any more.
(c) probably what you wanted here was not to pass in the three list
items, but to initialize them. And the other parameters perhaps aren't
really things needed up front, so you might even end up with an
initializer that looks like this:

def __init__(self):
self.create_shopping_list = []
self.eat_food = []
self.store_food = []

Like magic that would fix the initial error your program stopped on -
the initializer wanted multiple args and didn't get them (see below).

> def ManageFood(self, create_shopping_list, prompt, food, eat_food,
> store_food):
> create_shopping_list = []
> prompt = ("Which foods would you like to purchase?\nEnter
> 'quit' to exit. ")

This makes no sense... you're passing in "prompt", but then overriding
it in the method. So why pass it in at all?

> food = input(prompt)
> 
> while food != "quit":
> create_shopping_list.append(food)
> food = input(prompt)
> 
> print("These are your foods on your shopping list: %s." % ", "
> .join(create_shopping_list))
> eat_food = []
> store_food = []

You already created instance variables create_shopping_list, eat_food
and store_food.  Don't redo those in the method, use the instance
variables (self.create_shopping_list, self.eat_food, self.store_food).

> for food in create_shopping

Re: [Tutor] Help with function scoping

2017-03-23 Thread Mats Wichmann
On 03/22/2017 03:17 PM, Richard Mcewan wrote:
> Hi
> 
> I wonder if you can help. 
> 
> I'm confused about how functions should work. Below is some code I write to 
> check my understanding. 
> 
> I'm expecting two functions to be defined. Then called. One returns a random 
> number. The other user input (guessing the number). 
> 
> I expect the return values to act like variables that I can use in a while 
> loop. 
> 
> The programme asks for the user input then crashes. The error report says 
> 'NameError:The name 'userGuess' is not defined. 
> 
> My understanding is wrong somewhere. I thought functions would allow me to 
> return values I could use elsewhere without having to define them initially. 
> I.e. Encapsulation. 
> 
> I've looked for other examples but get the same issue. I expect a function to 
> return a variable I can use elsewhere. Not sure how to do. In the case below 
> I'm not sure how I can use the work of the function elsewhere. 

You mention "scoping", so... a variable defined in a particular scope is
not visible outside that scope. That's fine, because you then return it,
but what you're returning is the value, not the variable. You need to
save that value.  The "simple fix" is to assign the function returns to
the variables you want, see below:

> Advice welcome. 
> 
> Richard 
> 
> Using Pythonista App on iOS with Python 2.7 on iPhone 5s
> 
> # coding: utf-8
> import random
> 
> #guess number game
> 
> #computer generates random number
> def generateNumber():
>   computerGuess = int(random.randrange(0,101))
>   return computerGuess
> 
> #get user
> def getUser():
>   userGuess = int(input('Guess a number'))
>   return userGuess
>   
> #call for computer and user
> generateNumber()
> getUser()

# try this:
computerGuess = generateNumber()
userGuess = getUser()

# note these two names in the global scope are not
# the same as the identical names in function
# scopes, but there is no clash either, because
# of scoping rules

> 
> #loop to check guess and report
> while userGuess != computerGuess:
>   if userGuess < computerGuess:
>   print('Too low')
>   getUser()
>   elif userGuess > computerGuess:
>   print('Too high')
>   getUser()
>   elif userGuess > computerGuess:
>   print('Correct!')
> 
> #Add counter of guess later
> 
> 
> Sent from my iPhone
> ___
> 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] super constructor usage

2017-03-30 Thread Mats Wichmann


On 03/29/2017 04:02 PM, Mats Wichmann wrote:
> On 03/29/2017 08:33 AM, Rafael Knuth wrote:
> 
>> class A:
>> def __init__(self, message):
>> self.message = message
>> print(message)
>>
>> I then modified the child class B like this:
>>
>> class B(A):
>> def __init__(self, message):
>> print("This is the message from your parent class A:")
>> super(B, self).__init__(message)
>>
>> B("BlaBla")
>>
>> That works, however I am not sure about what exactly happens inside the code.
>> What I am concerned about is whether the argument is being actually
>> inherited from the parent class A or does B overwrite the argument.
>> Can anyone advise what the correct solution would be (in case mine is wrong).
>> Thank you.
> 
> Alan (as usual) already sorted this.
> 
> Just to try to fill in some of these questions - what's inherited,
> overridden, etc., I'm pasting a bit of code I wrote for somewhere else
> to demonstrate what's going on. 

etc.

To make sure there's an even simpler answer than poring through all
those cases (which I think is useful), also try this minimal rewrite of
your example:

class A(object):
def __init__(self, message):
self.message = message + " (decorated by superclass)"

class B(A):
def __init__(self, message):
print("Class B initializer called with %s argument" % message)
super().__init__(message)

b = B("BlaBla")
print("instance message =", b.message)



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


Re: [Tutor] super constructor usage

2017-03-30 Thread Mats Wichmann
On 03/29/2017 08:33 AM, Rafael Knuth wrote:

> class A:
> def __init__(self, message):
> self.message = message
> print(message)
> 
> I then modified the child class B like this:
> 
> class B(A):
> def __init__(self, message):
> print("This is the message from your parent class A:")
> super(B, self).__init__(message)
> 
> B("BlaBla")
> 
> That works, however I am not sure about what exactly happens inside the code.
> What I am concerned about is whether the argument is being actually
> inherited from the parent class A or does B overwrite the argument.
> Can anyone advise what the correct solution would be (in case mine is wrong).
> Thank you.

Alan (as usual) already sorted this.

Just to try to fill in some of these questions - what's inherited,
overridden, etc., I'm pasting a bit of code I wrote for somewhere else
to demonstrate what's going on.  Hope it provides some enlightenment
(it's written for Python3, you'd have to change the super() call if
you're using Python2).

Note that your print(message) in A's initializer doesn't really tell you
much, it just tells you what argument was passed to the initializer.
That would be the same for any function/method, and tells you nothing
about inheritance.

class A(object):
print('Setting class variables in A')
aa_cls = 'class A data'

def __init__(self):
print('A: Initializing instance of', self.__class__.__name__)
self.aa = 'instance of class A'

def ameth(self):
return "A method from class A"

class B(A):
print('Setting class variables in B')
bb_cls = 'class B data'

def __init__(self):
print('B: Initializing instance of', self.__class__.__name__)
super().__init__()
self.bb = 'instance of class B'

print("Begin examination...")
print("Data from classes:")
print("A.aa_cls:", A.aa_cls)
print("B.aa_cls:", B.aa_cls)

print("Instantiating A as a:")
a = A()
print("Instantiating B as b:")
b = B()

print("Data from instance a:")
print("a.aa_cls:", a.aa_cls)
print("a.aa:", a.aa)
print("call ameth directly from a:", a.ameth())
print("Dict a:", a.__dict__)

print("Data from instance b:")
print("b.bb_cls:", b.bb_cls)
print("b.bb:", b.bb)
print("b.aa_cls:", b.aa_cls)
print("call ameth from b:", b.ameth())
print("b.aa:", b.aa)
print("Dict b:", b.__dict__)

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


Re: [Tutor] reading files in Python 3

2017-03-31 Thread Mats Wichmann
On 03/30/2017 11:02 AM, Rafael Knuth wrote:
> I can read files like this (relative path):
> 
> with open("Testfile_B.txt") as file_object:
> contents = file_object.read()
> print(contents)
> 
> But how do I read files if I want to specify the location (absolute path):
> 
> file_path = "C:\Users\Rafael\Testfile.txt"
> with open(file_path) as file_object:
> contents = file_object.read()
> print(contents)
> 
> The above does not work ...

Yeah, fun.  You need to escape the \ that the idiot MS-DOS people chose
for the file path separator. Because \ is treated as an escape character.

Get familiar with the path function in the os module, it will let you do
examinations of file paths, by the way, including constructing them in ways

https://docs.python.org/2/library/os.path.html

simple workaround: use a r letter in front of the string (r for raw):

file_path = r"C:\Users\Rafael\Testfile.txt"
os.path.exists(file_path)

ugly workaround: escape the backslashes so they aren't treated specially:


file_path = "C:\\Users\\Rafael\\Testfile.txt"
os.path.exists(file_path)

you can use os.path.join() to build up a path string in a more
independent way, although it doesn't work quite as expected. To get what
you're asking for, though:

file_path = os.path.join(os.path.expanduser('~Rafael'), 'Testfile.txt')
print(file_path)





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


Re: [Tutor] super constructor usage

2017-03-31 Thread Mats Wichmann
On 03/30/2017 05:39 AM, Rafael Knuth wrote:
 I am trying to wrap my head around the super constructor.
> 
> Is it possible to embed a super constructor into an if / elif
> statement within the child class?
> 
> if message == "string A": return X
> elif: return Y
> 
> How should I modify my code below?
> (I couldn't solve that by myself)
> 
> class A:
> def __init__(self, message):
> self.message = message
> print(message)
> 
> class B(A):
> def __init__(self, message):
> print("This is the message from your parent class A:")
> super(B, self).__init__(message)
> 
> B("BlaBla")

For grins, try this (decorated with prints).  There's an additional
argument allowed to the class B initializer, but set as a default
argument so that if you omit it it defaults to True.

===
class A(object):
def __init__(self, msg):
print('A: Initializing instance of', self.__class__.__name__)
self.message = msg

class B(A):
def __init__(self, msg, doinit=True):
print('B: Initializing instance of', self.__class__.__name__)
if doinit:
super().__init__(msg)

print("Instantiating an A:")
a = A("some message")
print(a.message)

print("Instantiating a B:")
b = B("some message")
print(b.message)

print("Instantiating a B without calling superclass __init__:")
c = B("some message", False)
print(c.message)
===
When you run it:

Instantiating an A:
A: Initializing instance of A
some message
Instantiating a B:
B: Initializing instance of B
A: Initializing instance of B
some message
Instantiating a B without calling superclass __init__:
B: Initializing instance of B
Traceback (most recent call last):
  File "constr-tutor.py", line 22, in 
print(c.message)
AttributeError: 'B' object has no attribute 'message'
===

So note that: the instance attribute "message" is set in the class A
initializer, as in all your postings in this thread.  Just like Alan
pointed out, there are implications if you don't call up to the
superclass, and it shows up pretty clearly here: in the third case,
where we decide not to call the parent's  __init__, this initialization
doesn't happen and the attribute is missing, so accessing it blows up
with an AttributeError exception.


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


Re: [Tutor] Using an XML file for web crawling

2017-03-31 Thread Mats Wichmann
On 03/31/2017 05:23 AM, Igor Alexandre wrote:
> Hi!
> I'm a newbie in the Python/Web crawling world. I've been trying to find an 
> answer to the following question since last week, but I couldn't so far, so I 
> decided to ask it myself here: I have a sitemap in XML and I want to use it 
> to save as text the various pages of the site. Do you guys know how can I do 
> it? I'm looking for some code on the web where I can just type the xml 
> address and wait for the crawler to do it's job, saving all the pages 
> indicated in the sitemap as a text file in my computer. 
> Thank you!
> Best,
> Igor Alexandre

There's a surprisingly active community doing web crawling / scraping
stuff... I've gotten the impression that the scrapy project is a "big
dog" in this space, but I'm not involved in it so not sure.  A couple of
links for you to play with:

http://docs.python-guide.org/en/latest/scenarios/scrape/

the first part of this might be enough for you - lxml + Requests
I just had occasion to look over that page a few days ago, but I'm sure
a web search would turn that up easily

https://scrapy.org/

there are plenty of other resources, someone is bound to have what
you're looking for.


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


Re: [Tutor] reading files in Python 3

2017-03-31 Thread Mats Wichmann
On 03/31/2017 09:44 AM, Alex Kleider wrote:
> On 2017-03-30 13:45, Mats Wichmann wrote:
> 
>>
>> Yeah, fun.  You need to escape the \ that the idiot MS-DOS people chose
>> for the file path separator.
> 
> I also believe that the "MS-DOS people" are making a poor choice
> but to call them idiots is perhaps a bit strong.
> Remember that for many the use of MicroSoft's OS is not a choice but an
> edict handed down by superiors, or a requirement caused by other factors.
> Perhaps "idiot" was meant to apply to the OS, not to it's users?

I'm not sure it's even necessary to clarify, but yes, absolutely - it
was referring to the design choice.

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


Re: [Tutor] Validating String contains IP address

2017-04-01 Thread Mats Wichmann
On 03/31/2017 06:44 PM, Alex Kleider wrote:
> On 2017-03-31 16:35, Ed Manning wrote:
>> What's the best way to validate a string contains a IP address
>> Sent from my iPad
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
> 
> The re module perhaps?
> 
> How about:
> 
> import re
> 
> ip_regex = r"""
> [12]?\d?\d[.]
> [12]?\d?\d[.]
> [12]?\d?\d[.]
> [12]?\d?\d
> """
> 
> ip_pattern = re.compile(ip_regex, re.VERBOSE)
> 
> # then test for ip_pattern.search(source).group():
> res = ip_pattern.search(source).group()
> if res:
> print("IP is {}".format(res))
> else:
> print("Source doesn't contain an IP address")
> 
> # This assumes that an address would never be written as follows:
> 076.191.211.205


This assumes "an IP address" is the four dotted numbers characteristic
of IPv4. These days that's a bad assumption unless you're absolutely
sure an IPv6 address can never appear.  Can you?





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


Re: [Tutor] Asking about Run python script at Startup

2017-04-03 Thread Mats Wichmann
On 04/03/2017 04:20 AM, Alan Gauld via Tutor wrote:
> On 03/04/17 05:34, Quang nguyen wrote:
> 
>> I do not know how to run my python 3 script after my PI2 finished startup.
> 
> This might be a better question for a PI forum since it doesn't
> seem to have anything directly to do with Python.
> 
>> the easy way to run at startup with escape plan?. 
> 
> You will need to define what you want more clearly.
> Do you want your script to start as soon as the PI boots
> up - before you login? Or do you want it to start as soon
> as you login? Or do you want to start it manually as soon
> as you finish logging in?
> 
> Also, if you are running a GUI then you must decide if
> you want the script to start before or after the GUI
> launches.
> 
> (BTW I have no idea what you mean by an escape plan?
> Do you mean stopping the script when you hit Escape?
> Ctl-C is the usual means of doing that)
> 

Indeed, this doesn't even reveal what the RPi is running, since there
are many many options. Presumably it's a linux variant (like Raspbian
which I think is still the "default", been a while since I looked);
there's plenty of information on "initscripts" (older way) and "systemd"
(newer way) if you're looking for a system-level startup script for
Linux, as well as ways to run things at a user level (when you log in,
or when your desktop environment is instantiated if you run one).
Rapsberry PI forums and Linux forums are good places to look.


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


Re: [Tutor] Count for loops

2017-04-03 Thread Mats Wichmann
On 04/03/2017 10:16 AM, Alan Gauld via Tutor wrote:
> On 03/04/17 16:42, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
>> Sorry. That was  stupid of me. The loop does nothing.
> 
> Let me rewrite the code with some different variable names...
> 
 with open(file_path) as a:
 b = a.read()
> 
> with open (file_path) as PI_text:
>  PI_as_a_long_string = PI_text.read()
> 
 for year in b:
> 
> for each_char in PI_as_a_long_string:
> 
 if get_year in b:
 count += 1
> 
>   if get_year in PI_as_a_long_string:
>   count += 1
> 
 print("Your birth date occurs %s times in PI!" % (count))
> 
> if count:
>print("Your birth date occurs in PI, I checked, count, "times!")
> 
> 
> Aren't meaningful variable names great? We should all do
> them more often.


So the takeaways here are:

in the first ("non-counting") sample, there's no need to use a loop,
because you're going to quit after the outcome "in" or "not in" right
away - there's no loop behavior at all.

for year in b:
if get_year in b:
print("Your year of birth occurs in PI!")
break
else:
print("Your year of birth does not occur in PI.")
break

for the counting version you could do something that searches for the
year repeatedly, avoiding starting over from the beginning so you're
actually finding fresh instances, not the same one (hint, hint). There
are several ways to do this, including slicing, indexing, etc.  Alan's
suggestion looks as good as any.

Or, if you don't care about overlapping cases, the count method of a
string will do just fine:

PI_as_a_long_string.count(year)

If you're talking about 4-digit year numbers using a Western calendar in
digits of PI, the overlap effect seems unlikely to matter - let's say
the year is 1919, do we think PI contains the sequence 191919? count
would report back one instead of two in that case. In other cases it
might matter; count is written specifically to not care about overlaps:
"Return the number of (non-overlapping) occurrences"  So that's worth
keeping in mind when you think about what you need from
substrings-in-strings cases.



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


Re: [Tutor] Question about loop and assigning variables

2017-04-06 Thread Mats Wichmann
On 04/05/2017 01:07 PM, Fazal Khan wrote:
> Hello,
> 
> Heres another newbie python question: How can I loop through some data and
> assign different variables with each loop
> 
> So this is my original code:
> 
> def BeamInfo(x):
>   for Bnum in x:
> if plan1.IonBeamSequence[Bnum].ScanMode == 'MODULATED':
> TxTableAngle =
> plan1.IonBeamSequence[Bnum].IonControlPointSequence[0].PatientSupportAngle
> print(TxTableAngle)
> else:
> None
> 
> BeamInfo([0,1,2,3,4,5,6])
> 
> 
> Ideally what I want is this: when Bnum is 0, then "TxTableAngle" will be
> appended with "_0" (eg.TxTableAngle_0). When Bnum is 1 then TxTableAngle_1,
> etc. How do I do this in python?

well... what you're doing now is not very useful, as TxTableTangle goes
out of scope when the function has completed. Which means the work is
just lost.  And the else: clause - if you don't want to do anything here
(the terminology would be "pass", not "None", you don't even need to say
that).

the most likely solution, along the lines of what Alan has suggested, is
to create a list; and then you need to return it so it's actually usable
- just printing the output doesn't leave you with anything other than
characters on the console.  So consider this as a concept (not a working
implementation since there are other things missing):

def BeamInfo(x):
TxTableAngle = []
for Bnum in x:
if blah :
TxTableAngle.append(blah blah)
return TxTableAngle

var = BeamInfo([0,1,2,3,4,5,6])

(of course whenever you have a create-empty-list followed by a loop of
append-to-list you can replace that by a list comprehension)

that gets you back a variable var containing a a reference to a list
("array" if you prefer to think of it that way) you can iterate over.



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


Re: [Tutor] What would be good use cases for the enum module?

2017-04-09 Thread Mats Wichmann
On 04/09/2017 01:54 AM, Alan Gauld via Tutor wrote:
> On 09/04/17 04:00, boB Stepp wrote:
> 
>> understandable to me, but I am having difficulty imagining where I
>> might want to use these features.
>>
> 
> Steven has given the basics, here are a few more real world examples:
> 
> Any kind of status value:
> (open,closed,opening, closing,locked)  - control valve
> (on, off) - light
> (red,green,amber,red-amber) - uk traffic light
> 
> small collections:
> days of week
> months in year
> (cleaning, reception, waiting, valet) - rota duties
> (hourly,daily,weekly,monthly,annual) - schedules

All of these can of course be done without enums.  So the extra benefit
of an enum is that the set is closed (immutable) and requires
uniqueness: picking some other value will be an error, adding a new
enumerator with an already used value is an error.

Not sure if the question really way "what good are enums" or "what good
is the new Python enum module"... in looking that over there seems to be
a lot of stuff, almost seems unlike the Python project to add something
with so many options, that really doesn't have *huge* utility.


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


Re: [Tutor] downloading modules for both python 2 and 3

2017-04-09 Thread Mats Wichmann
On 04/09/2017 02:20 AM, Peter Otten wrote:
> Benjamin Fishbein wrote:
> 
>> I’ve been writing an app using Kivy, and now I want to test it out on an
>> iPhone. However, this can currently only be done in Python 2.
>> https://kivy.org/docs/guide/packaging-ios.html
>>  But when I import kivy in
>> Python2, I get an ImportError. ImportError: No module named kivy So I need
>> to install kivy for Python 2. But when I do:
>> sudo pip install kivy
>> I get the following:
>> Requirement already satisfied: requests in
>> ./anaconda/lib/python3.5/site-packages (from Kivy-Garden>=0.1.4->kivy)
>>
>> Do you know how I can convince my computer to download a module for Python
>> 2 when I already have it for Python 3?
> 
> On my (Linux) system there are multiple versions of pip, called pip2, pip3, 
> pip3.7; you might look for those.
> 
> Or you try to pick the desired interpreter with
> 
> $ sudo /path/to/desired/python -m pip install kivy

I'd highly suggest building a virtualenv for work requiring a specific
project to be installed. When doing that, you can call out the Python
you want involved, something like this sequence I just ran:

$ virtualenv -p /usr/bin/python2 kivywork
Already using interpreter /usr/bin/python2
New python executable in /home/mats/kivywork/bin/python2
Also creating executable in /home/mats/kivywork/bin/python
Installing setuptools, pip, wheel...done.
$ cd kivywork/bin
$ source activate
(kivywork) $ pip install --upgrade pip
Requirement already up-to-date: pip in
/home/mats/kivywork/lib/python2.7/site-packages
(kivywork) $ pip install --upgrade setuptools
Requirement already up-to-date: setuptools in
/home/mats/kivywork/lib/python2.7/site-packages
Requirement already up-to-date: appdirs>=1.4.0 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: packaging>=16.8 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: six>=1.6.0 in
/home/mats/kivywork/lib/python2.7/site-packages (from setuptools)
Requirement already up-to-date: pyparsing in
/home/mats/kivywork/lib/python2.7/site-packages (from
packaging>=16.8->setuptools)
(kivywork) $ pip install kivy
Collecting kivy
  Downloading kivy-1.9.1.tar.gz (16.4MB)
100% || 16.4MB 91kB/s
Complete output from command python setup.py egg_info:
Using distutils

Cython is missing, its required for compiling kivy !


Traceback (most recent call last):
  File "", line 1, in 
  File "/tmp/pip-build-ZXsSua/kivy/setup.py", line 184, in 
from Cython.Distutils import build_ext
ImportError: No module named Cython.Distutils


Command "python setup.py egg_info" failed with error code 1 in
/tmp/pip-build-ZXsSua/kivy/
$


Well, you get the idea.  I couldn't finish the install for the reason
listed.  With a virtualenv you get a controlled environment specifically
for what you want to do; the "activate" step gets it going, and changes
your prompt to show you you're in that environment. Should you need to
clean up now, it's a snap - just remove the virtualenv directory; you
have not messed with your "system" python.


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


Re: [Tutor] (no subject)

2017-04-09 Thread Mats Wichmann
On 04/09/2017 04:42 AM, shubham goyal wrote:
> Hello, I am a c++ programmer and wants to learn python for internship
> purposes. How can i learn the advanced python fast mostly data science
> packages, I know basic python.

Try an internet search?

Don't mean to be snide, but there are lots of resources, including a ton
of books, several courses, tutorials, websites, etc.  For example:

https://www.analyticsvidhya.com/blog/2016/10/18-new-must-read-books-for-data-scientists-on-r-and-python/

We can /possibly/ help you with specific questions here.


Quick hint: you will need to think a little differently in Python than
C++, static vs. dynamic typing, classes work differently, private things
are not really private, etc.


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


Re: [Tutor] counting function calls

2017-04-10 Thread Mats Wichmann
On 04/10/2017 01:55 AM, marcus lütolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR sensor
> with a function and
> I need to count how many times the funtion is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
> count += 1
> print('PIR 1 aktiviert', count)
> return
> 
> try:
> gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
> while True:
> time.sleep(2)
> except KeyboardInterrupt:
> print('PIR deaktiviert')
> 
> PIR 1 aktiviert
> Traceback (most recent call last):
>   File "./PIRex.py", line 9, in mein_callback
> count += 1
> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert
> 
> Tanks for help, marcus.

Yes, what Python does here may be surprising at first: if you only
read-access a global variable in a local (function in this case) scope,
it gives you the value just fine.  If you however try to save something
to a global variable what happens is it creates a local variable,
*unless* you have previously informed Python you mean the global one, by
using the global statement as Alan listed. The specific error you see is
because in order to increment 'count' (which Python has already figured
out has to be local because it will be assigned to) you have to read the
existing value first, but there is no existing value in the local scope.

The Python programming FAQ has a short explanation of why this might be so:

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

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


Re: [Tutor] [PYTHON27] How to save into .npy file?

2017-04-11 Thread Mats Wichmann
On 04/10/2017 07:17 PM, Steven D'Aprano wrote:
> On Mon, Apr 10, 2017 at 02:10:34PM +, Allan Tanaka via Tutor wrote:
>> Hi.
>> Is there a way to save module type data into .npy file that can be used 
>> latter?
> 
> What's "module type data"?
> 
> What's a .npy file?
> 
> To answer your question, literally, the answer is "Yes, of course. 
> Python can save ANY data into a file with ANY file extention". But I 
> guess that answer isn't helpful to you if you need to save specific data 
> to a specific file format.
> 
> But without knowing what that specific data is, and the specific format, 
> how can we answer?
> 
> 
> 

.npy is a (the?) NumPy format.  Sadly, I know no more than that...

maybe this is of use (quick search):

https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html


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


Re: [Tutor] Count for loops

2017-04-11 Thread Mats Wichmann
On 04/11/2017 10:48 AM, Rafael Knuth wrote:

> Thanks for the clarification.
> I tested this approach, and I noticed one weird thing:
> 
> Pi_Number = str(3.14159265358979323846264338327950288419716939)
> Pi_Number = "3" + Pi_Number[2:]
> print(Pi_Number)
> 
> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python Code\PPC_56.py ==
> 3141592653589793

> 
> How come that not the entire string is being printed, but only the
> first 16 digits?

Believe it or not, this is one of the Mysteries of Life (Monty Python
reference since that's what the language is named after... sorry).

To get what you're expecting, you could do this:

import decimal

Pi_Number =
str(decimal.Decimal(3.14159265358979323846264338327950288419716939))

in general, (binary) floats and all other things don't interact the way
we mere mortals might expect, and there's a ton of writing on that
topic. The decimal module documentation contains this pithy comment near
the top:

Decimal “is based on a floating-point model which was designed with
people in mind, and necessarily has a paramount guiding principle –
computers must provide an arithmetic that works in the same way as the
arithmetic that people learn at school.”

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


Re: [Tutor] understanding code testing

2017-04-16 Thread Mats Wichmann
On 04/15/2017 08:33 AM, Rafael Knuth wrote:
> can anyone point me to good learning resources on this subject?
> (python 3)
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

There is a lot of information on the PyTest website - the
talks/tutorials in particular might be interesting.

https://docs.pytest.org/en/latest/


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


Re: [Tutor] Can a virtual environment be renamed?

2017-04-16 Thread Mats Wichmann
On 04/16/2017 10:16 AM, Jim wrote:
> On 04/16/2017 10:10 AM, Chris Warrick wrote:
>> On 16 April 2017 at 16:45, Jim  wrote:
>>> My system python is 2.7.12 so I created a virtual environment using
>>> venu to
>>> run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6
>>> and
>>> put it in env36. Is it possible to change env to env35 for 3.5.2 without
>>> breaking things?
>>
>> No. You need to delete your existing virtualenv and create a new one.
>> You can just use `pip freeze > requirements.txt` in the old one and
>> run `pip install -r requirements.txt` in the new one to ”move” all the
>> packages you had.
>>
>>
> 
> Thanks Chris. I thought that would be the answer but wanted to check
> before I spent a lot of time trying to do something that was not possible.
> 
> Virtual environments tend to confuse me. My system is Mint 18.1 with
> 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6,
> then build it and then use it's version of venv to create a virtual
> environment to try 3.6. Is that correct?
> 
> Thanks,  Jim

It doesn't need to be terribly complicated, something called pyenv can
manage the install for you (yes, it will build it if needed).

pyenv install --list

to show what's available to install

pyenv install 3.6.0

to install a copy

If you set up the shell helpers, pyenv will let you create the
virtualenv and launch it:

pyenv virtualenv 3.6.0 test-3.6.0
pyenv activate test-3.6.0

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


Re: [Tutor] Do not understand code snippet from "26.8. test — Regression tests package for Python"

2017-04-16 Thread Mats Wichmann
On 04/16/2017 10:01 PM, boB Stepp wrote:
> OK, between Alan and Martin I think that I see how to make the code
> snippet actually test a *function* as the snippet seems to suggest.
> Recollect that my original question(s) started:


You got me thinking as well, as I don't much care for unittest, at least
partly because it forces you to use classes even when it doesn't feel
all that natural.

So here's a vaguely practical example of applying the same pattern using
pytest - that is, if you're going to test a function several different
ways, can you use just one test function instead of writing multiples.

First let's write the function to test: it tries to reverse its
argument, which should be something that can be iterated over, using
fancy list slicing.  To show it's working there is also code to try it
out if it is called as a program (as opposed to as a module).

=== reverser.py ==
def slicerev(collection):
return collection[::-1]

if __name__ == "__main__":
print slicerev([1,2,3,4])
print slicerev((1,2,3,4))
print slicerev('abcd')
===

Now write a test for this function, naming it, by convention,
test_{funcname}.py. (if it's named this way pytest can find it
automatically but it's not mandatory, you can give the name of the test
file as an argument).

Import pytest because we need the definition of the fixture decorator;
and import the function we're going to be testing, since it is, after
all, in a different file.

Since what we're factoring here is supplying different sets of data,
decorate a function "slicedata" which will return the data, turning it
into a pytest fixture (there's plenty of information on pytest fixtures
so won't repeat here); supply pairs of values where one value is the
data to call the function with and the other is the expected result of
calling the function under test.

The actual test function should be pretty straightforward.

=== test_slicerev.py ===
import pytest

from reverser import slicerev

@pytest.fixture(params=[
([1,2,3,4], [4,3,2,1]),
((1,2,3,4), (4,3,2,1)),
('abcd','edcba')
])
def slicedata(request):
return request.param

def test_slicerev(slicedata):
input, expected = slicedata
output = slicerev(input)
assert output == expected
===

Run the tests with "py.test test_slicerev.py"

Note the "expected" data for the string type is intentionally incorrect
so you should see an error with some explanatory output.

(you'll probably have to install pytest, since it's not in the standard
library; pytest can run all the unittest style tests too though).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reg. list update

2017-04-17 Thread Mats Wichmann
On 04/17/2017 12:41 PM, Rasika Sapate via Tutor wrote:
> Dear Python group,
> I had written following code.
> 
> super = []
> sub = [""]*3
> other = ["a","b","c","d"]
> sub[0] = "hi"
> sub[1] = "hello"
> for item in other:
> sub[2] = item
> super.append(sub)
> for item in super:
> print item
> 
> 
> Output :
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> 
> 
> Expected output:
> ['hi', 'hello', 'a]
> ['hi', 'hello', 'b']
> ['hi', 'hello', 'c']
> ['hi', 'hello', 'd']
> 
> 
> Is there anything wrong in this code or any feature of python?

yeah, feature of Python.  you could google for "deep copy".

in short, sub[2] ends up with a reference to, not a copy of, the object
referenced by "item" in the first for loop. all four lists hold this
reference. by the time you go to print, that's a reference to the value
"item" held when the first loop exited, or 'd'.  item itself no longer
refers to that, you assign new things to it.

You can see this by adding a couple of debug print lines

super = []
sub = [""]*3
other = ["a","b","c","d"]
sub[0] = "hi"
sub[1] = "hello"
for item in other:
sub[2] = item
print "item id:", id(item)
super.append(sub)
for item in super:
print item
print "item[2] id:", id(item[2])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reg. list update

2017-04-17 Thread Mats Wichmann

>>
>> Is there anything wrong in this code or any feature of python?
> 
> yeah, feature of Python.  you could google for "deep copy".
> 


the reference issue is involved here, but my explanation was off, I
confused myself, listen to Peter instead :)   It's just the same list
four times.




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


Re: [Tutor] classproperty for Python 2.7 (read-only enough)

2017-04-18 Thread Mats Wichmann
On 04/18/2017 04:00 AM, Thomas Güttler wrote:
> I would like to have read-only class properties in Python.
> 
> I found this
> http://stackoverflow.com/questions/128573/using-property-on-classmethods
> But there are a lot of discussions of things which I don't understand.
> 
> I want to be a user of class properties, not an implementer of the details.
> 
> I found this: https://pypi.python.org/pypi/classproperty
> 
> But above release is more then ten years old. I am unsure if it's dead
> or mature.
> 
> I am using Python 2.7 and attribute getters would be enough, no
> attribute setter is needed.
> 
> My use case is configuration, not fancy algorithms or loops.
> 
> Regards,
>   Thomas Güttler
> 

Not clear if you're asking for something more than the standard Python
properties.  The discussion you mention does go into additional
discussion which describes techniques for applying this to a class
attribute. In other words, is this quote a problem for you?

"The get method [of a property] won't be called when the property is
accessed as a class attribute (C.x) instead of as an instance attribute
(C().x). "

If applying to instance attributes is fine for your case, then the
property() call or the related decorators should do the trick, as in:

def get_temperature(self):
return self._temperature

def set_temperature(self, value):
self._temperature = value

temperature = property(get_temperature,set_temperature)

or, as is probably preferred:

@property
def temperature(self):
return self._temperature

@temperature.setter
def temperature(self, value):
self._temperature = value

(obviously both a getter and setter)

Note it's Python convention to use an underscore-prefixed variable name
to indicate it is "private", and you often see a backing store for the
property written like I did above, but nothing in Python enforces this
privacy, someone could fiddle directly with instance._temperature

Also ask yourself whether you really _need_ a property here?  Or would a
public data member be sufficient.  (Just asking, have no idea what's
inside your use case)

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


Re: [Tutor] Visual Studio Community 2017

2017-04-18 Thread Mats Wichmann
On 04/18/2017 11:14 AM, Alan Gauld via Tutor wrote:
> On 18/04/17 17:55, Rafael Knuth wrote:
>> I wanted to start my first project using matplotlib (I have never
>> worked with libraries before). 
> 
> Every time you do an import you are using a library.
> eg
> 
> import sys
> import os
> etc
> 
> It's no big deal.
> 
>> I am trying to get started with VS Community 2017, 
>> and I am having trouble performing the most basic
>> tasks such as installing matplotlib. Anyone here using VS 2017? 
> 
> VS is great for .NET development for Windows but frankly
> for anything else I prefer Eclipse or Netbeans as IDEs.
> But personally I don't much like big greedy IDEs (unless
> I'm writing Java) so I tend to just use a text editor
> (vim or notepad++ on windows) and a Python shell
>  - possibly even IDLE. I also use the Pythonwin IDE
> if I'm doing any COM type work because of its debugger
> and built in COM browser.
> 
> But editors and IDEs are very personal choices. The best
> thing is to download a few and play with them. There is
> no shortage of candidates to pick from!
> 

PyCharm :)

anyway, some thoughts on using VS, which I only recommend if you're
already a dedicated VS user (same general comment as Alan).

"libraries" other than the python standard library do need installation,
which in many cases is done through the PIP tool (on Windows there are
often also pre-built packages installed the normal way, which you can
resort to if something doesn't work using PIP - since you have a full
build environment known to be there with VS 2017, it should work though.

VS has a Python tools addon, which you should install if it's not there
already.

you can then go Tools -> Options -> Python Tools -> Environment Options

look at the paths in the existing environment (matching your installed
Python version) and remember them

create a new environment by clicking Add Environment (the existing one
will probably work, but I don't know how to get around VS's idea it's
fully managing it, and we want to install packages).

in new environment,  fill in the paths.  There's a way to auto-detect
(in a different screen) but on my VS 2015 install at least it seems to
always be greyed out.

You should have a Python Environments on the right, another tab where
there's usually the Solution Explorer.  If it's not open, you can get it
from View -> Other Windows.

pick "pip" from the drop-down, and search for the pkgs you want - just
typing matplotlib should give you a bunch of choices, and that should
also deal with dependencies.  That windo may also offer some existing
pkgs that need updating.


anyway, this sort of thing has worked for me in limited experiments.
Then it's just "import whatever" as Alan says.




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


Re: [Tutor] Visual Studio Community 2017

2017-04-18 Thread Mats Wichmann


...

naturally, far better than what I wrote, is:

https://docs.microsoft.com/en-us/visualstudio/python/python-environments



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


Re: [Tutor] using sudo pip install

2017-04-20 Thread Mats Wichmann
On 04/20/2017 01:24 PM, bruce wrote:
> Hey guys..
> 
> Wanted to get thoughts?
> 
> On an IRC chat.. someone stated emphatically...
> 
> Never do a "sudo pip install --upgrade..."
> 
> The claim was that it could cause issues, enought to seriously
> (possibly) damage the OS..
> 
> So, is this true??

It wouldn't be recommended... if your Python is packaged by your
distribution, you really shouldn't mess with the parts that come with
those packages.  The odds of breaking anything badly are probably low
(especially if what you're upgrading are the typical two - pip and
distutils), but still..

But there's an easy workaround if you want to experiment with newer
stuff, as well as isolate one set of installs from another so they don't
end up fighting over conflicting versions (foo wants bar 13.0 while baz
wants bar 14.0): use virtual environments.  You can safely install and
upgrade whatever you want into a virtualenv, because it's an isolated
location; if it messes up, you can just remove the whole thing and
there's no harm done.


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


Re: [Tutor] Sets question

2017-04-27 Thread Mats Wichmann
On 04/26/2017 06:33 PM, Phil wrote:
> Another question I'm afraid.
> 
> If I want to remove 1 from a set then this is the answer:
> 
> set([1,2,3]) - set([1])
> 
> I had this method working perfectly until I made a change to cure another bug.
> 
> So, I have a set represented in the debugger as {1,2,3} and again I want to 
> remove the one. Only this time the one set is represented as {'1'} and, of 
> course {'1'} is not in the set {1,2,3}.
> 
> Ideally, I would like {'1'} to become {1}. Try as I may, I have not 
> discovered how to remove the '' marks. How do I achieve that?
> 

A little confused... why not just create it the way you want it? How do
you end up with {'1'} ?

Since sets are unordered, you can't use indexing to change a value, but
you can discard a value and add a new value in the form you want.

but Python isn't terribly friendly to identifying if something is a
string... you could do something grotty like this I suppose:


for f in some_set:
if isinstance(f, str):
some_set.discard(f)
some_set.add(int(f))


(top of head, not really experimented with)

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


Re: [Tutor] Difference between %f and %F string formatting?

2017-04-27 Thread Mats Wichmann
F means print it in uppercase. That's really an edge case for a float, that 
would only apply to the special values infinity and not-a-number.

On April 26, 2017 8:08:16 PM MDT, boB Stepp  wrote:
>My Google-fu must be weak tonight.  I cannot find any discernible
>difference between '%f' %  and '%F' %
>.  Is there any or do they duplicate
>functionality?  If the latter, why are there two ways of doing the
>same thing?
>
>I had a similar question for %d and %i, but googling suggests these
>are inherited from differences in handling input in the C language,
>though I could not locate a Python example where there is a need for
>one or the other.  Are there any relevant Python examples?
>
>-- 
>boB
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python to access .txt files stored behind a firewall as .exe files

2017-05-01 Thread Mats Wichmann
On 05/01/2017 03:44 PM, Alan Gauld via Tutor wrote:
> On 01/05/17 18:20, Ian Monat wrote:
>> ...  I've written a script using the requests module but I
>> think a web scraper like Scrapy, Beautiful Soup or Selinium may be
>> required.
> 
> I'm not sure what you are looking for. Scrapy, BS etc will
> help you read the HTML but not to fetch the file. Also do
> you want to process the file (extract the text) in Python
> too, or is it enough to just fetch the file?
> 
> If the problem is with reading the HTML then you need to
> give us more detail about the problem areas and HTML
> format.
> 
> If the problem is fetching the file, it sounds like you
> have already done that and it should be a case of fine
> tuning/tidying up the code you've written.
> 
> What kind of help exactly are you asking for?
> 

This is a completely non-Python, non-Tutor response to part of this:

The self-extracting archive. Convenience, at a price: running
executables of unverified reliability is just a terrible idea.

I know you said your disty won't change their website, but you should
tell them they should: a tremendous number of organizations have
policies that don't just allow pulling down and running an exe file from
a website. Even if that's not currently the case for you, you could say
that you're not allowed, and get someone in your management chain to
promise to support that if there's a question - should not be hard. It
may be wired into the distributor's content delivery system, but that's
a stupid choice on their part.

"Then you have you run the .exe which produces a zipped file"

Don't do this ("run"), unless there's a way you trust to be able to
verify the security of what is offered. Just about any payload could be
buried in the exe, especially if someone broke in to the distributor's site.

Possibly slightly pythonic:

if it is really just a wrapper for a zipfile (i.e. the aforementioned
self-extracting archive), you should be able to open it in 7zip or
similar, and extract the zipfile, without ever "running" it.  And if
that is the case, you should be able to script extracting the zipfile
from the .exe, and then extracting the text file from the zipfile, using
Python (or other scripting languages: that's not particularly
Python-specific).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python to access .txt files stored behind a firewall as .exe files

2017-05-02 Thread Mats Wichmann
On 05/01/2017 06:12 PM, Ian Monat wrote:
> Thank you for the reply Mats.
> 
> I agree the fact that files are wrapped in an .exe is ridiculous. We're
> talking about a $15B company that is doing this by the way, not a ma and pa
> shop.  Anyways...
> 
> If I understand you correctly, you're saying I can:
> 
> 1) Use Python to download the file from the web (but not by using a
> webscraper, according to Alan)
> 2) Simply ignore the .exe wrapper and use, maybe Windows Task Manager, to
> unzip the file and place the .txt file in the desired folder
> 
> Am I understanding you correctly?
> 
> Thank you -Ian

Once you figure out the filename to download - and this may require some
scraping of the page - I'm thinking something like:

import subprocess

downloaded_filename = "something.exe"  # whatever you found to download
cmd = "7z x " + downloaded_filename
res = subprocess.check_output(cmd)

examine res to make sure there was something to extract
then go on and fish file(s) out of the zipfile

I have nothing to experiment with this on, so it's just "thinking out loud".

I have at some point used 7z (and most of the other windows archivers
that you'd consider "third party" can probably do something like)
interactively to fish a zip out of an exe, but there's no reason it
wouldn't work from the command line that I know of.

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


Re: [Tutor] Index Out of Range?List

2017-05-04 Thread Mats Wichmann

> atm_chg.append(float( line.split()[-1] ))
> 
> 
> np.asarray({atm_chg})
> 
> Execution still generates the errors:
> 
> runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py',
> wdir='/home/comp/Apps/Python/Testing')

that means you have a blank line it's reading, the result of splitting
an empty line is an empty list, which you can't index since it has no
members.

$ python
Python 2.7.13 (default, Jan 12 2017, 17:59:37)
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> ''.split()
[]
>>> ''.split()[-1]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range
>>>


you're going to need to do a little input validation, always a good idea
anyway.  that is inside this loop:

  for line in f.readlines():
  atm_chg.append(float( line.split()[-1] ))

check there's something usable in line before you split-and-use it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib ... lost novice's question

2017-05-09 Thread Mats Wichmann
this is one of those things where if what you want is simple, they're all 
usable, and easy. if not, some are frankly horrid.

requests is the current hot module. go ahead and try it. (urllib.request is not 
from requests, it's from urllib)

On May 8, 2017 9:23:15 AM MDT, Rafael Knuth  wrote:
>Which package should I use to fetch and open an URL?
>I am using Python 3.5 and there are presently 4 versions:
>
>urllib2
>urllib3
>urllib4
>urllib5
>
>Common sense is telling me to use the latest version.
>Not sure if my common sense is fooling me here though ;-)
>
>Then, there is another package, along with a dozen other
>urllib-related packages (such as aiourllib). I thought this one is
>doing what I need:
>
>urllib.request
>
>The latter I found on http://docs.python-requests.org along with these
>encouraging words:
>
>"Warning: Recreational use of the Python standard library for HTTP may
>result in dangerous side-effects, including: security vulnerabilities,
>verbose code, reinventing the wheel, constantly reading documentation,
>depression, headaches, or even death."
>
>How do I know where to find the right package - on python.org or
>elsewhere?
>I found some code samples that show how to use urllib.request, now I
>am trying to understand why I should use urllib.request.
>Would it be also doable to do requests using urllib5 or any other
>version? Like 2 or 3? Just trying to understand.
>
>I am lost here. Feeback appreciated. Thank you!
>
>BTW, here's some (working) exemplary code I have been using for
>educational purposes:
>
>import urllib.request
>from bs4 import BeautifulSoup
>
>theurl = "https://twitter.com/rafaelknuth";
>thepage = urllib.request.urlopen(theurl)
>soup = BeautifulSoup(thepage, "html.parser")
>
>print(soup.title.text)
>
>i = 1
>for tweets in soup.findAll("div",{"class":"content"}):
>print(i)
>print(tweets.find("p").text)
>i = i + 1
>
>I am assuming there are different solutions for fetching and open URLs?
>Or is the above the only viable solution?
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flowchart

2017-05-10 Thread Mats Wichmann
On 05/10/2017 05:26 PM, Alan Gauld via Tutor wrote:
> On 10/05/17 00:25, adil gourinda wrote:
>> As you requested, I uploaded my flowcharts on a web storage link as:
> 
> Thanks, although it would have helped if you included
> your original message since I am the only person to
> see it! It never got sent to the rest of the list.
> 
>> "https://app.box.com/s/camaahvmd1yroutfu9ff6xpte44oj1fn";
> 
> They look very pretty and, so far as I can tell at a
> glance, the if and while loop ones are accurate.
> 
> I'm not quite sure what the control one is trying to say.
> It mentions a for loop but you don't provide a pdf for
> that? And the block of code is of course only one subset
> of a nearly infinite number of possibilities.

and it turns out some people don't think flowcharts are really a useful
model... of course, it's a world where there are a zillion different
opinions on things.  I had to hunt a bit to find this one I had read at
some point in the past, take it for whatever it's worth:

https://www.quora.com/Why-is-using-a-flowchart-bad-practice-in-programming



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


Re: [Tutor] cffi version mismatch stalling pip install pygit2

2017-05-14 Thread Mats Wichmann
On 05/12/2017 01:44 PM, MR ZenWiz wrote:
> How do I fix this?
> 
> We are using a newer version of libgit2 than the standard release
> (libgit2.0.25.0 instead of libgit2.0.24.0 - some hard dependency in
> our code).
> 
> However, after I install libgit2 (25), I get this error chain:

If you use a virtualenv (google for instructions if you're not
familiar), you can have all the versions be what they need to be for
this install, without impacting your system versions of things - that's
about the only advice from here.  Although, I tried to install pygit2 in
a virtualenv and it failed, though a bit of a different error, so it may
be the pygit2 project itself is having some issues getting their
dependencies right.

I got this:

raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with error:
command 'gcc' failed with exit status 1

without any hint of *why* gcc failed, probably it was a missing C header
file but haven't researched.

> 
> pip install pygit2
> Collecting pygit2
>   Using cached pygit2-0.25.1.tar.gz
> Complete output from command python setup.py egg_info:
> /usr/lib/python2.7/site-packages/setuptools/version.py:1:
> UserWarning: Module cffi was already imported from
> /usr/lib64/python2.7/site-packages/cffi/__init__.pyc, but
> /tmp/easy_install-HY89WT/cffi-1.9.1 is being added to sys.path
>   import pkg_resources
> 
> Installed 
> /tmp/pip-build-OX9KGK/pygit2/.eggs/cffi-1.9.1-py2.7-linux-x86_64.egg
> /usr/lib/python2.7/site-packages/setuptools/dist.py:378:
> UserWarning: Module cffi was already imported from
> /usr/lib64/python2.7/site-packages/cffi/__init__.pyc, but
> /tmp/pip-build-OX9KGK/pygit2/.eggs/cffi-1.9.1-py2.7-linux-x86_64.egg
> is being added to sys.path
>   pkg_resources.working_set.add(dist, replace=True)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/tmp/pip-build-OX9KGK/pygit2/setup.py", line 210, in 
> **extra_args)
>   File "/usr/lib64/python2.7/distutils/core.py", line 112, in setup
> _setup_distribution = dist = klass(attrs)
>   File "/usr/lib/python2.7/site-packages/setuptools/dist.py", line
> 321, in __init__
> _Distribution.__init__(self, attrs)
>   File "/usr/lib64/python2.7/distutils/dist.py", line 287, in __init__
> self.finalize_options()
>   File "/usr/lib/python2.7/site-packages/setuptools/dist.py", line
> 390, in finalize_options
> ep.load()(self, ep.name, value)
>   File "/usr/lib64/python2.7/site-packages/cffi/setuptools_ext.py",
> line 188, in cffi_modules
> add_cffi_module(dist, cffi_module)
>   File "/usr/lib64/python2.7/site-packages/cffi/setuptools_ext.py",
> line 49, in add_cffi_module
> execfile(build_file_name, mod_vars)
>   File "/usr/lib64/python2.7/site-packages/cffi/setuptools_ext.py",
> line 25, in execfile
> exec(code, glob, glob)
>   File "pygit2/_run.py", line 67, in 
> ffi = FFI()
>   File "/usr/lib64/python2.7/site-packages/cffi/api.py", line 54,
> in __init__
> backend.__version__, backend.__file__))
> Exception: Version mismatch: this is the 'cffi' package version
> 1.10.0, located in '/usr/lib64/python2.7/site-packages/cffi/api.pyc'.
> When we import the top-level '_cffi_backend' extension module, we get
> version 1.9.1, located in
> '/tmp/pip-build-OX9KGK/pygit2/.eggs/cffi-1.9.1-py2.7-linux-x86_64.egg/_cffi_backend.so'.
> The two versions should be equal; check your installation.
> 
> 
> Command "python setup.py egg_info" failed with error code 1 in
> /tmp/pip-build-OX9KGK/pygit2/
> 
> Thanks.
> MR (long time s/w professional but python newb)
> ___
> 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] deleting elements of a dictionary

2017-05-19 Thread Mats Wichmann
On 05/19/2017 11:17 AM, Alan Gauld via Tutor wrote:
> On 19/05/17 15:23, Michael C wrote:
>> list(read_dictionary) converts the dictionary into a list right? How can
>> you save the list as a dictionary?
> 
> Nope, list() produces a new list object containing the
> keys of the dictionary. In the old day(of python 2) you
> used to get the same effect using
> 
> for key in mydict.keys()
> 
> but keys() now returns a funky view of the original dict
> keys and I suspect you'd have the same problems when
> deleting items. So Peter's list() is probably the best
> option.
> 

Or to take another related view:

don't remove items from an iterable while iterating over it: del() is
okay as long as you're not looping over the thing.

Dictionaries have a method for this called pop(), but to my blushes, I
don't really have a lot of experience with it.

What I'd think of just off the bat is build a new dictionary on the fly,
omitting the things you were trying to delete, and then if you like,
save the new dict by the old name (which will cause the old one to have
no references and be dropped.


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


Re: [Tutor] deleting elements of a dictionary

2017-05-20 Thread Mats Wichmann
On 05/19/2017 02:54 PM, Mats Wichmann wrote:
> On 05/19/2017 11:17 AM, Alan Gauld via Tutor wrote:
>> On 19/05/17 15:23, Michael C wrote:
>>> list(read_dictionary) converts the dictionary into a list right? How can
>>> you save the list as a dictionary?
>>
>> Nope, list() produces a new list object containing the
>> keys of the dictionary. In the old day(of python 2) you
>> used to get the same effect using
>>
>> for key in mydict.keys()
>>
>> but keys() now returns a funky view of the original dict
>> keys and I suspect you'd have the same problems when
>> deleting items. So Peter's list() is probably the best
>> option.
>>
> 
> Or to take another related view:
> 
> don't remove items from an iterable while iterating over it: del() is
> okay as long as you're not looping over the thing.
> 
> Dictionaries have a method for this called pop(), but to my blushes, I
> don't really have a lot of experience with it.
> 
> What I'd think of just off the bat is build a new dictionary on the fly,
> omitting the things you were trying to delete, and then if you like,
> save the new dict by the old name (which will cause the old one to have
> no references and be dropped.

Having now done a quick check, mydict.pop() is no better for this case.

Here's a simplistic sample that does work:

d = {
100:3,
200:4,
111:5,
222:5,
333:5,
500:6,
}

print "original: ", d

new = {key:value for (key,value) in d.iteritems() if value != 5}

print "new: ", new

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


Re: [Tutor] Looping through Dictionaries

2017-05-23 Thread Mats Wichmann
On 05/23/2017 11:38 AM, Rafael Knuth wrote:
> I wrote a function (shopping list) which calculates the total price of
> the purchase (quantity * price) as well as the stock change (stock -
> quantity). I know the latter is imperfect (my function does not take
> into account if items are out of stock for example, but that's my next
> challenge. The function does exactly what it's supposed to do:
> 
> def shopping(quantity, price, stock):
> total = 0
> for key in quantity:
> total += quantity[key] * price[key]
> stock_update = stock[key] - quantity[key]
> print(stock_update)
> print(total)
> 
> quantity = {
> "bapple": 10,
> "banana": 20
> }
> 
> price = {
> "bapple": 5,
> "banana": 3
> }
> 
> stock = {
> "bapple": 20,
> "banana": 50
> }
> 
> shopping(quantity, price, stock)
> 
> Now, I want to print the item next to the stock update, and I am
> receiving an error message. I couldn't figure out how to fix that:

in the code below you're trying to use "value" as your key, but it isn't
the key. Why did you change that from the code above?

it helps if you include the errors, by the way :)

> 
> def shopping(quantity, price, stock):
> total = 0
> for key, value in quantity.items():
> total += quantity[value] * price[value]
> stock_update = stock[value] - quantity[value]
> print(key, stock_update)
> print(total)
> 
> quantity = {
> "bapple": 10,
> "banana": 20
> }
> 
> price = {
> "bapple": 5,
> "banana": 3
> }
> 
> stock = {
> "bapple": 20,
> "banana": 30
> }
> 
> shopping(quantity, price, stock)
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] How to deploy seamless script updates to your "clients"?

2017-05-24 Thread Mats Wichmann
On 05/24/2017 04:10 PM, Juan C. wrote:
> I have some Python 3.6.0 scripts that my co-workers use for some small
> and medium tasks. Whenever I have time I fix some bugs and add some
> features to said scripts to make their lives (and mine :D) easier, but
> there's a problem: I need to send a new script via email/chat/whatever
> and they have to replace it wherever they use it, such a hassle.
> 
> How would I go to put a "update module" inside my script? I was
> thinking about using Git, because those scripts are already in
> personal repositories so that I can keep track of changes. Will I have
> to setup any special permissions so that the scripts can pull requests
> from my private repositories?
> 
> I was thinking of something like "check for update before start", if
> an update is found the script would replace itself with the newer
> version and restart, is that possible? For example, 'cool-tool.py'
> v0.2 starts and find that version v0.3 is out, so it downloads and
> replace 'cool-tool.py' code with newer code and restart as v0.3.

Yes, this is definitely a problem others have built solutions for.

It differs a bit depending on whether the script to potentially be
updated is a long-running one or one that can afford to "check on
startup", but not actually that much.

You can use os.execv to restart a script, there are several permutations
but they look something like (pick the bits you need, might not need all
of it)

args = sys.argv[:]
args.insert(0, sys.executable)
os.chdir(foo)  # foo being a saved copy of the directory you start in,
in case the program changes directories while running
os.execv(sys.executable, args)

that's the easy part, though.  self-updating software is tricky... much
easier if you're just talking about a single file, but then what if
updating fails, of if the update itself is broken? Then the user is left
with a non-working setup; you'll have to make sure there's a way to get
back to working that they can figure out how to operate.

For a single file you could put on github, or a local server of course,
and on update check download the file (requests module, perhaps), decide
if that's a new version, if so replace self and restart.  If that's too
expensive you can put in a timer - if it's been a week since the last
update (for example), do the download-and-check.  If neither of those
work, you'll have to build an API that can query versions... that's more
work for you, but maybe worth it.   I think there's an update checker
program somewhere on PyPi, but maybe it only works for things located on
PyPi?



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


Re: [Tutor] How to deploy seamless script updates to your "clients"?

2017-05-28 Thread Mats Wichmann
On 05/27/2017 05:33 AM, M Hashmi wrote:
> That's where Git or other version control systems come in. You can edit or
> upgrade creating a branch and when a branch tested at your side. You can
> push it with new tag like "some module changed". I guess this is how it
> works for everyone. All your team will get replicated code once you merge
> branch. Its simple and its reliable.all your resource only may need to
> work around a dozen shell commands.

Letting git (or mercurial, or some other version control system) handle
this is a nice approach. It doesn't have to be a public server, it can
of course be an inside-company git server.  Endorsed.

===

I did end up curious how hard it would be to write the check code, so
after a little hunting around I put together a simple one (might become
the source for a blog entry someday, or not).  The way this one works is
an update file in yaml format is in a Known Location (I used github),
it's fetched, and saved in a local cache file.  The update file
describes whatever different products are covered, with a version,
checksum, release date, download url, whatever else you need to
describe. In the simpleminded version it just returns true/false as to
whether an update is needed (probably would want to return the url to
download in the "true" case). Each script could import this and call it
with its name as the argument to see if it needs to update itself.

It's not huge, but too big for an email; lives here if anyone is curious:

https://github.com/mwichmann/PyBlog/tree/master/updater.d

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


Re: [Tutor] Problem with if statements and else statements

2017-05-28 Thread Mats Wichmann
On 05/27/2017 06:14 PM, boB Stepp wrote:
> Hello Jalen!
> 
> On Sat, May 27, 2017 at 4:19 PM, Jalen Barr  wrote:
>>
>> In this code it always changes the PlaceHolder to 0 no matter what Month is
>> set to
>>
>> Month ="September"
>>
>> if Month == "January" or "1":
>> PlaceHolder = 0
> 
> This must be written as:
> 
> if Month == "January" or Month == "1":
> PlaceHolder = 0
> 
> The way you wrote it is interpreted as:
> 
> if (Month == "January") or ("1"):
> PlaceHolder = 0

and since "1" is always True, PlaceHolder is always set to 0.

FWIW, if checking for multiples, you could also write:

if Month in ['January', '1']:




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


Re: [Tutor] sub-modules and python3

2017-05-31 Thread Mats Wichmann
On 05/31/2017 11:22 AM, john wrote:
> Hi folks,
> 
> In the past I used a simple "import filename" for sub-modules in python
> 2.  With python 3 I have run into errors reported (file not found) using
> python 2 import statements.  But I'm not asking how to correct the
> import as I am able to change the way I write the import as a work
> around - but I'm importing all the files at once.  What I want to know
> is what is the best practice for my situation.
> 
> Is there a simple way using python 3  to emulate python 2 imports?
> 
> Is there a standard python 3 import tool for sub-modules (files)?
> 
> Is it acceptable to add/change the os path to allow my app to find the
> modules/files?
> 
> Any help or thoughts on the matter is welcome.

try running the 2to3 tool and see what it suggests - I know it's
supposed to know what changes should be made to imports.  You don't have
to accept its' suggestions, of course.


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


Re: [Tutor] New blog that has solution for python programs

2017-06-02 Thread Mats Wichmann
On 06/02/2017 11:27 AM, meenu ravi wrote:
> Hello,
> 
> I'm planning to create a blog that provides solution with explanation for
> python programming challenges available in websites like Hackerearth,
> codecademy, etc., so that if others also share their solution along with
> explanation in the same blog, it will be helpful for beginners. I wanted to
> make sure that it's not illegal to share solution like that. I have seen
> solutions available in different websites. So I hope its legal. But still
> wanted to confirm with views of people in large forum. I felt it may be
> spoon-feeding the programmers, but I was able to find solutions for almost
> all the programs when I searched.

Seems like it helps defeat the purpose of such sites if the answers are
all located in one place...


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


Re: [Tutor] Coming from R, what's a good IDE editor? I've tried PyCharm and Spyder

2017-06-03 Thread Mats Wichmann
On 06/02/2017 11:46 AM, C W wrote:
> Dear Python list,
> 
> I am an R user learning Python. What is a good editor?
> 
> 1) Pycharm
> PyCharm evaluates the entire script, I just want to change a few lines in
> the script.
> For example,
> 
> import matplotlib.pyplot as plt
> import numpy as np
> 
> x = np.arange(0, 1,0.1)
> y = np.sin(2 * np.pi * x)
> 
> plt.figure(1)
> plt.clf()
> plt.plot(x, y)
> plt.show()
> 
> Now, I want to do a scatter plot, but don't want to generate the data
> again. I just want the "line by line" evaluation like in R and Matlab.
> Basically, you can type in console and add to the existing variables.

If you just want an editor, use an editor, not an IDE. An IDE attempts
to understand the totality of your project so it can give you
suggestions on various things e.g. autocompletion for methods and so
forth - as you describe above - and if that's not what you want, don't
use one.

Sadly, vim, which is The Best Editor Ever (see 23 million flamewars for
why such statement can only be a feeble attempt at humor, not reality),
is now trying to behave like an IDE, and it's doing things badly wrong.
For example, if I type import in a "from" line, it helpfully inserts the
word import... meaning those end up with syntax errors, "from foo import
import bar".  I don't know who is responsible for that idiocy and
haven't taken the time to figure out how to shut off the misbehavior.

You're not really talking about an editor with the rest of your
description, though.  You want to type something and have it acted on
right away. The IDEs, and even the almost-IDE programs, can run the
script with a quick key sequence, which is fairly close to what you're
talking about.  Sublime Text and Atom are two that are more editor than
IDE, but still have IDE-like behavior.

All this is just opinions...

Another opinion is Jupyter notebook (formerly iPython notebook) might be
closer to what you're looking for.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New blog that has solution for python programs

2017-06-03 Thread Mats Wichmann

> I don't think "what the authors might want" is the only factor here. 
> Personally, I think these programming challenge sites probably do more 
> harm than good, discouraging people that they're not good enough to be a 
> programmer because they can't solve the (often exceedingly tricky) 
> problems on their own. I think they're often dick-measuring contests, 
> for elite programmers to show off and sneer at "lesser mortals" who 
> can't solve the problems.
> 
> In the real world, nobody has to solve these sorts of problems under the 
> constraints given. In real life programming, you get to look for 
> existing solutions, you get to consult with your colleagues, pass ideas 
> back and forth, etc. If you need a solution to X, and your colleague 
> already solved it for another project, you say "Hey Fred, I'm stealing 
> your code" and if Fred gets upset you talk to his project manager who 
> tells Fred to cooperate.

Indeed... they're a slightly tamer variant of the even worse "clickbait"
articles like "how to answer the 10 top Python interview questions", not
a single one I've ever seen being something I'd expect to be part of a
competent interview process.

However, I still don't like the idea of answering people's quizzes. I
won't violently disagree with Steven's viewpoint, however.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Raspberry pi 2 python help

2017-06-13 Thread Mats Wichmann
On 06/13/2017 08:08 AM, DJ VIN Lom wrote:
> Can i create a script to have my pi change to a certian directory
> automaticlly after booting. I want it to be in a directory so when i ssh
> into it its ready and i dont need to spend time to do it. As well i dont
> want to carry a keyboard mouse and montor
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

There are a ton of ways to do this, and none of the common ones involve
python at all.



The wording "have my pi change to a directory" doesn't match how it
works... each new shell is a new context, so you need to set things upon
entering that context - namely after ssh establishes the connection and
the Pi launches a login shell in response.

Examples:

On the Pi, in your .bashrc, stick a cd command at the end
On the Pi, in your .bashrc define a short alias for the cd you want, so
what you type is very short
On the Pi, set the home directory of the account you are going to ssh
into to be the directory
On your host end, feed a command to ssh that includes doing something at
the other end, along this model:

ssh -t dj@pi 'cd /some/path && exec bash -l'

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


Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm

2017-06-14 Thread Mats Wichmann
On 06/14/2017 12:18 PM, Sibylle Koczian wrote:

> Correct usage would be:
> 
> if myvar == val1 or myval == val2:
> or
> if myvar in (val1, val2):


Just piling on here to say I find the second form very useful to collect
arguments in a "friendly" way, if you don't have a reason to very
rigidly constrain them. For example, if you have an on/off type switch
in your arguments (or "input()" type calls), you can say something like

if myarg in ('T', 't', 'True', 'true', 'Y', 'y', 'Yes', 'yes', '1',
'ON', 'On', 'on'):

Since that's getting too long, we can smash the casing:

if myarg.lower() in ('t', 'true', 'y', 'yes', '1', 'on'):


Of course if you do any serious argument handling, it's better to use
something like optparse (and earlier argparse) module so you're not
reinventing a wheel which has been massively worked on already.

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


Re: [Tutor] __str__ on a subclass

2017-06-19 Thread Mats Wichmann
On 06/19/2017 01:32 PM, Evuraan wrote:
> Greetings!
> 
> 
> #!/usr/bin/python3
> class Employee:
> """Class with FirstName, LastName, Salary"""
> def __init__(self, FirstName,LastName, Salary):
> self.FirstName = FirstName
> self.LastName = LastName
> self.Salary = Salary
> def __str__(self):
> return '("{}" "{}" "{}")'.format(self.FirstName,
> self.LastName, self.Salary)
> class Developer(Employee):
> """Define a subclass, augment with ProgLang"""
> def __init__(self, FirstName,LastName, Salary, ProgLang):
> Employee.__init__(self, FirstName,LastName, Salary)
> self.ProgLang = ProgLang
> def dev_repr(self):
> return '("{}" "{}" "{}" "{}")'.format(self.FirstName,
> self.LastName, self.Salary, self.ProgLang)
> a = Employee("Abigail", "Buchard", 83000)
> print(a)
> dev_1 = Developer("Samson", "Sue", 63000, "Cobol",)
> print(dev_1)
> print(dev_1.dev_repr())
> 
> running that yields,
> 
> ("Abigail" "Buchard" "83000")
> ("Samson" "Sue" "63000")
> ("Samson" "Sue" "63000" "Cobol")
> 
> My doubt is, how can we set the  __str__ method work on the Employee
> subclass so that it would show ProgLang too, like the
> print(dev_1.dev_repr())?
Use super() to call up to the base class, and then add the extra bits
pertaining to the derived class.

That is, add this to your Developer subclass:

def __str__(self):
sup = super().__str__()
return '{} "{}")'.format(sup, self.ProgLang)

You'd need to do a little bit of work to clean up the output, as the
string representation returned by the base class is already closed with
a paren (see second line of output below):

("Abigail" "Buchard" "83000")
("Samson" "Sue" "63000") "Cobol")
("Samson" "Sue" "63000" "Cobol")

but it should show a way to approach this problem, anyway


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


[Tutor] urljoin (was: Re: Tutor Digest, Vol 160, Issue 26)

2017-06-20 Thread Mats Wichmann
On 06/20/2017 02:34 AM, angela ebirim wrote:
> Hi,
> 
> I'm trying to dynamically build a url in python and have tried using:

can see a couple of things...

> 
> #file.py
> 
> import json
> import requests
> from urllib.parse import urljoin
> 
> baseUrl = "
> http://data.parliament.uk/membersdataplatform/services/mnis/members/query";
> search_criteria = "House=Commons"
> outputs = "Constituencies"
> 
> headers = {"content-type": "application/json"}
> 
> 
> *""" so the resulting url: resultUrl should be *
> http://data.parliament.uk/membersdataplatform/services/mnis/members/query/House=Commons/Constituencies
>  *"""*
> 
> *result = search_criteria + outputs*

if you expected a '/' between the two bits here you're going to have to
add it yourself.

> *resultUrl = urljoin(baseUrl + result)*

you would need a comma here instead of a plus, since you're trying to
provide two things to join (I think you'd get a syntax error as written,
so maybe that's a transcription error, not something really wrong in
your code)

plus urljoin often doesn't work the way people expect. In your baseUrl
above you end with /query, and the query piece is going to be stripped
off when urljoin'ing... if the "base" is the path to some page, then
what you join to it will end relative to that location, not to the page
- a trailing slash would change the sense to what I think you're expecting.

Consider something like this:

baseUrl =
"http://data.parliament.uk/membersdataplatform/services/mnis/members/query/";
# house is the one you want to search on
query = "House=%s/Constituencies" % house
resultUrl = urljoin(baseUrl, query)

But you don't really need urljoin for this... you can just format up the
url string yourself, since you don't need any of the special behavior.

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


Re: [Tutor] custom comparator with ordered list

2017-06-26 Thread Mats Wichmann
On 06/26/2017 10:38 AM, Anish Kumar wrote:
> 
>> anish singh wrote:
>>
>>> I need a custom comparator.
>>>
>>> dictionary = {a:[b,c], d:[e,f]}
>>>
>>> If both 'b' and 'e' belong to the same bin

if would help alot if your problem statement included a description of
what "same bin" is.

> Well no, take the case of [1,100] and [2,0]
> Both belong to same bin 

how would we conclude that these "belong to same bin"?


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


Re: [Tutor] how-to generate specific lines of text from two python lists

2017-06-26 Thread Mats Wichmann
On 06/25/2017 12:44 PM, Tahir Hafiz wrote:
> Thanks Alan and Peter,
> 
> Alan you are right this could be solved via an SQL statement but I was
> asked to finish the python script.
> Anyways, this worked and helped to solve the problem in the end:
> 
> # Create iterator object, dictionary which can be used to iterate against.
> b_iter = iter(new_emails)
> 
> 
> print "Creating a list of usernames and email addresses from retreived
> database data:"
> if __name__ == "__main__":
> dictionary = dict(zip(usernames, new_emails))
> my_list = []
> for username in usernames:
> 
>   my_list.append({'username':username, 'email':next(b_iter)})
> 
> print my_list
> 
> print
> print "Creating a file called update_emails.sql with UPDATE statements from
> the list."
> # Open a file in write mode and write the UPDATE sql statements to the file
> # Close the file once iterated against.
> with open('update_emails.sql', 'w') as f:
>for i in my_list:
>  mystring = "UPDATE users set email='{0}' WHERE username='{1}';"
>  new_mystring = mystring.format(i['email'], i['username'])
>  f.write(new_mystring + '\n')
> f.close()

I'd like to point out that with this solution you are creating a
dictionary named "dictionary" but then never using it, and you then
proceed to make a list consisting of dictionaries which each look like a
single record.  Far be it from me to tell you this is wrong since you
report the effort is working out!!! But you do seem to be redoing work.

Consider this as a simplified alternative, which actually uses the
dictionary you create up front (ignoring the very valid "don't do it
this way" comments you have already received, let the database connector
handle the quoting).  Also note you don't need to "close the file once
iterated against", since that's the exact purpose of the 'with'
statement - to handle that cleanup for you.

print "Creating dictionary of usernames and email addresses from
retreived database data:"
if __name__ == "__main__":
dictionary = dict(zip(usernames, new_emails))
print dictionary

print
print "Creating a file called update_emails.sql with UPDATE
statements from the list."
# Open a file in write mode and write the UPDATE sql statements to
the file
with open('update_emails.sql', 'w') as f:
   for key in dictionary.keys():
 mystring = "UPDATE users set email='{0}' WHERE username='{1}';"
 new_mystring = mystring.format(dictionary[key], key)
 f.write(new_mystring + '\n')


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


Re: [Tutor] Fwd: Re: Using files to read data

2017-06-27 Thread Mats Wichmann
On 06/27/2017 05:01 AM, Alan Gauld via Tutor wrote:
> Forwarding to list
> 
> Please always use ReplyAll or ReplyList when responding to list mail.
> 
> 
> 
>  Forwarded Message 
> 
> i apologize.  i guess it didn’t attach correctly.
> my issue is how do i get it out of my file and use it. 
> 
> *the json file, its only about a fifth of it but it should serve its
> purpose*
> [
> 0.9889,
> 0.02,
> "Mon Jun 26 20:37:34 2017"
> ]


A few thoughts here...

suggest storing the time not as a datetime string, but as a time value.
That is, use time.time() to generate it; you can always convert that
value to a string later if needed.

if you're going to write as json, then you should read as json, don't
create your own reader.

in order to get data serialized in a more usable form, you could define
a class, and serialize the class instances, this way you get the
variable name stored along with the data. Since json only understands a
limited number of data types, one cheap approach is to fish out the
dictionary of data from the instance object - json does understand
dicts. I'm using vars() for that.  So here's a cheap example, not
fleshed out to use any of your code:

import time
import json

class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.time = time.time()

# create a few points
A = Point(0.03, 0.9777)
B = Point(0.02, 0.9889)

print(json.dumps(vars(A)))
print(json.dumps(vars(B)))

You'll see you get formatted data that json.loads() ought to be able to
make use of:

{"y": 0.9777, "x": 0.03, "time":
1498577730.524801}
{"y": 0.9889, "x": 0.02, "time":
1498577730.524802}

You don't need a class for that, you can just build the dict yourself,
it was just a cheap way to illustrate.

Simulated read:

 >>> import json
 >>> point = json.loads('{"y": 0.9777, "x":
0.03, "time": 1498577980.382325}')
 >>> print(point['x'])
 0.0
 >>> print(point['y'])
 0.9778
 >>> print(point(['time'])
 1498577980.38
 >>>


I wouldn't open/close the json file you're writing to each time, that
seems a bit wasteful.

And do take on board some of the refactoring suggestions already made.

Dividing the heading by 90 using integer division (//) will give you
four possible values, 0-3, you can then base your definitions/decisions
on that, instead of your "if heading in range(1, 91):"  selections.
range actually generates the values, which you don't really need.

Best of luck!



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


Re: [Tutor] Query regarding output

2017-06-29 Thread Mats Wichmann
On 06/29/2017 03:02 AM, Alan Gauld via Tutor wrote:
> On 29/06/17 03:14, shubham goyal wrote:
> 
>> This Question is asked in some exam. i am not able to figure it out.
>>
>> a = [0, 1, 2, 3]
>> for a[-1] in a:
>> print(a[-1])
>>
>> its giving output 0 1 2 2
>>
>> it should be 3 3 3 3 as a[-1] belongs to 3.
>> can anyone help me figuring it out.
> 
> This is quite subtle and it took me a few minutes to figure
> it out myself.
> 
> It might be clearer if we print all of 'a' instead
> of a[-1]:
> 
 for a[-1] in a:
> ...print(a)
> ...
> [0, 1, 2, 0]
> [0, 1, 2, 1]
> [0, 1, 2, 2]
> [0, 1, 2, 2]
> 
> What is happening is that a[-1] is being assigned the value
> of each item in a in turn. The final iteration assigns a[-1]
> to itself, thus we repeat the 2.


Ugh.  I guess on an exam where they're trying to see if you can tease it
out, as you may one day have to debug such a sequence... but don't write
code like that.  One of the reasons people like "functional programming"
is it avoids these kind of side effects.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Installing Python3.6.1 on Ubuntu 16.04.2

2017-07-02 Thread Mats Wichmann
what was the error? nothing came through

On July 2, 2017 9:06:07 AM MDT, Joseph VOGTEMBING via Tutor  
wrote:
>I have a fresh install of Ubuntu 16.04.2, on which I try to install
>Python3.6.1, and I have done this multiple times in the past, but for
>some reason I tried it 3 times since yesterday but I kept having the
>same error message. here are the steps that i have taken for my
>installation.
>mariejosv@ubuntu:~$  sudo apt-get update
>mariejosv@ubuntu:~$  sudo apt-get upgrade
>mariejosv@ubuntu:~$ wget
>https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
>
>
>mariejosv@ubuntu:~$ tar xvf Python-3.6.1.tar.xz
>
>mariejosv@ubuntu:~$ sudo apt-get installbuild-essential checkinstall   
>
>mariejosv@ubuntu:~$ sudo apt-get installlibreadline-gplv2-dev
>libncursesw5-dev libssl-dev libsqlite3-dev tk-devlibgdbm-dev libc6-dev
>libbz2-dev   
>
>mariejosv@ubuntu:~$ cd Python-3.6.1
>
>mariejosv@ubuntu:~/Python-3.6.1$ ./configure   
>mariejosv@ubuntu:~/Python-3.6.1$sudo make altinstall  # after this
>line, the following message will popup at some point
>
>
>
>
>Please help.
>Thanks
>Joseph
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionaries are same but returning false

2017-07-05 Thread Mats Wichmann
On 07/05/2017 11:09 AM, Marc Tompkins wrote:
> On Wed, Jul 5, 2017 at 9:51 AM, Ashfaq  wrote:
> 
>> Hi Peter,
>> The way you find the issue is really cool! Very cool! :)
>>
>>
> I agree - that is very cool.  But I have also made this sort of mistake a
> few times, and found it by using a very quick, low-tech method...
> "Unfold" the lines of the two dictionary specifications and put them one
> above the other - I usually just cut'n'paste into a text editor and delete
> the newlines.  If the two unfolded lines don't line up (which these
> wouldn't, because one has extra quotes in it) the error will be immediately
> visible.  Subtler typos will be harder to spot, but still much easier than
> trying to compare two folded paragraphs several lines apart.
> 
> Not nearly as sophisticated, but sometimes quick'n'dirty is best.

but not terribly useful for dictionaries, which don't have any sense of
order (unless, of course you sort first, or use an ordered dict)


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


Re: [Tutor] Why use main() ?

2017-07-05 Thread Mats Wichmann
On 07/05/2017 09:45 AM, Zachary Ware wrote:
> On Wed, Jul 5, 2017 at 10:37 AM, David Rock  wrote:

>> I personally find using main() cumbersome, but many examples I come
>> across use main().  Is there some fundamental benefit to using main()
>> that I'm missing?
> 
> In no particular order: testing, encapsulation, and reusability.  With
> a "main()" function (which, recall, can be named whatever you like; it
> doesn't have to be "main") you can directly call the function in your
> tests to make sure it acts the way you want.  The encapsulation of the
> "main" code in a "main()" function also reduces your global state (and
> makes global state a bit more difficult to use), which is usually a
> good thing.  And finally, it makes it possible to use the "main()"
> function in some other piece of code that imports it.
> 

As a vaguely contradictory position to a part of this (which I in the
main agree with): if your objective is to make a module, and also have
some code (perhaps including test code) which is run in the non-module
(aka not-imported) case, then stuffing that code in a function main()
means you've exposed that not-really-module-code as part of the module,
and might then want to take steps to hide it from clients so it doesn't
end up looking like part of the module API.

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


Re: [Tutor] Which DB use with standalone desktop app

2017-07-06 Thread Mats Wichmann
On 07/06/2017 11:25 AM, Zachary Ware wrote:
> On Thu, Jul 6, 2017 at 3:57 AM, Freedom Peacemaker  
> wrote:
>> Hi Tutors,
>> I am working on standalone desktop app with tkinter GUI (Python3), and i
>> dont know which database should i use. I've tried to find solution on my
>> own but google cant help me. There are some with SQL in name (eg. sqlite3,
>> MySql), but there are some other NoSql like MongoDB or Redis. Please help
>> me which one i should use for my app not only from ones i've mentioned. My
>> database will have max 100 records described by 6-8 columns. Most of them
>> will be 25 characters max but one will have up to 60.
> 
> That sounds small enough that you probably don't even need a database,
> but could just store a JSON file with your data, for example.
> Otherwise, I'd suggest sqlite3; it's very lightweight and intended for
> single-user applications like this.  You definitely don't need
> anything as large as MySQL or MongoDB :)
> 
> Hope this helps,
> 

You don't really say what the use model is for this "database".
Lightweight manipulation of a single table (which is what your
description hints at) can be done just fine in Python (without resorting
to an external db engine) and be given persistence by using a simple
file - json or yaml format, or even Python's included pickle format, as
Zachary says.


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


Re: [Tutor] @property vs @classmethod

2017-07-08 Thread Mats Wichmann
On 07/08/2017 06:56 PM, Steven D'Aprano wrote:

> The pythonic way is not to use them at all.
> 
> For experts only: you'll know when you need them.
> 
> They really aren't even a little bit similar, if you thought they did 
> that just means that you haven't understood what they do.
> 
> property is for making computed atttributes. 
...
> which people can then assign to, read or even delete. But occasionally 
> you need to run some code whenever instance.x is accessed, and that's 
> when you should use property.

When I use them (rarely), it's seemed to make sense when there's an
attribute which naturally has a relationship to another attribute and it
seems better to store one and compute one on demand rather than store
both as instance attributes and have to update both when either changes.
 I'll admit that this has happened most often when writing a blog post
trying to explain properties :)

>From OO people, though, we get the sputtering But... But... what about
encapsulation, data hiding, etc?

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


Re: [Tutor] Image i/o in python

2017-07-16 Thread Mats Wichmann
On 07/16/2017 10:13 AM, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote:
> In python we have a set of imread and imshow in skimage. In matplotlib.image
> we again have imreadand imshow functions. In scipy.misc we again have
> another set imread and imshow. Are there anyfunctional differences between
> these multiple sets to justify their presence? …
> 
> regards,
> Sarma.

I've got good news for you, Sarma: there's an imread in OpenCV as well.
And I think there's at least one other set, plus I recall there's a
standalone imread package available in PyPi.

Each one of these is an independently developed project and they can
choose whatever they want to call their functions. Not that that helps
someone trying to pick one. Whether some are more useful than others, or
if any are useful in a context outside their own project... I'll leave
that to others to comment (or search the internet)


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


Re: [Tutor] Python Questions

2017-07-18 Thread Mats Wichmann
On 07/18/2017 11:42 AM, Alan Gauld via Tutor wrote:
> On 18/07/17 11:41, Max Smith wrote:
> 
>> What's the easiest way to learn python currently 
> 
> Write a lot of code.
> 
> As to which tutorial to follow, that's a very personal choice and
> depends on your previous knowledge and learning style. If you can
> already program in a similar language(say Perl, PHP or Javascript)
> then the official tutorial is just fine. If you are a comp-lete
> programming neophite then use one of the non programmers
> tutorials on the python web site (eg mine :-)
> 
> You can start with some of the many YouTube video courses if you
> prefer but none of these will give you the depth that a
> written tutorial will.

Absolutely, write code.  Some of the tutorials try hard to give you
"real" problems to solve, but they're by their nature prepared to
illustrate some point. It really helps if you supplement by using Python
to try to solve some distinct problem that interests you, because
ultimately what counts is whether you can apply your new knowledge to a
brand new situation, not one that's been hand-crafted by an author. If
you're doing that and get stuck, this is a place that can help with the
unsticking...

I'll just end up parroting Alan so I'll defer mentioning how hard it is
to choose "the best" "the easiest" "the fastest".  Do look at his
material by all means.

Google certainly knows what they're doing with Python, nothing wrong
with pursuing their stuff.

A python learning site that happens to appeal to me (one person's
opinions, and all that) is: http://www.python-course.eu/

AND there's actually one site that claims it is addressing the Computing
GCSE, http://usingpython.com/ - this one I have never looked at but it
might be worth a glance since that's the direction you're coming from.



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


Re: [Tutor] if/else statement

2017-07-18 Thread Mats Wichmann
And one more, the 'if' needs a colon at the end

On July 18, 2017 5:10:30 PM MDT, Alan Gauld via Tutor  wrote:
>On 18/07/17 18:31, Shane Johnson (shanejoh) wrote:
>
>> def greater_less_equal_5(answer):
>>if answer is '>' 5
>>return 1
>>elif answer is < 5:
>>return 0
>>else:
>>return 4
>
>> I’m getting a invalid syntax line 2 error. Any assistance is greatly
>appreciated.
>
>Thee are two problems.
>
>1) 'is' is a problem, you don't need it here. 'is' is an operator
>for testing whether two object references are to the same
>actual object
>eg.
>
>x = 42
>y = x   # y and x both refer to the same number
>if x is y: print 'yes!'
>
>You don't use it in mathematical comparisons so your code
>should look like:
>
>   if answer > 5
>  return 1
>   elif answer < 5:
>  return 0
>   else:
>  return 4
>
>Notice I also removed the quotes around the > sign and
>added indentation to the return statements which leads
>us to...
>
>2) You don't have any indentation in the function body.
>Indentation is all important in Python, it's how the
>interpreter knows where the conditional block starts
>and stops.
>
>HTH
>-- 
>Alan G
>Author of the Learn to Program web site
>http://www.alan-g.me.uk/
>http://www.amazon.com/author/alan_gauld
>Follow my photo-blog on Flickr at:
>http://www.flickr.com/photos/alangauldphotos
>
>
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unitest with random inputs

2017-07-19 Thread Mats Wichmann
On 07/19/2017 10:55 AM, Sydney Shall wrote:
> On 19/07/2017 18:42, Steven D'Aprano wrote:
>> On Wed, Jul 19, 2017 at 05:01:53PM +0200, Sydney Shall wrote:
>>
>> [...]
>>>   def test_zero_in_capitalsadvanced(self):
>>>  self.assertIn(self.capitalsadvanced, 0.0)
>>>
>>> The error message is:
>>>
>>> Traceback (most recent call last):
>> [...]
>>> in assertIn
>>>  if member not in container:
>>> TypeError: argument of type 'float' is not iterable
>>
>> You are trying to test whether capitalsadvanced is in 0.0. Reverse the
>> arguments:
>>
>>  self.assertIn(0.0, self.capitalsadvanced)
>>
>> which will test whether 0.0 is in self.capitalsadvanced.
>>
>>
>>> FAILED (failures=9, errors=1)
>>>
>>> The failures all arise from a 'nan'.
>>> It is this problem that I am trying to resolve.
>>
>> Well, since you don't show us what those failing tests are, we cannot
>> possibly tell you how to fix them.
>>
>> Start by showing us *one* failing test, and what the failure is.
>>
>>
> Thank you Steve.
> 
> The remaining 'nan' problems are shown below.
> 
> runfile('/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py',
> wdir='/Users/sydney/Capital/Capital_with_productivity/Current_Versions')
> /Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1582:
> RuntimeWarning: invalid value encountered in true_divide


The thing to remember is that NaN is actually... _not_ a number,
literally.  If you like to think in terms of exceptions, then NaN is lan
exception - some thing caused a result which cannot be represented as a
number, and so this magical value is used to tell you.  Thus, no numeric
operations can be done on it.  This is not from Python... this is the
way it was defined in the IEEE standard (754 if memory serves), Python
just tries to implement the requirements of that standard as best it
can.  (turns out Python actually has two flavors: a quiet NaN, and a
signaling NaN).

sorry there wasn't much Python content in this message :)




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


Re: [Tutor] centos 7 - new setup.. weird python!

2017-07-19 Thread Mats Wichmann
On 07/19/2017 02:48 PM, bruce wrote:
> Hi.
> 
> Testing setting up a new Cnntos7 instance.
> 
> I ran python -v from the cmdline...  and instantly got a bunch of the
> following! Pretty sure this isn't correct.
> 
> Anyone able to give pointers as to what I've missed.

It is expected, actually. You perhaps intended a capital v.  The
lowercase one means this:

   -v Print  a  message each time a module is initialized,
showing the
  place (filename or built-in module) from  which  it  is
loaded.
  When  given twice, print a message for each file that is
checked
  for when searching for a module.  Also provides
information  on
  module cleanup at exit.


so you asked it to tell you  what it was doing in extra detail, and it
did :)

> 
> thanks
> 
> python -v
> # installing zipimport hook
> import zipimport # builtin
> # installed zipimport hook
> # /usr/lib64/python2.7/site.pyc matches /usr/lib64/python2.7/site.py
> import site # precompiled from /usr/lib64/python2.7/site.pyc
> # /usr/lib64/python2.7/os.pyc matches /usr/lib64/python2.7/os.py
> import os # precompiled from /usr/lib64/python2.7/os.pyc
> .
> .
> .
> ___
> 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] Problems with pytz module

2017-07-19 Thread Mats Wichmann
> On 19/07/17 20:58, Daniel Bosah wrote:

don't see a lot of benefit to using pytz here... just my opinion.  the
question does give a chance to annotate the example with some thoughts,
though; take them for what they're worth.

import datetime
import pytz

class Account:
"""Simple account class with balance"""
# 1. if you set up balance param with a default value, you can skip
#the argument if account is created with no balance
#def __init__(self, name, balance):
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.transaction_list = []
# 2. seems to make sense to report initial balance
#print "Account created for " + self.name
print "Account created for " + self.name + ", initial balance" +
balance

def deposit(self,amount):
# 3. to avoid cascading indents, bail on "not applicable",
#rather than indenting a whole function behind "applicable"
#if amount > 0:
if amount <= 0:
# 4. do you want to indicate this call was a problem somehow?
return

self.balance += amount
# 5. it is not very interesting to just dump a balance.
#Either add indication it's a deposit/withdrawal and amount,
#or just omit, leaving caller to print balance if they want.
#self.show_balance()
# 6. the pytz part is just adding confusion. In the log, store the
#utc time.
# 7. suggest put the simpler/more important value first in the
log entry

#self.transaction_list.append((pytz.utc.localize(datetime.datetime.utcnow()),
amount))
# appends traction details to list
self.transaction_list.append((amount, datetime.datetime.utcnow()))

def withdrawl(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
else:
print "The account must be greater then zero and no more
then your account balance"
#self.show_balance()
# 8. record a transaction on withdraw as well. Make it negative
#as show_transactions method triggers on that.
self.transaction_list.append((-amount, datetime.datetime.utcnow()))

def show_balance(self):
print "Balance is {}".format(self.balance)

def show_transactions(self):
# 9. Presumably translog print is rare, let's say what we're doing
print "Transaction log:"
# after note #7, unpack in other order
#for date, amount in self.transaction_list:
for amount, date in self.transaction_list:
if amount > 0:
tran_type = "deposited"
else:
tran_type = "withdrawn"
amount *= -1 # to show negative number
# 10. Assuming you wanted to print in either case, change indent
# print "{:6} {} on {} (local time was
{})".format(amount, tran_type, date, date.astimezone())
print "{:6} {} on {} UTC".format(amount, tran_type, date)
# can add timezone-relative display back in if you wish

if __name__ == '__main__':
# after note #1, can leave out a zero initial balance
#tim = Account("Tim", 0)
tim = Account("Tim")
tim.show_balance()


tim.deposit(1000)
tim.show_balance()
tim.withdrawl(500)
tim.show_transactions()

tim.show_balance()

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


Re: [Tutor] Quick Pythonic Style Tips

2017-07-22 Thread Mats Wichmann
On 07/22/2017 07:46 AM, Alan Gauld via Tutor wrote:
> On 22/07/17 12:20, Abdur-Rahmaan Janhangeer wrote:
> 
>> As a user switching between some languages, it took sometimes before i
>> discovered that there was a styling guide in python
> 
> There are style idioms in most languages although not always
> written down as clearly as in PEP8. That having been said
> they should be viewed as guides not rules. In addition there
> are often local style guides that must be followed in
> a particular company.
> 
>> i'd like to know if there was a specific C++ or java> style of doing things 
>> which should be avoided ?

I'd like to contibute a rather different sort of tidbit to what Alan
wrote: be really careful about using mutable data types in function
calls, as class variables, and just in general.  Here's a quick example
of a classic "trap":

# append value to list, if list omitted return a new list
def func(val, alist=[]):
alist.append(val)
print alist
return alist

func(1)
func(2)
func(3)

pop quiz :)  what is the output?

C++ has default arguments as well, so the output might be surprising in
that context:

[1]
[1, 2]
[1, 2, 3]

Instead of you getting a new empty list each time 'func' is called
without a second argument, the default list is part of the function.
Python runs the function code when it comes across it, creating a
function object which is then used each time the function is called, so
this initially empty list is reused each time.

To move the instantiation of the list to run-time, you could recode like
this:

def func(val, alist=None):
if not alist:
alist = []
alist.append(val)
print alist
return alist

func(1)
func(2)
func(3)


This is really a bit of "Python style" (using None as the default to act
as a flag to do something special) that may not be reflected in the code
format parts of style guides.


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


Re: [Tutor] new to python

2017-07-23 Thread Mats Wichmann
On 07/23/2017 09:16 AM, Alex Kleider wrote:
> On 2017-07-23 01:06, Anish Tambe wrote:
>>> for line in file:
>>
>> This line is not required as the you have opened your file to 'f'.
>> 'file' is a built-in class. Type -
>> help(file)
>> on the interpreter to know more about it.
> 
> This appears to be true in python2x but not in python3:
> 
> 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.
 help(file)
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'file' is not defined
 exit()
> alex@X301n3:~$ python
> Python 2.7.6 (default, Oct 26 2016, 20:32:47)
> [GCC 4.8.4] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 help(file)
> Help on class file in module __builtin__:
> 
> class file(object)
>  |  file(name[, mode[, buffering]]) -> file object
>  |
> ...

It is nonetheless still true that Python provides context manager
support for file objects that behave the same way as described (that is,
when handle - called 'f' in the example above - goes out of scope, it is
closed for you).  Otherwise, the relevant documentation on file objects
is now in the IO discussion:

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

> Also puzzling is that the 'intro' to python2 declares itself to be 'on
> linux2' vs just 'on linux' in the case of python3.  (Something I'd not
> previously noticed.)

That's just a cleanup of an old issue, Python3 dropped the "linux2"
thing (which was never a great idea, linux kernels are now 4.x after 2.x
lived for a very long time, Python never followed those changes nor did
it need to);

FWIW, the preferred method now to check if a host is linux is to do:

if sys.platform.startswith("linux"):

instead of checking explicitly for a string "linux", "linux2", etc.



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


Re: [Tutor] class newbie

2017-07-23 Thread Mats Wichmann
On 07/23/2017 02:42 PM, Michael C wrote:
> never mind, I forgot to put 'self' in the method definition!

class mahschool:
def print(self):
print('Say something')


a = mahschool()

a.print()

Indeed.  The error message was clear on this - but not in a way that's
always instructive until you're used to it :)

"TypeError: print() takes 0 positional arguments but 1 was given"

A method is called "silently" (you didn't pass it yourself as an
argument when you called print()) with the instance, so you need to
declare such a parameter in the method definition.

And to give myself an excuse for preaching: it's usually not a great
idea to reuse the name of a built-in function.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic decorator question

2017-07-24 Thread Mats Wichmann
On 07/24/2017 08:33 AM, bruce wrote:
> Hi.
> 
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
> 
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.
> 
> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?
> 
> But as a start, if you have pointers to any really "basic" step by
> step sites/examples I can look at, I'd appreciate it. I suspect I'm
> getting flumoxed by something simple.

wrap and return are not two distinct things, they're part of the same
process...  the general concept is that a decorator changes the result
of a function without modifying the function itself by returning a new
function object which does some other stuff in addition to running the
code of the original function object.

This is a really simple wrapper:

def my_decorator(some_function):
def wrapper():
print("Stuff happening before some_function() is called.")
some_function()
print("Stuff after some_function() is called.")
return wrapper

If you have an unwrapped function:

def foo():
print "This is the unwrapped function"

You can show this in action like this:

foo()
bar = my_decorator(foo)
bar()

function names are just handles to the function object, so the middle
line of those three is passing the original function object referred to
by foo to my_decorator, whose inner function returns a function object
which is runs some code before and after the original function.  If the
undecorated fuction does not need to be referred to, the previous often
gets written as:

foo = my_decorator(foo)
foo()

Now to add Python's magical decorator syntax:

@my_decorator
def bar():
print "This is another unwrapped function"

bar()

So all the @my_decorator bit does is provide shorthand for the syntax

bar = my_decorator(bar)

Wasn't ultra-clear on your original question; if you wanted the
"happening before" and "happening after" to call out to other functions
instead of doing a print, you can. Is that what you mean by multiple
internal functions?

Does this clarify at all?

Do hunt some, there are some really good tutorials on decorators.

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


Re: [Tutor] new to python

2017-07-24 Thread Mats Wichmann
On 07/24/2017 04:32 PM, N6Ghost wrote:

> update code:
> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
> for line in f:
> for line in f:
> print(line.rstripe())
> 
> f.close()
> 
> 
> C:\coderoot\python3\level1>python secondscript.py
> Traceback (most recent call last):
>   File "secondscript.py", line 5, in 
> print(line.rstripe())
> AttributeError: 'str' object has no attribute 'rstripe'

You presumably meant 'rstrip' (strip from right) rather than 'rstripe'.
With errors like this, look in the documentation to see the available
methods:

https://docs.python.org/3/library/stdtypes.html#string-methods
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommended Python Compiler

2017-07-30 Thread Mats Wichmann
since this all opinions :), I don't think idle is worth bothering with. for 
editor that can do ide like things, consider atom (free, get a bunch of 
plugins) or sublime text (not free). for a full ide, pycharm is great 
(community edition free). for a lightweight ide to get started, i liked thonny 
when i trialed it at somebody's request, but do look at that wiki page, tons of 
choices there.

On July 30, 2017 6:09:20 PM MDT, Alan Gauld via Tutor  wrote:
>On 30/07/17 23:22, George Sconyers via Tutor wrote:
>> ...looking for a recommended compiler for an Ubuntu environment. 
>
>In programming precision is everything.
>
>You are not in fact looking for a compiler, you are
>looking for a development environment or IDE.
>
>A compiler takes source code and produces executable
>machine code. C-Python does not have such a thing
>(it uses an interpreter to translate the code at runtime)
>although you an get one for the Java based Jython.
>But that's not really what you are asking for...
>
>> ...using gedit but don't get the benefit of auto-indentation > and
>color coding of key words.
>
>These are feature of the editor (usually a component of an IDE)
>- and gedit can do the syntax colouring, I'm not sure about the
>auto-indent... But rather than use gedit I suggest you use
>IDLE which is a simple but useful Python IDE built in Python.
>
>> ...something that facilitates debuggig and stepping through code. 
>
>IDLE does all of the above.
>
>You can get it via the Ubuntu software manager or Synaptic or
>apt-get...
>Make sure you get the right version for your Python version
>
>There are many other IDEs for Python, right up to professional tools
>like Eclipse and Netbeans but IDLE is a good starting point. And
>there are lots of YouTube videos to get you started.
>
>HTH
>-- 
>Alan G
>Author of the Learn to Program web site
>http://www.alan-g.me.uk/
>http://www.amazon.com/author/alan_gauld
>Follow my photo-blog on Flickr at:
>http://www.flickr.com/photos/alangauldphotos
>
>
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pythonic ascii decoding!

2017-07-31 Thread Mats Wichmann
On 07/31/2017 09:39 AM, bruce wrote:
> Hi guys.
> 
> Testing getting data from a number of different US based/targeted
> websites. So the input data source for the most part, will be "ascii".
> I'm getting a few "weird" chars every now and then asn as fas as I can
> tell, they should be utf-8.
> 
> However, the following hasn;t always worked:
> s=str(s).decode('utf-8').strip()
> 
> So, is there a quick/dirty approach I can use to simply strip out the
> "non-ascii" chars. I know, this might not be the "best/pythonic" way,
> and that it might result in loss of some data/chars, but I can live
> with it for now.
> 
> thoughts/comments ??

It's easy enough to toss chars if you don't care what's being tossed,
which sounds like your case, something like:

''.join(i for i in s if ord(i) < 128)


but there's actually lots to think about here (I'm sure others will jump in)

- Python2 strings default to ascii, Python3 to unicode, there may be
some excitement with the use of ord() depending on how the string is
passed around
- websites will tell you their encoding, which you could and probably
should make use of
- web scraping with Python is a pretty well developed field, perhaps you
might want to use one of the existing projects? (https://scrapy.org/ is
pretty famous, certainly not the only one)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error with sqlalchemy

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

this is not viewable, at least not here.

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

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


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

2017-08-02 Thread Mats Wichmann
On 08/01/2017 07:14 PM, Ben Finney wrote:
> boB Stepp  writes:
> 
>> A quick scan of some of my Python books does not turn up the use of
>> "/" as a function argument.
> 
> The appearance of this in Python's documentation and dfunction signature
> descriptions, without a clear description of what it means, is
> troubling.
> 
> The best I can find is this informational draft PEP
> https://www.python.org/dev/peps/pep-0457/>, which *proposes* it as
> syntax for some future Python.
> 

Yes, this is kind of interesting.

So it looks like it has been introduced internally to help with
introspection, but has not been introduced in documentation.

Old Python did this:

>>> help(pow)
pow(...)
pow(x, y[, z]) -> number

new Python does this:

>>> pow(x, y, z=None, /)


Documentation still says this:

 pow(x, y[, z])

While the PEP suggested standardizing on not only the
end-of-positional-only parameters marker but also on the brackets to
show optional positional-only parameters, apparently the implementation
has not done the latter and has instead undone the brackets (at least in
this example) and gone to a different syntax which looks like a keyword
parameter but which you can infer is not because of the presence of the
marker somewhere to its right.


Fine.

So now it looks like the old advice of "if in doubt, ask Python itself"
should be tempered with "... although the response may use syntax that
is not documented anywhere and might confuse you"

Sorry, bad night, I shouldn't be sniping but it's hard to resist.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If tuple cannot be sorted, then why sorted() on a tuple is fine?

2017-08-02 Thread Mats Wichmann
it generated a new object, did not change the original. hint: notice the output 
is a list, not a tuple!

On August 2, 2017 1:01:31 PM MDT, C W  wrote:
>Dear list,
>
>I am a little confused about why Tuple can be sorted.
>
>Suppose I have the following,
>
>> aTuple = (9, 3, 7, 5)
>> sorted(aTuple)
>[3, 5, 7, 9]
>
>Why is it ok to sort a the class tuple? If it is invariant by nature,
>then
>wouldn't applying a function on it yield an error?
>
>Thanks!
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The results of your email commands

2017-08-03 Thread Mats Wichmann
On 08/03/2017 10:21 AM, Alan Gauld via Tutor wrote:
> On 03/08/17 11:05, Abdur-Rahmaan Janhangeer wrote:
>> me i cooked up :...
> 
> Yes that works too, especially if you don;t need access
> to the individual prices later.
> 
> There are a couple of things to make it more Pythonic...
> 
>> x = True
>> sum = 0
>>
>> while (x==True):
>> a = input("input:")
>> if a =="exit":
>> x=False
> 
> You could replace that with
> 
> sum = 0
> while True:
>  a = input("input:")
>  if a =="exit":
>  break# exit the loop

I'd like to add a thought here... checking for a precise string as a
quit marker is fine, but it might be a little friendlier to accept
spelling variants (as long as none of them could be confused with valid
values... true in this case as you want numbers)... and also to let your
user know what you're expecting!

thus:

a = input("enter number ('exit' when done):)
if a in ('x', 'exit', 'Exit'):

> 
> and
> 
>> try:
>> sum += float(a)
>> except:
>> pass
> 
> That's a risky strategy because if there is
> any error other than the one you anticipate
> then you will never know about it and
> ignore it. You should always try to specify
> the error(s) if possible:
> 
> try:
>sum += float(a)
> except ValueError, TypeError:
>pass
> 

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


Re: [Tutor] file move with wait period

2017-08-03 Thread Mats Wichmann
On 08/03/2017 05:22 AM, banda gunda wrote:
> Dear tutors,
> 
> I am interested to move a set of files, periodically, from source_folder to 
> dest_folder.
> source_folder receives processed files from a ‘decompressing program’.  The 
> files are deposited from the ‘decompressing program’ at periodic random 
> intervals.  Furthermore some of the files dropped in the source_folder are 
> large, of typical size 800MB.  These files take time before it is completely 
> deposited in the source_folder.
> 
> I could use shutil.move (source_folder, dest_folder).  But then how?
> 
> The frequency of moving files from source_folder to dest_folder is flexible.  
> It could be once in 15 minutes (or even lengthier).
> Challenge for me:  How could the code include the wait statement to make sure 
> that the file in the source_folder is completely formed before attempting to 
> move to dest_folder?

Well, we cannot answer that question with the information you have given.

"How can you know" is actually the key question to explore. You need to
answer it before you worry about any Pythonic implementation details of
solving your problem.

- is the decompressor initiated by your program?  In that case there
will be techniques to maintain communication with it to find out when it
is done (perhaps as simple as waiting for it to quit-with-success).
- if it launches completely independently, how do you find out that it
has deposited files? Do you intend to just can periodically? Or is there
a way that the system causing the files to be generated can trigger
something that your program could be asked to be notified about when a
file is available?
- is it possible to convice the compressor to give files a certain
suffix or other recognizable pattern, but only when they are complete?
(downloader systems often work like this... while they're writing the
file, it has some temporary name, then when it finishes it is renamed to
the intended target name).

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


Re: [Tutor] unorderable types

2017-08-06 Thread Mats Wichmann
On 08/06/2017 11:35 AM, boB Stepp wrote:

> So these final two "if" groupings should be _outside_ your while loop:
> 
> while guessesTaken < 6:
> 
> 
> if guess_value == number:
> print('good job, ' + myName + '! you guessed my number in',
> guessesTaken, 'guesses!')
> 
> else:
> print('nope. the number i was thinking of was', number)
> 
> Notice the differences in indentation between what is _inside_ the
> while loop and what now follows _outside_ the while loop.  Also
> instead of two consecutive "if" blocks, I used the "if - else"
> structure.  If the "if" condition is not true then the code will
> automatically execute the "else" block.  Per what the others have
> said, I did not convert "guessesTaken" and "number" to strings,  The
> print function will handle that for us.  Also, with the print function
> if items to be printed are listed as separate arguments, that is,
> separated by commas, the default behavior  of print is to insert a
> single space in the place of each comma.

Yes, to highlight this last comment, the code as written is building one
string to pass to print, in other words it is similar to doing:

x = chunk1 + chunk2 + chunk3
print(x)

of course there's no assignment to 'x' taking place, I just use that to
illustrate that print is called with one argument.

and Bob is suggesting you can also let print do the combining:

print(chunk1, chunk2, chunk3)

it which case it applies a little formatting work for you (inserting the
space).  There will be lots more options to string formatting for print.


Meanwhile, it is worth pointing out that while: (as with other python
loops) can take an else: clause, which is executed if the loop runs to
completion and was not exited via break.  That means you could ALSO
write (this is pseudo-code for brevity):

while guessesTaken < 6:
collect_guess
if guess_value == number
break
other_actions
else:
print(guesses_ran_out)
quit_program

# if we got here it's because a guess was correct
print(congratulations)

Using this is no more or less correct than not using it, just pointing
it out for your learning about Python loops.  Apparently some people
think while/else, for/else and so on are useless, or vile, or whatever.
But they're certainly a part of the language.


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


Re: [Tutor] How does len() compute length of a string in UTF-8, 16, and 32?

2017-08-08 Thread Mats Wichmann
eh? the bytes are  ff fe h 0 
0xff is not literally four bytes, its the hex repr of an 8bit quantity with all 
bits on 

On August 8, 2017 9:17:49 PM MDT, boB Stepp  wrote:
>On Mon, Aug 7, 2017 at 10:01 PM, Ben Finney
> wrote:
>> boB Stepp  writes:
>>
>>> How is len() getting these values?
>>
>> By asking the objects themselves to report their length. You are
>> creating different objects with different content::
>>
>> >>> s = 'Hello!'
>> >>> s_utf8 = s.encode("UTF-8")
>> >>> s == s_utf8
>> False
>> >>> s_utf16 = s.encode("UTF-16")
>> >>> s == s_utf16
>> False
>> >>> s_utf32 = s.encode("UTF-32")
>> >>> s == s_utf32
>> False
>>
>> So it shouldn't be surprising that, with different content, they will
>> have different length::
>>
>> >>> type(s), len(s)
>> (, 6)
>> >>> type(s_utf8), len(s_utf8)
>> (, 6)
>> >>> type(s_utf16), len(s_utf16)
>> (, 14)
>> >>> type(s_utf32), len(s_utf32)
>> (, 28)
>>
>> What is it you think ‘str.encode’ does?
>
>It is translating the Unicode code points into bits patterned by the
>encoding specified.  I know this.  I was reading some examples from a
>book and it was demonstrating the different lengths resulting from
>encoding into UTF-8, 16 and 32.  I was mildly surprised that len()
>even worked on these encoding results.  But for the life of me I can't
>figure out for UTF-16 and 18 how these lengths are determined.  For
>instance just looking at a single character:
>
>py3: h = 'h'
>py3: h16 = h.encode("UTF-16")
>py3: h16
>b'\xff\xfeh\x00'
>py3: len(h16)
>4
>
>From Cameron's response, I know that \xff\xfe is a Big-Endian BOM.
>But in my mind 0xff takes up 4 bytes as each hex digit occupies
>16-bits of space.  Likewise 0x00 looks to be 4 bytes -- Is this
>representing EOL?  So far I have 8 bytes for the BOM and 4 bytes for
>what I am guessing is the end-of-the-line for a byte length of 12 and
>I haven't even gotten to the "h" yet!  So my question is actually as
>stated:  For these encoded bytes, how are these lengths calculated?
>
>
>
>-- 
>boB
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly does the three dots do? Why such as thing?

2017-08-11 Thread Mats Wichmann
On 08/10/2017 05:23 PM, Alan Gauld via Tutor wrote:
> On 10/08/17 14:39, C W wrote:
> 
>> I suppose it's just a place holder, though I don't know when I would use it
>> in my every day life.
> 
> Probably never.
> 
> Like most programming languages Python has a load of rarely used,
> obscure features. Most Python programmers never use ellipses,

I guess what this means is when I post code snippets with some lines
elided for greater readability of the point being made I should not use
ellipses for that, as they're actually a syntactic element!   :)

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


Re: [Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)

2017-08-11 Thread Mats Wichmann
On 08/11/2017 09:54 AM, Alan Gauld via Tutor wrote:
> On 11/08/17 13:35, Thomas Güttler wrote:
> 
>> I guess most python installations have setuptools. 
> 
> I guess so too, although I don't know.
> Those that don't are probably in one of two categories
> a) people who just downloaded Python and never installed
>anything else
> b) people working for large paranoid corporates. Although
>in this case there is probably only one installation,
>albeit with hundreds of users.
> 
> So far as I can tell I don't have it on any of my
> Python installs on my Linux box, but I may just be looking
> in the wrong place... 

Most Linux distributions choose to make it a separate package.  I have
it (them - one for Py2 and one for Py3) installed everywhere, but I'd
guess it's not a default install then.

Fedora:
python2-setuptools-36.2.0-1.fc26.noarch
python3-setuptools-36.2.0-1.fc26.noarch

Ubuntu:
Desired=Unknown/Install/Remove/Purge/Hold
|
Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name  Version  Architecture Description
+++-=---=
ii  python-setuptools 33.1.1-1 all  Python Distutils
Enhancements
ii  python3-setuptools33.1.1-1 all  Python3 Distutils
Enhancements
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Path tree"

2017-08-14 Thread Mats Wichmann
On 08/13/2017 02:07 PM, Michael C wrote:
> Hi all:
> 
> I am trying to formulate a "path-finding" function, and I am stuck on this
> problem:
> 
> Please look at the picture attached: Those dots are coordinates of (x,y),
> and this tree can be thought of as a list of tuples, with each tuple
> consisting of (x,y).  Now I am trying to make a function go through this
> list of tuples and then return the "path." to go from, say, 4 to 8. If I
> simply compute for the dot for shortest distance, then the solution would
> be to go from 4 to 8 direct, but that doesn't work, because the correct
> solution should have been 4,3,2,5,6,8.
>
> How do I do this?

There is no picture, don't know if you forgot to attach, or if it got
stripped by the mailing list software (the latter does happen, although
some seem to get through).

There is quite some on path-walking solvers in Python if you search a
bit, although when I looked just now it was not as easy to find useful
stuff as I remembered from some years ago when I was interested in such
a problem.

Usually, the tutors are better able to help if you post some initial
code and explain what you're trying to do and what is going wrong or
what you don't understand.


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


Re: [Tutor] conditional renaming folder and files in the tree

2017-08-14 Thread Mats Wichmann
On 08/14/2017 09:18 AM, banda gunda wrote:
> Dear Tutor,
> 
> 
> I have made some progress!
> 
> But not yet got the results.
> 
> Attached is revised code.
> 
> 
> Specifically, the problem in below:
> 
> 
> for root, dirs, files in os.walk(".", topdown=False):
> for name in files:
> print(os.path.join(root, name))
> os.rename(path + name, path + name.replace("---", "changed"))
> #os.rename(path + "\\"+ name, path + "\\"+ name.replace("---", 
> "changed")
> files[name] = os.sep.join([dirpath, name])
> 
> print (files)
> 
> for name in dirs:
> print(os.path.join(root, name))
> 
> 
> .\---DAT1\---DAT3\---10.txt
> 
> 
> ---
> FileNotFoundError Traceback (most recent call last)
>  in ()
>   2 for name in files:
>   3 print(os.path.join(root, name))
> > 4 os.rename(path + name, path + name.replace("---", "changed"))
>   5 #os.rename(path + "\\"+ name, path + "\\"+ 
> name.replace("---", "changed")
>   6 files[name] = os.sep.join([dirpath, name])
> 
> FileNotFoundError: [WinError 2] The system cannot find the file specified: 
> 'E://---10.txt' -> 'E://changed10.txt'

Well, here are a few thoughts.

(1) it will really help if your debugging print in line 3 makes the same
path calculation as the command in line 4.  You can see these don't
match, which is a good hint you're getting something you don't expect.
(2) where are you getting "path" from?  It doesn't show in your code. Is
there any reason why you don't just use the same calculation as in line 3?
(3) for cautious programming, you can check if the file you are going to
rename exists (os.path.exists() or os.path.isfile()) before trying to
rename it, that would at least cause you not to take an exception and
quit when you get something wrong.
(4) you've still not fixed "dirpath" in line 6.  Note the python
documentation for the walk() function shows dirpath as the first element
of the result triple, but you've called it "root" in your code, so this
is probably what you meant.
(5) why are you printing the whole list of files in line 7? That means
you will show the files list each time you iterate through the list.
(6) it's usually not a great idea to modify an interable while you're
iterating over it (line 6).
(7) you indicate you want to rename the directories as well, but you are
not doing that.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: "Path tree"

2017-08-14 Thread Mats Wichmann
On 08/14/2017 03:06 PM, Alan Gauld via Tutor wrote:
> 
> Forwarding to the list.
> 
>  Forwarded Message 
> 
> 
> 
> 
> pic
> http://imgur.com/a/CwA2G
> 
> On Mon, Aug 14, 2017 at 8:55 AM, Alan Gauld via Tutor  > wrote:
> 
> On 13/08/17 21:07, Michael C wrote:
> 
> > Please look at the picture attached:


So in modeling this in your program you need to describe not just the
x,y coordinates, but also the connections. point 1 can only reach point
2, so it has one link.  point 2 can reach 3 and 5, so two links. How can
you describe this in your data model?


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


Re: [Tutor] (no subject)

2017-08-17 Thread Mats Wichmann
On 08/17/2017 05:45 AM, Howard Lawrence wrote:
> Yes, it does.
> 
> On Aug 16, 2017 8:02 PM, "Zachary Ware" 
> wrote:
> 
> Hi Howard,
> 
> On Wed, Aug 16, 2017 at 5:36 PM, Howard Lawrence <1019sh...@gmail.com>
> wrote:
>> class Address:
>> def _init_(self,Hs,St,Town,Zip):
> 
> Your issue is in this line, it should be `__init__` rather than
> `_init_` (that is, two underscores before and after "init").
> 
> Hope this helps,


I would add that typography in a web browser, and sometimes even on the
printed page, may not make the double underscores ('dunder') actually
clearly look like two characters, so until one runs into this lesson The
Hard Way, it might be an easy mistake to make.


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


Re: [Tutor] When to use classes

2017-08-19 Thread Mats Wichmann
On 08/19/2017 10:00 AM, boB Stepp wrote:

>> (That was easy; but I wonder what tkinter would look like without
>> callbacks...)
> 
> I wish I knew more so that I could fully wonder about this myself.
> You might even be making a clever joke and I am clueless.

All graphics frameworks depend heavily on callbacks, to the point where
I'm starting to recognize that callback laden code in other contexts was
probably written by a (former?) graphics programmer :)

It makes some sense though; computational code just goes ahead and
computes.  In the graphical UI world, interesting things happen when an
event you can't exactly plan for takes place.  From the point of view of
a computer program, waiting for somebody to move a mouse and click it is
a slow, infrequent, and unpredictable event, so you set up callbacks
which are invoked when one of those events happens, and in the meantime
you can either do other productive work, or do nothing at all (let other
programs on the computer do work).  I'm finding it hard to imagine
tkinter without them...

>>> - if you can't, encapsulate it in classes.
>>
>> I think it's important that you say "classes", not "class". As with
>> functions three small dedicated classes are much better than one big know-
>> it-all/do-it-all class.
> 
> I try to keep this in mind.  Another thing I'm currently struggling
> with is when to use inheritance vs. separate, independent classes.

or when to use a class that contains an instance of another class...

It ought to feel natural... there's a lot in common, but we want to do a
little bit of specialization, that's a decent case for inheritance. So
they claim.  Except the examples are always so simplistic in the
literature: write a class called Human, then specialize it into Man and
Woman to deal with gender differences.  Sure.  And as recent political
kerfuffles have highlighted, what about an instance that is not clearly
one or the other?  What about all those pesky little details that are
not as simple as "has two arms" that are never part of the "real world"
models, but are very much part of the programming environment when you
go to implement something?

Inheritance describes a relationship - "is a".  a Volvo is-a Car. A
Checking Account is-a Bank Account. If you can't make that feel natural,
then it's probably not the right model.

(my opinions only)


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


Re: [Tutor] help with subprocess module

2017-08-19 Thread Mats Wichmann
On 08/19/2017 04:13 AM, kay Cee wrote:
> I made a python script that will update a Ubuntu Server every second and
> writes asuccess message  and date to a log file, but for some reason the
> file is not being written to.
> 
> Here is the Script:
> 
> #!/usr/bin/python3
> 
> import subprocess
> import time
> import datetime
> 
> class UpdateError(Exception):
> pass
> 
> def update():
> while True:
> try:
> update_log = open('update_log.txt', 'r+')
> time.sleep(1)
> subprocess.call(['apt-get', 'update', '-y'])
> date = datetime.datetime.now()
> update_log.write("System was updated sucessfully on {}\n".format
> (str(date)))
> subprocess.call(['reboot'])
> except UpdateError:
> print("Update Error!!!")
> update_log.close()
> 
> if __name__ == '__main__':
> update()

Hate to not just "answer the question", but what are you trying to
accomplish with this script?

You certainly don't want to call "apt-get update -y" in loop this fast.
Why are you then rebooting? (update doesn't change the system, only the
apt cache info)

Ubuntu has a way to do this stuff as a background task anyway.

For logging, you may want to actually use Python logging facilities.


All those said, the way you want to debug something like this is to run
a much more benign task through subprocess, before moving on to big (and
slow) tasks.

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


Re: [Tutor] How to use subprocess module to get current logged in user?

2017-08-25 Thread Mats Wichmann
import getpass 
getpass.getuser ()

depending on how fussy you want to be...

On August 25, 2017 6:13:12 PM MDT, boB Stepp  wrote:
>SunOS 5.10, Python 2.4/2.6
>
>I ask forgiveness in advance as I cannot copy and paste into an email
>what I am doing on this system.  So I will have to manually type
>things, introducing the usual possibility of typos.
>
>My objective:  Determine who the currently logged in user is and
>determine if that user is in my list of users that I have authorized
>to use my programs.
>
>I tried in the interpreter:
>
>=
>py2> cmd = ['who', '-m']
>py2> import subprocess as sp
>py2> p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
>py2> out, err = p.communicate()
>py2> out
>''
>py2> err
>"Must be attached to terminal for 'am I' option\n"
>py2> p = sp.Popen(cmd, shell=True, stdin=sp.PIPE, stdout=sp.PIPE,
>stderr=sp.PIPE)
>py2> out, err = p.communicate()
>py2> out
>'rstepp ...' followed by all the other currently logged in users as if
>I had just typed 'who' in the terminal.
>=
>
>What am I doing wrong?  Why cannot I get the '-m' to be used?  And is
>there an easier way to accomplish my objective?
>
>If I cannot work this out, then I will be forced to do:
>
>py2> import os
>py2> current_usr = os.popen('who -m')
>
>This should not be a security issue for me as no user input is
>involved.  But I would rather use the subprocess module.
>
>TIA!
>
>-- 
>boB
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] easygui

2017-08-27 Thread Mats Wichmann
On 08/27/2017 02:14 AM, Alan Gauld via Tutor wrote:
> On 27/08/17 03:07, George Sconyers via Tutor wrote:
>> Hello all. Need some help with easygui which my son is trying to run for a 
>> book he is working in.
> 
> I'm not sure what the current status of easygui is, I read
> somewhere that it had been discontinued. But if you are
> still finding a download for 2.7 then it should
> presumably work... Ok, I see that the code is still
> available, and being Tkinter based should still work
> but the project was frozen in 2013.
> 
>> Using Python 2.7 we downloaded easygui and put it in an executable path. 
>> Code is:import easyguieasygui.msgbox("Hello there")
> 
> The code appears to be mangled by the mail system. I assume you mean
> 
> import easygui
> easygui.msgbox("Hello there")
> 
>> No popup occurs, cusor changes to a cross and no longer process mouse 
>> clicks.> When we click on the bash shell the program terminates,
> 
> I assume from the bash reference that you are using either Linux
> or MacOSX?
> 
>> script.py: line 2: syntax error near unexpected token  '"Hello there"
>> 'script.py: line 2: 'easygui.msgbox("Hello there")'
> 
> How exactly are you running the program?
> The message format does not look like a normal Python
> traceback message.

Indeed, that's an error from bash running the script, not Python.

If you're on Linux (or Mac), and your script is named example.py, run it as:

python example.py

or perhaps less intuitively, stick a first line in it to tell the system
to have Python run it, so your script looks like this (there are
possible variants on that magic first line, but this one should work
whichever your platform is, as long as it is the first line):

#!/usr/bin/env python
import easygui
easygui.msgbox("Hello there")


and you can then run the script directly.

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


Re: [Tutor] intro book for python

2017-09-01 Thread Mats Wichmann
On 09/01/2017 07:42 AM, Derek Smith wrote:
> 
> Hello!
> 
> I am new to python coming from a Perl and Unix Admin background.  I reviewed 
> the site https://wiki.python.org/moin/IntroductoryBooks and would like to 
> know which book(s) you all recommended for a newbie?

Hi Derek, welcome to Python.

We don't recommend anything on the wiki, it wouldn't really be fair,
there are so many books written by dedicated Python enthusiasts, how
could we seem to prefer one over another? Some publishers are more
diligent than others at adding everything they publish, but that's not
really representative of quality, either.

That said, there's obviously more to choose from than one could possibly
get through.  There ARE forums where people will be more than happy to
offer an opinion, some of those were listed in the autoreply.

The python tutor mailing list (of which some of the webmasters are also
participants) will be happy to help you along as you run into questions.
 Stack Overflow is also a good source for answers to questions, although
there it's best to search first, or you'll get shut down with the
somewhat unhelpful "this question has already been asked and answered" ding.



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


Re: [Tutor] intro book for python

2017-09-01 Thread Mats Wichmann
Okay, this reply makes it seem like I was really confused.  My mail
client did a weird thing, made it look to me like this question was on
the Python webmaster list, where I also hang out - now it's resorted and
I see it was already sent to tutor.  Sorry about confusing anyone else
:)  And welcome!


On 09/01/2017 11:43 AM, Mats Wichmann wrote:
> On 09/01/2017 07:42 AM, Derek Smith wrote:
>>
>> Hello!
>>
>> I am new to python coming from a Perl and Unix Admin background.  I reviewed 
>> the site https://wiki.python.org/moin/IntroductoryBooks and would like to 
>> know which book(s) you all recommended for a newbie?
> 
> Hi Derek, welcome to Python.
> 
> We don't recommend anything on the wiki, it wouldn't really be fair,
> there are so many books written by dedicated Python enthusiasts, how
> could we seem to prefer one over another? Some publishers are more
> diligent than others at adding everything they publish, but that's not
> really representative of quality, either.
> 
> That said, there's obviously more to choose from than one could possibly
> get through.  There ARE forums where people will be more than happy to
> offer an opinion, some of those were listed in the autoreply.
> 
> The python tutor mailing list (of which some of the webmasters are also
> participants) will be happy to help you along as you run into questions.
>  Stack Overflow is also a good source for answers to questions, although
> there it's best to search first, or you'll get shut down with the
> somewhat unhelpful "this question has already been asked and answered" ding.
> 
> 
> 

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


Re: [Tutor] intro book for python

2017-09-01 Thread Mats Wichmann
On 09/01/2017 01:08 PM, Chris Warrick wrote:
> I would recommend reading the official Python tutorial [0] This
> tutorial will explain the important parts of Python. It doesn’t spend
> too much time explaining programming basics though.
> 
> My alternate recommendations include Think Python [1] or Automate the
> Boring Stuff with Python [2].
> 
> 
> On 1 September 2017 at 19:51, Raghunadh  wrote:
>> Hello Derek,
>>
>> I would start with this book
>>
>> hxxps://learnpythonthehardway.org
>>
>> Raghunadh
> 
> LPTHW is a terrible book: slow and boring, tells readers to memorize
> truth tables instead of understanding them (sic!), 19% of it is
> thoughtlessly teaching print() — overall, a failure at teaching people
> to program. Moreover, the author wrote a nonsensical essay bashing
> Python 3 [3] (debunked in [4]), and released a Python 3.6 version of
> his book shortly afterwards.


So I pointed out people would have strong opinions :)


Turns out - I had forgotten this though I saw it once long ago - that
some people tried to put together a page for people coming from Perl.

https://wiki.python.org/moin/PerlPhrasebook

that might possibly help setting some early concepts, and "idioms", into
place; it certainly won't replace a good Python book, but still...


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


Re: [Tutor] Python 3 for Beginners was: (Re: intro book for python)

2017-09-03 Thread Mats Wichmann
On 09/03/2017 04:02 AM, Leam Hall wrote:

> Anyone that uses python on Linux has to use Python 2. 

Every current distro I know of has a python 3 package, plus lots and
lots of add-ons in python 3 mode.  It's quite easy to use python 3 as a
result... and if that doesn't work you can install your own to your
workspace (rather than as a "system package") just as easily.

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


  1   2   3   4   >