[Tutor] What these Python user-defined functions do?
Hi, I started learning Python (v3.5) and was given some code samples to assist in my studies. There are some things I could not figure out using Python documentation or other online sources. I have experience with SQL programming and some procedural programming, but little in terms of OOP. I try to slice and dice a Python script that exports a shipment from ERP system to a text file. Shipment consists of a Header (H, one record) and Details (D, one or more records). Script first imports a library with a number of user-defined functions. Then the script uses functions defined in library to do exporting to a text file. Here is the part of the library: class View: def __init__(self): self.handle = None … def order(self, n): return hostviewOrder(handle, self.handle, n) def put(self, fieldName, value, verify=1): if verify == True: verify = 1 elif verify == False: verify = 0 return hostviewPut(handle, self.handle, fieldName, value, verify) def read(self): return hostviewRead(handle, self.handle) def browse(self, filter="", ascending=1): if ascending == True: ascending = 1 elif ascending == False: ascending = 0 return hostviewBrowse(handle, self.handle, filter, ascending) def fetch(self): return hostviewFetch(handle, self.handle) Here is a part of the script I am trying to understand: def ExportShipment(): f = open("c:\\" + me.get("SHN") + ".txt", "w") h = View("Header", *1*) d = View("Details", *1*) h.*order*(1) # SHN h.*put*("SHN", me.get("SHN"), 1) h.*read*() f.write("H," + h.get("LOCATION") + "," + h.get("ADDR1") + "\n") d.*browse*("SHIUNIQ=" + "{:.0f}".format(h.get("SHIUNIQ")), 1) while (d.*fetch*() == 0): f.write("D," + d.get("ITEM") + "," + "{:.0f}".format(d.get("QTYSHIPPED")) + "\n") f.close() Export output looks like: H,4,1234 Any Road D,A2,1 D,B1,3 I understand what file operations do. However I can’t get what these functions do: *order(), put(), read(), browse(), fetch()*. Function definitions in the library are of little help for now, as all functions feature handle and self.handle in their returns; however I cannot find out what handle and self.handle may mean in this context. Please let me know if I should provide more info for my question to make sense. Thanks a lot! -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What these Python user-defined functions do?
On 21/05/16 02:21, Max Jegers wrote: > class View: > def __init__(self): > self.handle = None > > def order(self, n): > return hostviewOrder(handle, self.handle, n) > > def put(self, fieldName, value, verify=1): > if verify == True: > verify = 1 > elif verify == False: > verify = 0 > return hostviewPut(handle, self.handle, fieldName, value, > verify) This is a very odd function. The if/else bit at the top makes no sense at all. > def read(self): > return hostviewRead(handle, self.handle) > > def browse(self, filter="", ascending=1): > if ascending == True: > ascending = 1 > elif ascending == False: > ascending = 0 > return hostviewBrowse(handle, self.handle, filter, ascending) Same comment regarding the if/else here. > def fetch(self): > return hostviewFetch(handle, self.handle) Other than the if/else issues above the methods are just wrappers around the hostview library, which we obviously can't see so can't comment on. I also notice that self.handle never gets set to anything other than None, which is odd unless there are other methods you are not showing us? Also a handle argument is passed to the hostview functions but its not clear where that is defined... > Here is a part of the script I am trying to understand: > > def ExportShipment(): > f = open("c:\\" + me.get("SHN") + ".txt", "w") > h = View("Header", *1*) > d = View("Details", *1*) > h.*order*(1) # SHN > h.*put*("SHN", me.get("SHN"), 1) > h.*read*() > f.write("H," + h.get("LOCATION") + "," + h.get("ADDR1") + "\n") I'm not sure where all the * characters are coming from, I assume they are not part of the code? But the code above opens a file and creates two View objects, one for the header and one for the details. However the View init() function above does not have any paramaters so this should fail. Also there is reference to a get() method which is not part of the class definition above. And there is reference to a me object but its not defined above either. > d.*browse*("SHIUNIQ=" + "{:.0f}".format(h.get("SHIUNIQ")), 1) > while (d.*fetch*() == 0): > f.write("D," + d.get("ITEM") + "," + > "{:.0f}".format(d.get("QTYSHIPPED")) + "\n") > f.close() Again this code does not match the code above. There is no View.get() method. And View.browse() does not change the View's state so its hard to see what the get() method could return. It could only work if there were either a lot of global variables being used in the background(by listview) or if thee is a lot more to the View definition than we have seen. > I understand what file operations do. However I can’t get what these > functions do: > > *order(), put(), read(), browse(), fetch()*. They are trivial wrappers around the listviewXXX functions that are presumably defined in another library somewhere. But the code is generally inconsistent and definitely not good Python on any level. > Function definitions in the library are of little help for now, as all > functions feature handle and self.handle in their returns; however I cannot > find out what handle and self.handle may mean in this context. > Please let me know if I should provide more info for my question to make > sense. Apart from the issue over handle its not clear what you don't understand. However until you get the two code segments harmonised you will never make sense of it. The code as it stands is inconsistent and could never work. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting started in testing
(sorry for top-posting) I liked https://www.packtpub.com/application-development/python-testing-beginners-guide though perhaps it was a bit too basic. It covers forest, unit test, nose. > Date: Thu, 19 May 2016 12:34:27 -0700 > From: carr...@tjc.com > To: tutor@python.org > Subject: [Tutor] Getting started in testing > > Is anyone aware of any good tutorials on testing one's Python code? > > These days, I'm a hobby programmer, writing little things just for my own > use, and don't really sweat testing much. But I do have one niche > open-source project where I need to be a bit more regimented, and > specifically need to develop a set of tests to be passed before releasing. > > Any resources would be helpful. I am aware of the docs on unittest, but > I'm looking for a more tutorial approach. > > I use Python 2.7, and my project is a module with no GUI, if that matters. > Thanks. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python 3: string to decimal conversion
Hello all, I am working on a piece of python code that's supposed to help me manage a budget: 1. Read a banking statement 2. Categorize expenses and income by month and by type 3. Print out a report comparing the projected expenses/income with actual numbers. *File characteristics:* Banking statement in a csv file format. contents: 5 columns, 1st column= date, 4 column=expenses date format: mm/dd/, type: string expenses format: ($0.00), type: string income format: $0.00, type: string *Python Version: 3.5 (64 bit)* IDE:Microsoft Visual Studio Community 2015 Version 14.0.25123.00 Update 2 Python Tools for Visual Studio 2.2.40315.00 Python Tools for Visual Studio provides IntelliSense, projects, templates, Interactive windows, and other support for Python developers. *Problem:* I want to convert expense/income values into a decimal form so I could sum them into appropriate buckets according to the month in which they occur. I am getting the following error message when I run my code: "decimal.InvalidOperation was unhandled by user code Message: []" *Question: *I tried looking up the meaning of this error, but couldn't find anything on the internet. *Can someone help me understand what's wrong with my code?* Below is my code: ++ import numpy as np import csv import timestring as ts import decimal months= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] expenses = {x: decimal.Decimal() for x in months} income = {x: decimal.Decimal() for x in months} exp_cat = [] income_cat = [] files =['export.csv'] with open("budgetfile.csv","wt") as fw: writer = csv.writer(fw) for file in files: with open(file) as csvfile: records = csv.reader(csvfile, quoting=csv.QUOTE_NONE) print("Processing file {}. \n" .format(file)) header = next(records) for row in records: row[4].replace("($","") row[4].replace(")","") row[4].replace('"', '') try: expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4]) except ValueError: pass + ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Never need to apologise for top-posting: just don't do it (was: Getting started in testing)
Albert-Jan Roskam writes: > (sorry for top-posting) If you know enough to apologise for the mistake, you know enough to avoid the mistake. Resist that urge. Delay the response until you can compose it on a device that makes it feasible to reply interleaved. -- \ “I have an answering machine in my car. It says, ‘I'm home now. | `\ But leave a message and I'll call when I'm out.’” —Steven Wright | _o__) | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting started in testing
Terry Carroll writes: > Is anyone aware of any good tutorials on testing one's Python code? > > Any resources would be helpful. I am aware of the docs on unittest, > but I'm looking for a more tutorial approach. The book Dive Into Python (available both for Python 2 and Python 3) http://www.diveintopython.net/> has a good “dive in”, tutorial style, to unit testing a complete program. This guide has good “dos and don'ts” for testing while you code http://docs.python-guide.org/en/latest/writing/tests/>. Test behaviour of the whole program, too, with behavioural tests https://semaphoreci.com/community/tutorials/getting-started-with-behavior-testing-in-python-with-behave>. Automate all of this by writing build scripts which run *all* the tests with a single command. That's something you should already have in place, but Fabric is a place to start, or you may be more comfortable with Make. -- \“The problem with television is that the people must sit and | `\keep their eyes glued on a screen: the average American family | _o__) hasn't time for it.” —_The New York Times_, 1939 | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3: string to decimal conversion
Saidov writes: > *Python Version: 3.5 (64 bit)* > IDE:Microsoft Visual Studio Community 2015 Your IDE is apparently suppressing, or hiding somewhere, the full traceback of the exception. It's important that you always have that in front of you when trying to diagnose an un-handled exception. > "decimal.InvalidOperation was unhandled by user code > Message: []" So, this tells us only the name of the exception, not the location in the code, nor the call stack that produced it. You need to find and paste the full traceback text. > *Question: *I tried looking up the meaning of this error, but couldn't find > anything on the internet. *Can someone help me understand what's wrong with > my code?* Please turn off any “rich” or HTML formatting of your message, post in plain text only. You need the text of your message to survive without any mangling. -- \ “Give a man a fish, and you'll feed him for a day; give him a | `\religion, and he'll starve to death while praying for a fish.” | _o__) —Anonymous | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3: string to decimal conversion
Hi Saidov, I'm going to reply to your post inline, as that is the etiquette here and in many technical mailing lists. On 21May2016 13:34, Saidov wrote: I am working on a piece of python code that's supposed to help me manage a budget: 1. Read a banking statement 2. Categorize expenses and income by month and by type 3. Print out a report comparing the projected expenses/income with actual numbers. Thank you for providing your problem's context. *File characteristics:* Banking statement in a csv file format. contents: 5 columns, 1st column= date, 4 column=expenses date format: mm/dd/, type: string expenses format: ($0.00), type: string income format: $0.00, type: string *Python Version: 3.5 (64 bit)* IDE:Microsoft Visual Studio Community 2015 Version 14.0.25123.00 Update 2 Python Tools for Visual Studio 2.2.40315.00 Python Tools for Visual Studio provides IntelliSense, projects, templates, Interactive windows, and other support for Python developers. And this level of detail is very welcome. *Problem:* I want to convert expense/income values into a decimal form so I could sum them into appropriate buckets according to the month in which they occur. I am getting the following error message when I run my code: "decimal.InvalidOperation was unhandled by user code Message: []" Please always provide the full traceback which accompanied the exception report; there should be a list of code lines indicating the call stack where the error occurred. This provides valuable context for figuring out where in your code to look for issues. Absent that context, I will have a guess at where this might be occurring: [...] files =['export.csv'] with open("budgetfile.csv","wt") as fw: writer = csv.writer(fw) for file in files: with open(file) as csvfile: records = csv.reader(csvfile, quoting=csv.QUOTE_NONE) [...] for row in records: [...] try: expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4]) except ValueError: pass I would guess that this: decimal.Decimal(row[4]) is the source of your error; it seems to be the only place where you actually convert a string into a Decimal. I would guess that when handed a bad string this raises decimal.ConversionSyntax instead of a ValueError. I suggest that you print out the value of row[4] before the "try" statement: print("row[4] =", repr(row[4])) Note the use of repr: it gets you better detail about the value of the string. Thank you for a well presented question. Finally, please try to post in plain text instead of rich text; this is a plain text list and if you post in rich text or HTML (a) some hinting you have have povided like coloured text will not be presented to readers and (b) some things, particularly code, and be presented visually mangled, which makes things hard to read and debug. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor