From jgarvit912 at gmail.com Sun Nov 3 05:00:39 2019 From: jgarvit912 at gmail.com (Garvit) Date: Sun, 3 Nov 2019 15:30:39 +0530 Subject: [Tutor] regarding an error in the programming Message-ID: <5dbea548.1c69fb81.bc63e.3bcf@mx.google.com> Sir/ma?am, I am a student and learning python as the programming language. During the execution of a program about ?pie charts? an error is occurring i.e. ?Traceback (most recent call last): File "C:\Users\yashmita jain\Desktop\garvit\computer\programs for file\prog 11.py", line 19, in plt.pie(Book_price,Book_name,colors=Colours,shadow=True,startangle=140,autopct='%1.1f%%') File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\pyplot.py", line 2783, in pie data is not None else {})) File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\__init__.py", line 1538, in inner return func(ax, *map(sanitize_sequence, args), **kwargs) File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\axes\_axes.py", line 2964, in pie x += expl * math.cos(thetam) TypeError: can't multiply sequence by non-int of type 'float' ?. How can I correct it? Do response quickly. Thanking you, Garvit Jain From mats at wichmann.us Sun Nov 3 08:54:21 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 3 Nov 2019 06:54:21 -0700 Subject: [Tutor] regarding an error in the programming In-Reply-To: <5dbea548.1c69fb81.bc63e.3bcf@mx.google.com> References: <5dbea548.1c69fb81.bc63e.3bcf@mx.google.com> Message-ID: <41183a99-63a3-d1a6-f36f-3da99a4b63ee@wichmann.us> On 11/3/19 3:00 AM, Garvit wrote: > Sir/ma?am, > I am a student and learning python as the programming language. > During the execution of a program about ?pie charts? an error is occurring i.e. > > ?Traceback (most recent call last): > File "C:\Users\yashmita jain\Desktop\garvit\computer\programs for file\prog 11.py", line 19, in > plt.pie(Book_price,Book_name,colors=Colours,shadow=True,startangle=140,autopct='%1.1f%%') > File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\pyplot.py", line 2783, in pie > data is not None else {})) > File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\__init__.py", line 1538, in inner > return func(ax, *map(sanitize_sequence, args), **kwargs) > File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\axes\_axes.py", line 2964, in pie > x += expl * math.cos(thetam) > TypeError: can't multiply sequence by non-int of type 'float' ?. > > How can I correct it? Do response quickly. By reading and understanding the error message. The failing line was: x += expl * math.cos(thetam) The error was: TypeError: can't multiply sequence by non-int of type 'float' ? That means expl is a sequence type (list, or tuple, or ...) because the cos function always returns a float. "Don't do that". Since you didn't see fit to include any code at all nobody listening here can say anything more. From py.ohayo at sunrise.ch Wed Nov 6 05:29:26 2019 From: py.ohayo at sunrise.ch (Pavel Yermolenko) Date: Wed, 06 Nov 2019 10:29:26 +0000 Subject: [Tutor] execute search request on website Message-ID: Hello, Is someone aware of the procedure for running a search request on a website, for example to search Amazon for a book using its ISBN? Thanks. From mats at wichmann.us Wed Nov 6 08:49:27 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 6 Nov 2019 06:49:27 -0700 Subject: [Tutor] execute search request on website In-Reply-To: References: Message-ID: <4fc35e81-abb3-94f5-faa7-19c5292c0a65@wichmann.us> On 11/6/19 3:29 AM, Pavel Yermolenko wrote: > Hello, > Is someone aware of the procedure for running a search request on a > website, for example to search Amazon for a book using its ISBN? In a limited way - there is an API here which you can look at, which as I recall, says nothing about Python specifically. https://docs.aws.amazon.com/AWSECommerceService/latest/DG/ItemSearch.html In general, it's up to each website whether or not they provide an API to access their materials, and under what terms you can do so. Amazon wants to sell things, so they do but some of the search engines, for example, are not allowed to (or don't wish to, if they have the rights) present their results in a way that does not include their presentation and branding. So something that seems simple may not be (and this is why many people go down the route of web scraping, which may or may not legally circumvent those same restrictions of who owns what and how it may be presented). Maybe others have examples? From asuitaji22 at gmail.com Thu Nov 7 17:42:50 2019 From: asuitaji22 at gmail.com (Itaji Le) Date: Thu, 7 Nov 2019 17:42:50 -0500 Subject: [Tutor] Virutal env. is missing from PyCharm Message-ID: Hi, my name is Nhu and I am new but interested in learning to program using Python! After downloaded PyCharm and created a new project, I encounter this problem when trying to assign a Python interpreter... I have tried to search for solutions to this problem but unsuccessfully... Can you direct me on how to fix this problem? [image: image.png] Thank you! Sincerely From mats at wichmann.us Thu Nov 7 18:17:08 2019 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 7 Nov 2019 16:17:08 -0700 Subject: [Tutor] Virutal env. is missing from PyCharm In-Reply-To: References: Message-ID: On 11/7/19 3:42 PM, Itaji Le wrote: > Hi, my name is Nhu and I am new but interested in learning to program using > Python! After downloaded PyCharm and created a new project, I encounter > this problem what problem? looks like you might have included an image, but it didn't survive the list software, which strips many kinds of attachments for safety reasons. when trying to assign a Python interpreter... I have tried to > search for solutions to this problem but unsuccessfully... Can you direct > me on how to fix this problem? > [image: image.png] have you tried JetBrains' documentation? It's usually pretty solid. I find this: https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html From mats at wichmann.us Thu Nov 7 18:45:56 2019 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 7 Nov 2019 16:45:56 -0700 Subject: [Tutor] Virutal env. is missing from PyCharm In-Reply-To: <9c8a0c67fd103e04ffd989f4ca86f038@sonic.net> References: <9c8a0c67fd103e04ffd989f4ca86f038@sonic.net> Message-ID: <3a394f2b-cd84-397d-0f84-baf22313b15f@wichmann.us> On 11/7/19 4:39 PM, Alex Kleider wrote: > > Lurker's comment: > I prefer virtualenvwrapper[1] but perhaps not for the obvious > (functionality) reasons: > What I like is that all the 'env's are under one directory > (~/.virtualenvs) rather than scattered in various project directories. > "Different strokes for different folks." yeah, I use pyenv partly for the same reason, all of the stuff ends up in my ~/.pyenv directory.... From akleider at sonic.net Thu Nov 7 18:39:06 2019 From: akleider at sonic.net (Alex Kleider) Date: Thu, 07 Nov 2019 15:39:06 -0800 Subject: [Tutor] Virutal env. is missing from PyCharm In-Reply-To: References: Message-ID: <9c8a0c67fd103e04ffd989f4ca86f038@sonic.net> On 2019-11-07 15:17, Mats Wichmann wrote: > On 11/7/19 3:42 PM, Itaji Le wrote: >> Hi, my name is Nhu and I am new but interested in learning to program >> using >> Python! After downloaded PyCharm and created a new project, I >> encounter >> this problem > > > have you tried JetBrains' documentation? It's usually pretty solid. I > find this: > > https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html > Lurker's comment: I prefer virtualenvwrapper[1] but perhaps not for the obvious (functionality) reasons: What I like is that all the 'env's are under one directory (~/.virtualenvs) rather than scattered in various project directories. "Different strokes for different folks." [1]https://virtualenvwrapper.readthedocs.io/en/latest/ From robertvstepp at gmail.com Thu Nov 7 22:39:39 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 7 Nov 2019 21:39:39 -0600 Subject: [Tutor] OT: Has anyone tried the Visual Studio Code editor? Message-ID: An article popped up on my phone today about Visual Studio Code. It claimed that a Stack Overflow survey this year found it to be the most popular code editor. So, being curious, has anyone tried it for Python development? And the Python extension? Also, has anyone using this editor tried the Vim extension? -- boB From mats at wichmann.us Thu Nov 7 23:14:25 2019 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 7 Nov 2019 21:14:25 -0700 Subject: [Tutor] OT: Has anyone tried the Visual Studio Code editor? In-Reply-To: References: Message-ID: <5d8a7066-7e92-6d7c-9530-4289f88c13a0@wichmann.us> On 11/7/19 8:39 PM, boB Stepp wrote: > An article popped up on my phone today about Visual Studio Code. It > claimed that a Stack Overflow survey this year found it to be the most > popular code editor. So, being curious, has anyone tried it for > Python development? And the Python extension? Also, has anyone using > this editor tried the Vim extension? vscode is decent at Python. some of the additional addons are poor (I have a running battle with the ReST support plugin, which always seems to be missing support for something I try to use) but it's not at all a bad editor for py code. It you're a vim person, though, why not just use vim, rather than fiddling with an addon for another editor that tries to support vim keystrokes?? From robertvstepp at gmail.com Thu Nov 7 23:31:14 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 7 Nov 2019 22:31:14 -0600 Subject: [Tutor] OT: Has anyone tried the Visual Studio Code editor? In-Reply-To: <5d8a7066-7e92-6d7c-9530-4289f88c13a0@wichmann.us> References: <5d8a7066-7e92-6d7c-9530-4289f88c13a0@wichmann.us> Message-ID: On Thu, Nov 7, 2019 at 10:14 PM Mats Wichmann wrote: > >... It you're a vim person, though, why not just use > vim, rather than fiddling with an addon for another editor that tries to > support vim keystrokes?? I have been using Vim (more recently Neovim). The things I like about Vim boil down to being able to use the keyboard for everything without going through keyboard contortions, like emacs with its extensive use of control key combinations. And its speed. What I hate about it is its varying methods of installing plugins, finding the right plugins, etc. To me it is a nightmare! I can get it done, but I feel like I am getting a root canal at the dentist. So my hope with Visual Studio Code is that it could do most of the two things I like and greatly improve the main thing I dislike about Vim. -- boB From alan.gauld at yahoo.co.uk Fri Nov 8 04:53:19 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 8 Nov 2019 09:53:19 +0000 Subject: [Tutor] OT: Has anyone tried the Visual Studio Code editor? In-Reply-To: References: Message-ID: <93ee8957-496e-b9fd-b04f-054c5d357253@yahoo.co.uk> On 08/11/2019 03:39, boB Stepp wrote: > An article popped up on my phone today about Visual Studio Code. It > claimed that a Stack Overflow survey this year found it to be the most > popular code editor. So, being curious, has anyone tried it for > Python development? And the Python extension? Also, has anyone using > this editor tried the Vim extension? > I tried it in vanilla form for Linux. It was part of my general testing of IDEs - Netbeans, Eclipse and a few others were also considered. In the end I opted for Netbeans as my tool of choice (previously it had been Eclipse) But I don't use an IDE for python work, they are just too big and clunky. I only use them for bigger, mixed language projects. VScode was an OK IDE, familiar to me from my use of it programming C++ and C# on Windows. But it didn't offer anything special enough for me to pick it over Netbeans. Like all IDEs it's big and clunky so takes a while to start up. If you have sufficient RAM then it runs well enough once started. But for Python coding I still prefer vim. I have no issues with plugins because I don't use any! :-) Raw vim has more than enough features to keep me happy. Plus, for me, one of vim's strongest features is its all pervasive presence on Linux boxes. I can go anywhere and find a vim. If I become dependent on a non-standard feature then I lose productivity when visiting an alien vim. So I keep to the vanilla editor. -- 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 From david at lowryduda.com Fri Nov 8 10:55:37 2019 From: david at lowryduda.com (David Lowry-Duda) Date: Fri, 8 Nov 2019 10:55:37 -0500 Subject: [Tutor] OT: Has anyone tried the Visual Studio Code editor? In-Reply-To: References: <5d8a7066-7e92-6d7c-9530-4289f88c13a0@wichmann.us> Message-ID: <20191108155537.GA5003@mail.lowryduda.com> > What I hate about it is its varying methods of installing plugins, > finding the right plugins, etc. To me it is a nightmare! I don't mean to make this into a vim discussion, but I would like to add that essentially every plugin can be installed using a single plugin manager and it doesn't really matter which plugin manager you choose. If you decide you would like to try to adjust your vim-strategy, I invite you to ask on the vim mailing list. I'll also add that I know a few people who like the modal editing interface of vim and use vim-bindings in pycharm as their python editor of choice. Good luck (with visual studio or vim or whatever is next for you). -- David Lowry-Duda From robertvstepp at gmail.com Fri Nov 8 22:54:04 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 8 Nov 2019 21:54:04 -0600 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? Message-ID: I have spent the afternoon playing around with Visual Studio Code with the Vim extension enabled, comparing it to Neovim. While interesting and "pretty", I will continue to stick with Vim/Neovim. But playing around with VSC with all of its many integrated tools has convinced me it is time to give careful thought to what would be helpful tools for serious Python development to make me more efficient and less error prone. Up to this point in my on and off adventures with Python I have strictly avoided any such tools to force myself to get Python syntax into my head and fingers. I think I now am at the point where these tools would be more helpful than harmful to my Python journey. My main system at home is Linux Mint. I am using a bare Neovim editor installation (Meaning no plugins installed and using existing defaults) with no GUI running in Gnome terminal. I am using Python 3.7.5 on this PC. I use Git for version control. I have installed vim-plug for Neovim plugin management (Done today.) I normally use Python's unittest module for testing, though I play around with pytest from time to time. My normal workflow is to have Neovim open in one terminal tab, the Python interpreter in another, and finally another tab for actually running any code. I normally prefer the latter to using Neovim's integrated terminal or its terminal commands. What Neovim plugins would any of you recommend as especially useful? Searching online I have found a variety of opinions, but as to functionality I have seen suggested: 1) Git integration plugins. 2) Code completion plugins. 3) Linters. 4) File explorer plugins. 5) Bracket and quote completion plugins. 6) Comments plugins. 7) Code autoformatting plugins. 8) PEP 8 compatibility plugins. 9) Multiple cursor plugins. 10) Code folding plugins. 11) "Fuzzy" searching plugins. 12) And on and on and ... I may very well have left out something that is actually important. Perhaps an integrated debugger of some sort? This is all quite mind boggling and it is hard to sift out the wheat from the chaff, not to mention there are usually multiple plugins that claim to perform the same functionality. I am sure there must be significant variation in quality of these different options. Any help in making sense of these will be appreciated. I have agreed to work with my son on what looks to be a potentially very large project (Meaning for us possibly tens of thousands LOC.) and anything that will help my code quality and efficiency in generating it, I am willing to entertain. TIA! -- boB From javon1974 at me.com Fri Nov 8 23:19:08 2019 From: javon1974 at me.com (Eddwin Shoemo) Date: Fri, 8 Nov 2019 22:19:08 -0600 Subject: [Tutor] Curve Fitting a cvs data file in Python Message-ID: <7A44F6E8-3B60-4440-97CD-0799AEA632A2@me.com> Hi. I was presented with a question and it has me stumped. My PY and csv files are attached. Here is the question: Use the function, test_func1(x, b0, b1,b2,b3,b4,b5) ( References: <7A44F6E8-3B60-4440-97CD-0799AEA632A2@me.com> Message-ID: On 09/11/2019 04:19, Eddwin Shoemo via Tutor wrote: > Hi. I was presented with a question and it has me stumped. In what way? You have et us a lot of code but no idea what you want to know. We will not do your homework for you. We will try to help steer you in the right direction. But few of us are likely to try running arbitrary code sent through the internet. So you need to tell us what happens, what you expected to happen plus any error messages you get(in full) > My PY and csv files are attached. The code is inline but the csv data seems to have gotten lost. The server doesn't trust many attachments. > Here is the question: > > Use the function, test_func1(x, b0, b1,b2,b3,b4,b5) ( to predict the SALES in terms of each of the 3 attributes: the TV, Radio, and Newspaper data. PLOT the results. > HINT: use the optimize library from scipy module. look for functions such as curve_fit. > > My Script: > > import csv > import pandas as pd > import numpy as np > from scipy import optimize > from scipy.optimize import curve_fit > import matplotlib.pyplot as plt #Used to plot > from sklearn.linear_model import LinearRegression, Ridge, Lasso > from sklearn.model_selection import cross_val_score, GridSearchCV # for optimuim MSE with Linear reg > > ########## Another data set -advertising > data2 = pd.read_csv('Advertising.csv') > print(data2.head()) # print the first 5 lines > #print(data2) > data2.drop(['Unnamed: 0'], axis=1, inplace=True)# drop the unnamed column (axis=1 for col, and 0 for rows) > print(data2.head()) > > #tv=data2['TV'].values # Alternative command for the one listed below > tv=data2[['TV']] > > #print(tv) > radio=data2['radio'].values > #radio=data2[['radio']] # Alternative method to command listed above > #print(radio) > newspaper=data2['newspaper'].values > #print(newspaper) > #sales=data2['sales'].values > sales=data2[['sales']] > > """ This effectively comments out most of the rest of the code. Is that what you intended? > reg1 = LinearRegression() > reg1.fit(tv, sales) > y_pred1 = reg1.predict(tv) > plt.figure() > plt.scatter(tv, sales, color='y') #plot real values > plt.plot(tv, y_pred1, "r.") #plot predicted values # The dot displays a dotted value > ## COLORS: one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'} > > reg2 = LinearRegression() > reg2.fit(radio.reshape(-1,1), sales) # Will use a column vector > y_pred2 = reg2.predict(radio.reshape(-1,1)) > plt.scatter(radio, sales, color='b') #plot real values > plt.plot(radio, y_pred2, c="black", linewidth=3) > plt.xlabel("The number of Ads (TV, Radio, and Newspaper)") # Label for the graph > plt.ylabel("The Sales") # Label for the graph > > reg3 = LinearRegression() > reg3.fit(newspaper.reshape(-1,1), sales) > y_pred3 = reg3.predict(newspaper.reshape(-1,1)) > plt.scatter(newspaper, sales, color='red') #plot real values > plt.plot(newspaper, y_pred3, "g.") > > ### Ridge Regression ############################################### > ridge = Ridge() > parameters_dict = {'alpha':[1e-12, 1e-7, 1e-3, 1e-2, 1, 4, 15, 20]} > rg_regressor = GridSearchCV(ridge,parameters_dict,scoring='neg_mean_squared_error',cv=5) > rg_regressor.fit(tv,sales) > y_pred4 = rg_regressor.predict(tv) > print('The best value for -Ridge- alpha is', rg_regressor.best_params_) > print('The minimuim MSE -Ridge-is',rg_regressor.best_score_) > plt.scatter(tv,sales,color='m') # Plot real values > plt.plot(tv, y_pred4, "k--") > > ### Lasso Regression ############################################### > lasso = Lasso() > parameters_dict_lasso = {'alpha':[1e-12, 1e-7, 1e-3, 1e-2, 1, 4, 15, 20]} > ls_regressor = GridSearchCV(lasso, parameters_dict_lasso,scoring='neg_mean_squared_error', cv=5) > ls_regressor.fit(tv,sales) > y_pred5 = ls_regressor.predict(tv) > print('The best value for Lasso alpha is', ls_regressor.best_params_) > print('The minimuim MSE -Lasso-is', ls_regressor.best_score_) > plt.scatter(tv,sales,color='m') # Plot real values > plt.plot(tv, y_pred5, "g--") # -- is how the plot is displayed > > ### Linear Regression with optimuim MSE ############################# > LR = LinearRegression() > MSEs=cross_val_score(LR,tv,sales,scoring='neg_mean_squared_error', cv=5) > avg_MSEs=np.mean(MSEs) > print('The average MSE-Linear', avg_MSEs) > LR.fit(tv, sales) > Pred = LR.predict(tv) > plt.scatter(tv,sales,color='m') # Plot real values > plt.plot(tv, Pred, "b--") # -- is how the plot is displayed > """ > > > def test_func1(x, b0, b1,b2,b3,b4,b5): > return (b0 + b1*x + b2*x**2+ b3*x**3 + b4*x**4+ b5*x**5) > > print('call the function:',test_func1(1,10,5,4,3,2,1)) This is all just plain math, no need for data or anything else. I have no idea how it relates to the question or the code above. -- 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 From beachkidken at gmail.com Mon Nov 11 17:51:01 2019 From: beachkidken at gmail.com (Ken Green) Date: Mon, 11 Nov 2019 17:51:01 -0500 Subject: [Tutor] Something new in line printing? Message-ID: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> I have not use Python printing for quite a while. In the meantime, I acquired a new printer, a HP OfficeJet 4652. Ran a program to print the output of a program and get the following error: lpr: Error - No default destination. ------------------ (program exited with code: 0) Press return to continue End of error message. I created a short program to print a simple line as follow: # sample_printing.py # 11/11/2019 import sys, os, time print datecode = "02042011" month = datecode[0:2] date? = datecode[2:4] year? = datecode[4:8] datecode = year + month + date pr = (os.popen("lpr", "w")) pr.write (datecode) pr.close() End of code. Thanks for pointing me into the right direction. Did something changed? Thanks guys and gals. Ken From david at lowryduda.com Mon Nov 11 18:43:51 2019 From: david at lowryduda.com (David Lowry-Duda) Date: Mon, 11 Nov 2019 18:43:51 -0500 Subject: [Tutor] Something new in line printing? In-Reply-To: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> Message-ID: <20191111234351.GA546@icerm-dld> Hello! > I acquired a new printer, a HP OfficeJet 4652. Ran a program to print > the output of a program and get the following error: > > lpr: Error - No default destination. lpr is not a python program. It is a protocol, often used through a tool (which is often written in C). Not every printer follows the LPD/LPR protocol. > pr = (os.popen("lpr", "w")) > pr.write (datecode) > pr.close() In your code, these lines open "lpr" as a process and writes some things to it. The first step towards debugging your printing would probably be to remove python and see if you can directly setup/use lpr from a command-line. Good luck! -- David Lowry-Duda From alan.gauld at yahoo.co.uk Mon Nov 11 19:13:06 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 Nov 2019 00:13:06 +0000 Subject: [Tutor] Something new in line printing? In-Reply-To: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> Message-ID: <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> On 11/11/2019 22:51, Ken Green wrote: > I have not use Python printing for quite a while. > In the meantime, I acquired a new printer, a HP > OfficeJet 4652. Ran a program to print the output > of a program and get the following error: This is as much an OS problem as it is python so it helps if you start off by telling us which OS you are using. I assume some kind of Unix derivative but which? > lpr: Error - No default destination. This is an OS level error not a Python issue. > # sample_printing.py > # 11/11/2019 > > import sys, os, time > > print This implies you are using Python 2.7? Might be worth considering a move to python 3 before support for v2 ends next year,. > datecode = "02042011" > month = datecode[0:2] > date?? = datecode[2:4] > year?? = datecode[4:8] > datecode = year + month + date Consider using the datetime module functions for date processing. But in this example slicing suffices I guess. > pr = (os.popen("lpr", "w")) os.popen is deprecated, the subprocess module is the recommended tool for this kind of task. It is much more powerful and flexible although somewhat more complex to use. But the module documentation gives several examples for most scenarios, including os.pipe. > pr.write (datecode) > pr.close() What happens here depends on your OS setup... Does it work outside python if you just cat a string into lpr? > Did something changed? Yes, your printer. Until we know that it is set up to work properly with lpr all bets are off. -- 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 From robertvstepp at gmail.com Mon Nov 11 19:53:46 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 Nov 2019 18:53:46 -0600 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: Message-ID: I thought I would follow up on my questions in case anyone is waiting with bated breath ~(:>)) The intent of my original post was primarily query about programming tools that it would be good for me to implement regardless of my specific editor and then to narrow it down to the best specific plugins for my actual editor. Judging from the lack of responses... Anyway here is what my best efforts came up with... On Fri, Nov 8, 2019 at 9:54 PM boB Stepp wrote: > > What Neovim plugins would any of you recommend as especially useful? > Searching online I have found a variety of opinions, but as to > functionality I have seen suggested: > 1) Git integration plugins. > 2) Code completion plugins. > 3) Linters. > 4) File explorer plugins. > 5) Bracket and quote completion plugins. > 6) Comments plugins. > 7) Code autoformatting plugins. > 8) PEP 8 compatibility plugins. > 9) Multiple cursor plugins. > 10) Code folding plugins. > 11) "Fuzzy" searching plugins. > 12) And on and on and ... After research I feel that the following plugin functionalities would improve my code quality and coding efficiency: 1) Enhanced syntax highlighting; 2) Code completion; 3) Code linting, especially checking for PEP 8 and 257 compatibility; 4) Code autoformatting; 5) Implementing type annotation and its checking. As best as I can tell from my research these are the functionalities that can make a meaningful difference in my code quality and coding efficiency. The other categories of tools in my mind fall into the category of "nice to haves" or "aesthetically pleasing". As to specific plugins for my chosen editor, Neovim: 1) I am trying out Semshi (https://github.com/numirias/semshi). The built-in syntax highlighting of Neovim seems to be fairly good, but Semshi seems to offer enhancement. My only thought is whether things will become too busy looking. 2) Code completion: I really struggled on this one. There are a variety of options. I finally went with Conquer of Completion (https://github.com/neoclide/coc.nvim), which is designed to take advantage of Neovim's asynchronous plugin running capabilities. I had trouble figuring out its configuration. Apparently it can use Jedi or Microsoft Language Services for its language syntax knowledge. I chose the former and had to install that via pip. 3) Code linting: This was another toughy. I finally went with ALE (= Asynchronous Lint Engine) (https://github.com/dense-analysis/ale), again designed upfront to take advantage of Neovim's asynchronous capabilities. Apparently ALE can run in the background, or, upon save, quite a large variety of linters and code formatters. For Python it supports autopep8, bandit, black, flake8, isort, mypy, prospector, pycodestyle, pydocstyle, pyflakes, pylama, pylint, pyls, pyre, reorder-python-imports, vulture and yapf. Of course all of these have to be installed for ALE to find them. Of these options I am going to try to run the flake8 package (Pyflakes, pycodestyle, Mccabe) as I edit, pylint upon save, black on save, mypy as I edit, pydocstyle as I type. 4) Code autoformatting: Black. 5) Type annotation checking: Study up on it and use MyPy. I am not entirely sure if I yet have everything configured correctly, but "stuff" is happening. Especially with ALE I am not certain yet whether everything that is supposed to be happening, is, in fact, happening. But interesting gutter markings are showing up in my buffers and when I go one of these lines a message appears in my editor's status bar. We'll see. As always, configuring these tools and figuring out how to properly use them is a painful process for me. Hopefully all of this will be helpful and not harmful. However, I notice that one of my source files that I copied and ran Black on made one of the linters unhappy for about four lines where it did not like the level of indentation chosen for a dictionary definition with some long entries. Also, is it considered bad style to define constants (using all caps) locally in a function definition? Did not like that one either. I might want to investigate some of the other tools that I currently see more as conveniences, but that will have to wait until I figure out what I have already installed. Cheers! -- boB From beachkidken at gmail.com Mon Nov 11 19:55:58 2019 From: beachkidken at gmail.com (Ken Green) Date: Mon, 11 Nov 2019 19:55:58 -0500 Subject: [Tutor] Something new in line printing? In-Reply-To: <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> Message-ID: On 11/11/19 7:13 PM, Alan Gauld via Tutor wrote: > On 11/11/2019 22:51, Ken Green wrote: >> I have not use Python printing for quite a while. >> In the meantime, I acquired a new printer, a HP >> OfficeJet 4652. Ran a program to print the output >> of a program and get the following error: > This is as much an OS problem as it is python so it helps > if you start off by telling us which OS you are using. > I assume some kind of Unix derivative but which? > >> lpr: Error - No default destination. > This is an OS level error not a Python issue. > >> # sample_printing.py >> # 11/11/2019 >> >> import sys, os, time >> >> print > This implies you are using Python 2.7? > Might be worth considering a move to python 3 before support > for v2 ends next year,. > >> datecode = "02042011" >> month = datecode[0:2] >> date?? = datecode[2:4] >> year?? = datecode[4:8] >> datecode = year + month + date > Consider using the datetime module functions for date > processing. But in this example slicing suffices I > guess. > >> pr = (os.popen("lpr", "w")) > os.popen is deprecated, the subprocess module is the recommended > tool for this kind of task. It is much more powerful and flexible > although somewhat more complex to use. But the module > documentation gives several examples for most scenarios, > including os.pipe. > >> pr.write (datecode) >> pr.close() > What happens here depends on your OS setup... > Does it work outside python if you just cat a string into lpr? > >> Did something changed? > Yes, your printer. > Until we know that it is set up to work properly with lpr > all bets are off. I'm sorry to have forgotten to mention my OS and Python model. I should have known better. Currently using Ubuntu 18.04.3 LTS and Python 2.7.15+.? Been using Ubuntu and Python2 before the new printer arrived in spring of 2019 and no problem was noted before then. Usage of printer other than Python2 was fine with current OS. I suppose I should try using Python 3.6.8 and see what gives. Thanks. Ken From PyTutor at danceswithmice.info Mon Nov 11 21:16:39 2019 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 12 Nov 2019 15:16:39 +1300 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: Message-ID: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> Sorry @boB, I guess it comes down to 'spare time'. Also, it's a conversation that often leads to time-sinking 'religious wars'. On 12/11/19 1:53 PM, boB Stepp wrote: > I thought I would follow up on my questions in case anyone is waiting > with bated breath ~(:>)) The intent of my original post was primarily > query about programming tools that it would be good for me to > implement regardless of my specific editor and then to narrow it down > to the best specific plugins for my actual editor. Judging from the > lack of responses... Anyway here is what my best efforts came > up with... Whilst I appreciate the point that vi[m] 'comes standard', it was presented as anything but standard - some systems opened in cmd mode, others with Insert on, ... It has been pointed-out to me (when I last trotted-out exactly that line) that most of the more popular Linux distributions (at least - and thus all of their 'derivatives') come with nano. (I'll say no more - see also 'religious wars') For reference: 1 I'd never choose to use MS-VScode, simply because of the first two letters, 2 I was persuaded to try VScodium, which was somewhat fun, but fairly soon afterwards a pip and/or pytest upgrade turned the effort into a (circular) farce; so 3 for the last years I've been using SublimeText (also with useful plug-ins), mainly to suit others in a particular dev.team, but also because folk in another team didn't like me doing web.dev from PyCharm. Go figure! > On Fri, Nov 8, 2019 at 9:54 PM boB Stepp wrote: >> What Neovim plugins would any of you recommend as especially useful? >> Searching online I have found a variety of opinions, but as to >> functionality I have seen suggested: >> 1) Git integration plugins. >> 2) Code completion plugins. >> 3) Linters. >> 4) File explorer plugins. >> 5) Bracket and quote completion plugins. >> 6) Comments plugins. >> 7) Code autoformatting plugins. >> 8) PEP 8 compatibility plugins. >> 9) Multiple cursor plugins. >> 10) Code folding plugins. >> 11) "Fuzzy" searching plugins. >> 12) And on and on and ... > > After research I feel that the following plugin functionalities would > improve my code quality and coding efficiency: 1) syntax highlighting; +1 2) Code completion; +1 3) Code linting, especially checking for PEP 8 and 257 compatibility; +1 (although "here be dragons", so being able to selectively turn-off specific checks is on the path of harmony and peaceful co-existence) 4) Code autoformatting; ? doesn't the (Python) editor do this 5) Implementing type annotation and its checking +1 although I see mypy as operating at the same time as/effectively a single unit with pytest (which I saw a 'missing' from your previous list; despite my using just such a plug-in 'all the time') Referring to your original list: >> 1) Git integration plugins. - this is handy, but it wouldn't worry me if it was a separate application - likely depends upon the operation's definition of CI >> 4) File explorer plugins. ? to do what >> 5) Bracket and quote completion plugins. +1 but surely part of the editor >> 6) Comments plugins. ? which do what >> 9) Multiple cursor plugins. +1 I find this very handy, from time-to-time (it's built-in to ST's editor) >> 10) Code folding plugins. +1 again: editor/built-in >> 11) "Fuzzy" searching plugins. ? which do what Something which I'd like is a view/map of my entire (Python) application's entities showing how the pieces of the 'jig-saw' fit together, as well as a 'click on the link' facility to 'jump there'. Perhaps it already exists but outside of my vocabulary... I don't have one right now, but have seen editors/IDEs with a similar structure of elements within a single/the current file. Not so interesting, but then perhaps that's because I don't like to have too much* in a single file - and perhaps end-up with too many* file-imports. * make of that what you will! > As to specific plugins for my chosen editor, Neovim: ... > will become too busy looking. Thus, the use for a 'distraction free' or 'edit only' mode - you can sing-along to this song: "built into the editor"! > Hopefully all of this will be helpful and not harmful. However, I > notice that one of my source files that I copied and ran Black on made > one of the linters unhappy for about four lines where it did not like > the level of indentation chosen for a dictionary definition with some > long entries. Also, is it considered bad style to define constants > (using all caps) locally in a function definition? Did not like that > one either. ...and what was I saying about the futility of acting (only) to make others happy? See also, selectively 'turning off' features. I have failed to re-locate an article which talked about Python and "IDEs" (as opposed to more humble, "editors"). The claim was that Python didn't need half of the "cruft" that other languages demand of their editors because (a) it is interpreted/evidence not available until run-time, and (b) it's a better language(?) - which I think is true - but won't be driving me back to Notepad as a dev.tool, any time soon! Your other comment is worthy of consideration: all these things take time to learn and then commit to muscle-memory/to become habits. Meantime, your Python dev work is slowed/brain-power is being absorbed off-task. I have colleagues who trade editors, sorry, maybe that should be IDEs, about as often as they change their under-wear. That comment about it taking time to come-up-to-speed seems to convince them that I am mad (quite possible - you don't have to be to work here - but it helps!). At least I can type faster than they, suffer less from FoMo, and am waaaaaay better-looking) Selecting good tools - and the right tool for the job, is a necessary component of efficiency. So, I'm convinced of the importance of a good editor - and that may vary by language or other choices. However, what's right for you, might not be for me - and vice-versa. It's "horses for courses" - not that I'm comparing your looks to a horse (front-end or back...) -- Regards =dn From PyTutor at DancesWithMice.info Mon Nov 11 21:36:18 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Tue, 12 Nov 2019 15:36:18 +1300 Subject: [Tutor] Something new in line printing? In-Reply-To: References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> Message-ID: <63199af3-b01f-f9c2-5204-41d912ea0c53@DancesWithMice.info> On 12/11/19 1:55 PM, Ken Green wrote: > On 11/11/19 7:13 PM, Alan Gauld via Tutor wrote: >> On 11/11/2019 22:51, Ken Green wrote: >>> I have not use Python printing for quite a while. >>> In the meantime, I acquired a new printer, a HP >>> OfficeJet 4652. Ran a program to print the output >>> of a program and get the following error: >> This is as much an OS problem as it is python so it helps >> if you start off by telling us which OS you are using. >> I assume some kind of Unix derivative but which? >> >>> lpr: Error - No default destination. >> This is an OS level error not a Python issue. >> > I'm sorry to have forgotten to mention my OS and Python model. > I should have known better. That's all right: then you were only confusing half of OS users and some pythonista, NOW you're upsetting HALF the WORLD! "Spring"??? That's what it is right now in the southern hemisphere, but was six months ago in the northern (and is practically unknown by those living 'in the middle'). > Currently using Ubuntu 18.04.3 LTS and Python 2.7.15+.? Been > using Ubuntu and Python2 before the new printer arrived in > spring of 2019 and no problem was noted before then. Usage of > printer other than Python2 was fine with current OS. I suppose > I should try using Python 3.6.8 and see what gives. Thanks. See earlier comments about "OS level". Are you able to print from other s/w under Ubuntu? (even the printer's Test Page) Modern Linux-es prefer to run printers through cups, and HP require an extra apt-get to receive the facilities to drive/monitor printers (and scanners, if appropriate). (?hpijs - Fedora's s/w name(s) may be different to Ubuntu/Debian's) Insert obligatory comment here - Python 2.n becomes 'end of life' in less than 50-days! (not that this appears to be a Py2/3 issue) -- Regards =dn From robertvstepp at gmail.com Mon Nov 11 21:53:10 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 Nov 2019 20:53:10 -0600 Subject: [Tutor] Something new in line printing? In-Reply-To: References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> Message-ID: On Mon, Nov 11, 2019 at 6:56 PM Ken Green wrote: > > > > On 11/11/19 7:13 PM, Alan Gauld via Tutor wrote: > > On 11/11/2019 22:51, Ken Green wrote: > >> I have not use Python printing for quite a while. > >> In the meantime, I acquired a new printer, a HP > >> OfficeJet 4652. Ran a program to print the output > >> of a program and get the following error: > > This is as much an OS problem as it is python so it helps > > if you start off by telling us which OS you are using. > > I assume some kind of Unix derivative but which? > > > >> lpr: Error - No default destination. > > This is an OS level error not a Python issue. I'll take a couple of shots in the dark. I am not fluent in *nix printing commands, but at work where I have to use the Solaris OS, whenever we change printers it is a hassle to change default printers. There is a graphical interface that allows printer configurations and it works fine for installed GUI applications, but when I am at the command line I have to use lpr explicitly and it requires switches that are different than in the GUI case. For instance, the "name" label on the graphical representation of the printer is _not_ the name assigned to lpr in the printer settings. Also, in this command line environment I have always had to explicitly use the correct printer name with lpr as there are multiple printers I could print to. Might this be your case as well? Or perhaps the old printer is still considered a valid printer even though it may no longer be connected to your system? And there have been other subtleties that I find as confusing as heck. However, some online research and re-reading the man page for lpr have so far enabled me to overcome the challenges to date. Sorry for being so vague, but I am not good at remembering details of things I only infrequently have to deal with. -- boB From beachkidken at gmail.com Mon Nov 11 22:00:44 2019 From: beachkidken at gmail.com (Ken Green) Date: Mon, 11 Nov 2019 22:00:44 -0500 Subject: [Tutor] Something new in line printing? In-Reply-To: <63199af3-b01f-f9c2-5204-41d912ea0c53@DancesWithMice.info> References: <21f87dde-415b-ad6f-b399-64787191b54d@gmail.com> <2a2efd9a-38e3-ada6-8797-8ad1e926e033@yahoo.co.uk> <63199af3-b01f-f9c2-5204-41d912ea0c53@DancesWithMice.info> Message-ID: <4c984304-a2d1-8f35-f2e2-24b6d39c67ce@gmail.com> On 11/11/19 9:36 PM, David L Neil via Tutor wrote: > On 12/11/19 1:55 PM, Ken Green wrote: >> On 11/11/19 7:13 PM, Alan Gauld via Tutor wrote: >>> On 11/11/2019 22:51, Ken Green wrote: >>>> I have not use Python printing for quite a while. >>>> In the meantime, I acquired a new printer, a HP >>>> OfficeJet 4652. Ran a program to print the output >>>> of a program and get the following error: >>> This is as much an OS problem as it is python so it helps >>> if you start off by telling us which OS you are using. >>> I assume some kind of Unix derivative but which? >>> >>>> lpr: Error - No default destination. >>> This is an OS level error not a Python issue. >>> > >> I'm sorry to have forgotten to mention my OS and Python model. >> I should have known better. > > That's all right: then you were only confusing half of OS users and > some pythonista, NOW you're upsetting HALF the WORLD! > > "Spring"??? That's what it is right now in the southern hemisphere, > but was six months ago in the northern (and is practically unknown by > those living 'in the middle'). > > >> Currently using Ubuntu 18.04.3 LTS and Python 2.7.15+.? Been >> using Ubuntu and Python2 before the new printer arrived in >> spring of 2019 and no problem was noted before then. Usage of >> printer other than Python2 was fine with current OS. I suppose >> I should try using Python 3.6.8 and see what gives. Thanks. > > See earlier comments about "OS level". Are you able to print from > other s/w under Ubuntu? (even the printer's Test Page) > > Modern Linux-es prefer to run printers through cups, and HP require an > extra apt-get to receive the facilities to drive/monitor printers (and > scanners, if appropriate). > (?hpijs - Fedora's s/w name(s) may be different to Ubuntu/Debian's) > Yes, I have been able to run print jobs in Ubuntu 18.04.3 except Python 2 and 3. Okay, you gave me a head up on apt-get something from HP. Will search tomorrow. That would be the best course of action to take. Failing that, will use my Windows 10 laptop that has Python 3 already installed. Thanks. > > Insert obligatory comment here - Python 2.n becomes 'end of life' in > less than 50-days! > (not that this appears to be a Py2/3 issue) From robertvstepp at gmail.com Mon Nov 11 22:33:57 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 Nov 2019 21:33:57 -0600 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> Message-ID: On Mon, Nov 11, 2019 at 8:17 PM DL Neil via Tutor wrote: > > Sorry @boB, I guess it comes down to 'spare time'. Also, it's a > conversation that often leads to time-sinking 'religious wars'. No apologies merited! Nor any intent to stir the editor wars pot either. I _did_ ask about Visual Studio Code editor in a _separate_ thread, but after trying out its Vim extension I decided to stick with what I have been using Vim/Neovim. And I only asked about VSC because of an article that popped up on my phone's news feed that suggested VSC is the most popular editor currently and that piqued my interest. > > On 12/11/19 1:53 PM, boB Stepp wrote: > > On Fri, Nov 8, 2019 at 9:54 PM boB Stepp wrote: > >> What Neovim plugins would any of you recommend as especially useful? > >> Searching online I have found a variety of opinions, but as to > >> functionality I have seen suggested: > >> 1) Git integration plugins. > >> 2) Code completion plugins. > >> 3) Linters. > >> 4) File explorer plugins. > >> 5) Bracket and quote completion plugins. > >> 6) Comments plugins. > >> 7) Code autoformatting plugins. > >> 8) PEP 8 compatibility plugins. > >> 9) Multiple cursor plugins. > >> 10) Code folding plugins. > >> 11) "Fuzzy" searching plugins. > >> 12) And on and on and ... > 3) Code linting, especially checking for PEP 8 and 257 compatibility; > +1 (although "here be dragons", so being able to selectively turn-off > specific checks is on the path of harmony and peaceful co-existence) I think I am already encountering the dragons... > 4) Code autoformatting; > ? doesn't the (Python) editor do this If we are speaking of the same thing, no. I am talking about tools like Black, yapf and autopep8, which actually edit/rearrange your code to make it conform to the selected coding style, usually PEP 8, but I found optionally yapf does a Facebook and Google style. > 5) Implementing type annotation and its checking > +1 although I see mypy as operating at the same time as/effectively a > single unit with pytest (which I saw a 'missing' from your previous > list; despite my using just such a plug-in 'all the time') I want to eventually switch to pytest, but I first want to master the standard library unittest module. For instance at work I will never have access to pytest because of their software installation prohibitions on our planning software platform. And I don't think I will lose anything as the pytest docs says it will happily run unittest tests. > >> 4) File explorer plugins. > ? to do what Apparently to have a "nicer" file system interface than what the editor natively supplies. > >> 5) Bracket and quote completion plugins. > +1 but surely part of the editor AFAIK, Vim/Neovim only natively highlights matching brackets, but will not complete them for you. However, there are at least a couple of plugins that will provide that functionality. > >> 6) Comments plugins. > ? which do what Apparently allow for some sort of shortcut to insert comments or convert non-commented lines into comments. > >> 9) Multiple cursor plugins. > +1 I find this very handy, from time-to-time (it's built-in to ST's editor) I had checked out ST a few years ago and at that time this was one of their oft-touted selling points. I played around with it a little then, but my coding sophistication did not match the editor's sophistication. > >> 10) Code folding plugins. > +1 again: editor/built-in I know Vim/Neovim comes with something along these lines, but the available plugins somehow offer something _more_. > >> 11) "Fuzzy" searching plugins. > ? which do what Apparently you type _something_ into the search area and it will look for _something_ in a variety of places: file names, contents of files, contents of your open buffers, etc. > Something which I'd like is a view/map of my entire (Python) > application's entities showing how the pieces of the 'jig-saw' fit > together, as well as a 'click on the link' facility to 'jump there'. > Perhaps it already exists but outside of my vocabulary... > > I don't have one right now, but have seen editors/IDEs with a similar > structure of elements within a single/the current file. Not so > interesting, but then perhaps that's because I don't like to have too > much* in a single file - and perhaps end-up with too many* file-imports. In my brief look at VSC it had, off to the side, a representation of the current file structure that would enable you to click inside it and go approximately to that location. I don't know what it might (or might not) display with a multi-file project loaded into the editor. > Your other comment is worthy of consideration: all these things take > time to learn and then commit to muscle-memory/to become habits. > Meantime, your Python dev work is slowed/brain-power is being absorbed > off-task. > > I have colleagues who trade editors, sorry, maybe that should be IDEs, > about as often as they change their under-wear. That comment about it > taking time to come-up-to-speed seems to convince them that I am mad > (quite possible - you don't have to be to work here - but it helps!). At > least I can type faster than they, suffer less from FoMo, and am > waaaaaay better-looking) Maybe this is a function of youth? My son, a teenager now, said to me something like, "Papa, just try Visual Studio Code and see how you like. If you don't like it, either try something else or go back to what you had been using. It's no big deal!" > Selecting good tools - and the right tool for the job, is a necessary > component of efficiency. So, I'm convinced of the importance of a good > editor - and that may vary by language or other choices. However, what's > right for you, might not be for me - and vice-versa. It's "horses for > courses" - not that I'm comparing your looks to a horse (front-end or > back...) +1 -- boB From PyTutor at danceswithmice.info Tue Nov 12 02:15:27 2019 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 12 Nov 2019 20:15:27 +1300 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> Message-ID: <0ccd1438-8e62-91e4-6088-712c96831ff6@DancesWithMice.info> On 12/11/19 4:33 PM, boB Stepp wrote: > On Mon, Nov 11, 2019 at 8:17 PM DL Neil via Tutor wrote: > I _did_ ask about Visual Studio Code editor in a _separate_ thread, > but after trying out its Vim extension I decided to stick with what I > have been using Vim/Neovim. And I only asked about VSC because of an > article that popped up on my phone's news feed that suggested VSC is > the most popular editor currently and that piqued my interest. On the basis of earlier comments, that's it then; but... >> On 12/11/19 1:53 PM, boB Stepp wrote: >>> On Fri, Nov 8, 2019 at 9:54 PM boB Stepp wrote: >>>> What Neovim plugins would any of you recommend as especially useful? >> 4) Code autoformatting; >> ? doesn't the (Python) editor do this > > If we are speaking of the same thing, no. I am talking about tools > like Black, yapf and autopep8, which actually edit/rearrange your code > to make it conform to the selected coding style, usually PEP 8, but I > found optionally yapf does a Facebook and Google style. We probably are not. However, within your list aren't there two sides of the same/similar coins? Some wait for us to type and then 'correct' the formatting; others are more up-front. So, my expectation is that having typed a colon, eg for...: the following Enter key will be augmented with an appropriate indentation 'into' the loop. Most modern/GUI editors seem to do this 'out of the box'. >> 5) Implementing type annotation and its checking >> +1 although I see mypy as operating at the same time as/effectively a >> single unit with pytest (which I saw a 'missing' from your previous >> list; despite my using just such a plug-in 'all the time') > > I want to eventually switch to pytest, but I first want to master the > standard library unittest module. For instance at work I will never > have access to pytest because of their software installation > prohibitions on our planning software platform. And I don't think I > will lose anything as the pytest docs says it will happily run > unittest tests. I believe so, but have not tested such a claim. Similarly, I may recall, but can't say if there are similar for the automatic save-and-test of other testing regimes, eg unittest, mocks... >> >> 4) File explorer plugins. >> ? to do what > > Apparently to have a "nicer" file system interface than what the > editor natively supplies. ST has a panel with both a list of the open files and a tree of the project's directory/ies. This is displayed optionally. >> >> 5) Bracket and quote completion plugins. >> +1 but surely part of the editor > > AFAIK, Vim/Neovim only natively highlights matching brackets, but will > not complete them for you. However, there are at least a couple of > plugins that will provide that functionality. Again, seems fairly standard out-of-the-box, amongst the modern crop. >> >> 6) Comments plugins. >> ? which do what > Apparently allow for some sort of shortcut to insert comments or > convert non-commented lines into comments. Ah, yes. Alt+E, M - whatever that is called in English. BTW the definition of "comment" varies by language, eg # or //. Which now makes me wonder if there are 'language' plug-ins or if the range that I use came as-standard. >> >> 9) Multiple cursor plugins. >> +1 I find this very handy, from time-to-time (it's built-in to ST's editor) > I had checked out ST a few years ago and at that time this was one of > their oft-touted selling points. I played around with it a little > then, but my coding sophistication did not match the editor's > sophistication. I didn't cover this earlier - without reference to personal abilities or skill-levels, but it is most relevant. It is a topic us-trainers often spend ages debating - and my earlier comment about the "cognitive load" of learning the editor IN ADDITION to your primary learning-objective - in this case, learning Python. I've been 'pushing' the idea of using an 'intro editor' at the beginning, to ease 'entry' (in the case of Python, on this list we have strong representation for Idle, but there are others - and if it were my training language I'd be pushing for an editor which shows the allocation of storage). However, the main argument-against, is that professionals are more likely to use a 'professional tool'. So, somewhere between 'beginner' and 'advanced' training, there's an extra task/aim - learning SublimeText, PyCharm, VScodium, or whatever. Who likes 'extra work'? So, the choice of editor (plus add-ons) should indeed be matched to the skills of the individual. >> >> 11) "Fuzzy" searching plugins. >> ? which do what > > Apparently you type _something_ into the search area and it will look > for _something_ in a variety of places: file names, contents of > files, contents of your open buffers, etc. Ah yes, when I first discovered this, I was SO pleased! The ability to search within all open files, within all the files of a project was revolutionary over the original 'within a single file' limitation. >> Your other comment is worthy of consideration: all these things take >> time to learn and then commit to muscle-memory/to become habits. >> Meantime, your Python dev work is slowed/brain-power is being absorbed >> off-task. >> >> I have colleagues who trade editors, sorry, maybe that should be IDEs, >> about as often as they change their under-wear. That comment about it >> taking time to come-up-to-speed seems to convince them that I am mad >> (quite possible - you don't have to be to work here - but it helps!). At >> least I can type faster than they, suffer less from FoMo, and am >> waaaaaay better-looking) > > Maybe this is a function of youth? My son, a teenager now, said to me > something like, "Papa, just try Visual Studio Code and see how you > like. If you don't like it, either try something else or go back to > what you had been using. It's no big deal!" Perhaps this is more than valid. How else will we realise 'progress', and stay up-to-date? However, a quick look to stay 'aware', has little in common with the motives and costs of editor-hoppers. At the risk of pouring fuel on the 'fire', I have to say that GUI editors (with keyboard short-cut keys) offer (me) an easier and equally powerful option (which may say more about my level of skill - per above). I'll maintain a basic skill in vi for server config maintenance and similar; but if I'm spending all day creating, I'd rather use an easy-to-view GUI tool. There are people who can make vi/emacs stand-up and beg (I'm not one of them) and more power to their right arm. However, there are others who would have to stay in the nursery unless they use a WYSIWYG tool. -- Regards =dn From cs at cskk.id.au Tue Nov 12 02:21:56 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 12 Nov 2019 18:21:56 +1100 Subject: [Tutor] Something new in line printing? In-Reply-To: <4c984304-a2d1-8f35-f2e2-24b6d39c67ce@gmail.com> References: <4c984304-a2d1-8f35-f2e2-24b6d39c67ce@gmail.com> Message-ID: <20191112072156.GA12024@cskk.homeip.net> On 11Nov2019 22:00, Ken Green wrote: >>Modern Linux-es prefer to run printers through cups, and HP require an >>extra apt-get to receive the facilities to drive/monitor printers (and >>scanners, if appropriate). >>(?hpijs - Fedora's s/w name(s) may be different to Ubuntu/Debian's) >> >Yes, I have been able to run print jobs in Ubuntu 18.04.3 except >Python 2 and 3. Okay, you gave me a head up on apt-get something from >HP. Will search tomorrow. That would be the best course of action to >take. Failing that, will use my Windows 10 laptop that has Python 3 >already installed. Thanks. You're testing the wrong thing. Your python programme is doing the equivalent of this shell command: echo hello | lpr Does that work from the command prompt? I suspect it will fail the same way as your Python programme, and when you have a working "lpr" command at the shell prompt, you will find that same command will work from within Python. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Tue Nov 12 04:39:22 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 Nov 2019 09:39:22 +0000 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: <0ccd1438-8e62-91e4-6088-712c96831ff6@DancesWithMice.info> References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> <0ccd1438-8e62-91e4-6088-712c96831ff6@DancesWithMice.info> Message-ID: On 12/11/2019 07:15, DL Neil via Tutor wrote: >>> >> 11) "Fuzzy" searching plugins. >>> ? which do what >> >> Apparently you type _something_ into the search area and it will look >> for _something_ in a variety of places: file names, contents of >> files, contents of your open buffers, etc. > > Ah yes, when I first discovered this, I was SO pleased! The ability to > search within all open files, within all the files of a project was > revolutionary over the original 'within a single file' limitation. Hasn't this been a feature of vi since its origins - possibly even a feature of ex, before vi even existed? You just run a grep command then step through the results visiting each line in turn. Or am I missing something? -- 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 From alan.gauld at btinternet.com Sun Nov 3 08:57:06 2019 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Nov 2019 13:57:06 +0000 Subject: [Tutor] regarding an error in the programming In-Reply-To: <5dbea548.1c69fb81.bc63e.3bcf@mx.google.com> References: <5dbea548.1c69fb81.bc63e.3bcf@mx.google.com> Message-ID: <0b89f3d6-eb34-904f-3261-26f3eb0f79c3@btinternet.com> On 03/11/2019 10:00, Garvit wrote: > Sir/ma?am, > I am a student and learning python as the programming language. > During the execution of a program about ?pie charts? an error is occurring i.e. > > File "C:\Users\yashmita jain\Desktop\garvit\computer\lib\site-packages\matplotlib\axes\_axes.py", line 2964, in pie > x += expl * math.cos(thetam) > TypeError: can't multiply sequence by non-int of type 'float' ?. > > How can I correct it? Do response quickly. Without seeing the code we have no idea what expl is but the error indicates it is a sequence of some sort (list? set? array? dict?). And the cosine is obviously going to be a float. As the error says, you can't multiply a sequence by a float. So you either need to change expl into something that can be multiplied by a float, or you need to iterate over the sequence multiplying each item individually. 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 From robertvstepp at gmail.com Tue Nov 12 12:43:05 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 12 Nov 2019 11:43:05 -0600 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? Message-ID: As I begin to play around with my newly installed editor tools, pylint does not like the following: def get_days_to_goal(goal_date_obj, start_date_obj=None): -- """Given a start date object and a goal date object, return the number of days it will take to attain a goal, counting the start date as one of these days. start_date_obj: A date object giving the start date for further calculations. goal_date_obj: A date object giving the date by which the goal should be attained. days_to_goal: An integer giving the number of days to achieve the goal, counting today as one of those days. """ if not start_date_obj: start_date_obj = date.today() -- COUNT_TODAY_TOO = 1 days_to_goal = (goal_date_obj - start_date_obj).days + COUNT_TODAY_TOO return days_to_goal Please ignore the flagging of the function docstring. I need to reread the docstring PEP. Apparently I need to make the first line of the docstring a short one-line summary sentence ending in a period. What I am asking about is the flagging of "COUNT_TODAY_TOO = 1" At the time I wrote this I did not want a magic number "1" to appear in the line beginning "days_to_goal = ..." So I thought it appropriate to label "1" as a constant with a meaningful name. But apparently according to this section of PEP 8 (https://www.python.org/dev/peps/pep-0008/#id48): Constants Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL. Scrolling through my entire module I see that I use COUNT_TODAY_TOO locally in one other function for a similar reason. The overall module length is 383 LOC. I guess the bottom line question is: What should I have done? N.B.: The copying process from editor to Gmail window has apparently reduced my indentation from 4 spaces to 2 due to the presence of the gutter where pylint (via the ALE plugin) displays its fun little flags. BEWARE! This installation of linting tools in my editor may lead to a significant increase in my Tutor postings while I puzzle over all of these newly flagged items in my code. -- boB From mats at wichmann.us Tue Nov 12 14:07:48 2019 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 12 Nov 2019 12:07:48 -0700 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: References: Message-ID: On 11/12/19 10:43 AM, boB Stepp wrote: > As I begin to play around with my newly installed editor tools, pylint > does not like the following: To just answer the question you asked first: > What I am asking about is the flagging of "COUNT_TODAY_TOO = 1" > I guess the bottom line question is: What should I have done? The style preference is to define such a constant (uppercased) at the module level - that is, at the top of the file somewhere, not inside the scope of a function definition. Particularly works well as you use it more than once. That should quiet pylint; or you could lowercase the name leaving it inside the function and pylint will think it's an "appropriate" local variable name. This is certainly a PEP-8 style thing, one I'm not personally in love with, but I'll happily go along if "PEP 8 conformance" is a requirement of what I'm working on. You can also configure pylint not to issue that particular warning - describing how is a bit out of scope for this message. === > > def get_days_to_goal(goal_date_obj, start_date_obj=None): > -- """Given a start date object and a goal date object, return the > number of > days it will take to attain a goal, counting the start date as > one of these > days. > > start_date_obj: A date object giving the start date for further > calculations. > > goal_date_obj: A date object giving the date by which the goal > should be > attained. > > days_to_goal: An integer giving the number of days to achieve the goal, > counting today as one of those days. > """ ... > Please ignore the flagging of the function docstring. I need to > reread the docstring PEP. Apparently I need to make the first line of > the docstring a short one-line summary sentence ending in a period. Blatantly failing to follow your instructions :) - right, one-line summary of what it does, followed by a blank line followed by a more detailed description, if such is needed. Since your longer description already says what the start and goal dates are, it seems the description of what it does is: Return the number of days it will take to attain a goal === Your function signature has two parameters, your docstring has three, which hints at a mismatch. Since you're playing with tools anyway, you could let the tools generate the initial docstring, then you can fill it in. Many editors have some way to generate a template docstring (often with a selector to pick the style of docstring markup you prefer), and for those that don't, the external Pyment tool could do that. I pasted just the function signature (followed by pass) into a file and it generated this: # Patch generated by Pyment v0.3.3 --- a/x.py +++ b/x.py @@ -1,3 +1,9 @@ def get_days_to_goal(goal_date_obj, start_date_obj=None): + """ + + :param goal_date_obj: + :param start_date_obj: (Default value = None) + + """ pass or if you prefer the more human-readable Google style: # Patch generated by Pyment v0.3.3 --- a/x.py +++ b/x.py @@ -1,3 +1,12 @@ def get_days_to_goal(goal_date_obj, start_date_obj=None): + """ + + Args: + goal_date_obj: + start_date_obj: (Default value = None) + + Returns: + + """ pass Don't document days_to_goal in the docstring - it's just a variable (an obvious one at that) internal to the function, which then is immediately returned. === Since this function has a very specific expectation of the types of the arguments, you could add type hints to say so, and your tooling should warn you if there are mismatches. e.g., assuming you've done from datetime import date so that date is a known symbol, you can rewrite your signature annotated like so: def get_days_to_goal(goal_date_obj: date, start_date_obj: date = None) -> int: I'm not (yet?) a "use type hints everywhere" guy, but this seems like a good place for it - your function would blow up if sent parameters of different types than a datetime.date, so it's useful to provide a way for at least some tooling to detect that - or else program the function a bit more defensively. From PyTutor at DancesWithMice.info Tue Nov 12 15:28:29 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Wed, 13 Nov 2019 09:28:29 +1300 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> <0ccd1438-8e62-91e4-6088-712c96831ff6@DancesWithMice.info> Message-ID: On 12/11/19 10:39 PM, Alan Gauld via Tutor wrote: > On 12/11/2019 07:15, DL Neil via Tutor wrote: > >>>> >> 11) "Fuzzy" searching plugins. >>>> ? which do what >>> >>> Apparently you type _something_ into the search area and it will look >>> for _something_ in a variety of places: file names, contents of >>> files, contents of your open buffers, etc. >> >> Ah yes, when I first discovered this, I was SO pleased! The ability to >> search within all open files, within all the files of a project was >> revolutionary over the original 'within a single file' limitation. > > Hasn't this been a feature of vi since its origins - possibly even a > feature of ex, before vi even existed? You just run a grep command > then step through the results visiting each line in turn. Or am I > missing something? No, not missing anything, per-se. I guess it depends upon how one sees 'the world'. The *nix tradition has been one of small tools, doing one job, and doing it well; and being able to pipe/chain them. However, that world is changing, eg the standardisation/uniformity, efficiency vs tradition etc argument that erupted when systemd arrived in Linux. "One...to rule them all". So, yes, it is possible to use vi for editing, grep for searching, python3 for interpreting, pytest for unit testing, etc, etc - under 'the best tool for the job' heading; whereas a GUI editor (with add-ons, per the OPs discussion) brings it all 'under one roof' or 'at the click of a mouse', eg "File | Save" might mean: save, then lint, then pytest. In the case of SublimeText (mentioned only because it is what I am currently using), a bulk-search causes a new editing tab to be opened and the results to be 'displayed' there, They can then be used for 'editing'; the ones I don't deal with 'now' can be thrown on a ToDo list, etc, etc - all from the comfort of my arm-chair (assuming I'm sitting there whilst editing).) From the constructivist theories of cognition, the GUI makes it easy for a beginner (or a 'forgetterer'!) to 'explore' and find/learn such powerful facilities for him-/her-self - 'there must be a better way; where is it?'. Whereas the *nix approach requires/d a very much less-obvious learning-path. [I haven't gone back to check, but compare/imagine explaining those two within the pages of a book! Which would you prefer? Which would enjoy the greatest likelihood of trainee-success/mastery?] Traditionally, a *nix/vi/emacs enthusiast would argue that (s)he can do things faster - in part by never lifting hands from keyboard (cf the GUI !usually being mouse-driven). However, in this (wider search) example, I doubt that claim would stand. NB I'm not saying one 'way' is completely correct and thus the other the epitome of evil. Per earlier comment: "horses for courses". [IMHO] you/yous should use (hah!) whichever tool 'works' for you. There are two riders (pun my word!): (i) that you be 'aware' of other opportunities (eg new products, developments to 'competitive products') and thus take advantage of productivity improvements as they become possible; and (ii) that what you do has a 'social fit' with the other members of your team. -- Regards =dn From robertvstepp at gmail.com Tue Nov 12 16:00:02 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 12 Nov 2019 15:00:02 -0600 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: References: Message-ID: On Tue, Nov 12, 2019 at 1:08 PM Mats Wichmann wrote: > > On 11/12/19 10:43 AM, boB Stepp wrote: > ...You can > also configure pylint not to issue that particular warning - describing > how is a bit out of scope for this message. A pity. Trying to determine how to configure pylint is what I am currently struggling with. I am not finding its official documentation easy to comprehend. > > def get_days_to_goal(goal_date_obj, start_date_obj=None): > > -- """Given a start date object and a goal date object, return the > > number of > > days it will take to attain a goal, counting the start date as > > one of these > > days. > > > > start_date_obj: A date object giving the start date for further > > calculations. > > > > goal_date_obj: A date object giving the date by which the goal > > should be > > attained. > > > > days_to_goal: An integer giving the number of days to achieve the goal, > > counting today as one of those days. > > """ > Your function signature has two parameters, your docstring has three, > which hints at a mismatch. Since you're playing with tools anyway, you > could let the tools generate the initial docstring, then you can fill it > in. Many editors have some way to generate a template docstring (often > with a selector to pick the style of docstring markup you prefer), and > for those that don't, the external Pyment tool could do that. I pasted > just the function signature (followed by pass) into a file and it > generated this: A good thought. I suppose over time I would save a fair amount of the same. > # Patch generated by Pyment v0.3.3 > > --- a/x.py > +++ b/x.py > @@ -1,3 +1,9 @@ > > def get_days_to_goal(goal_date_obj, start_date_obj=None): > + """ > + > + :param goal_date_obj: > + :param start_date_obj: (Default value = None) > + > + """ > pass > > > or if you prefer the more human-readable Google style: > > # Patch generated by Pyment v0.3.3 > > --- a/x.py > +++ b/x.py > @@ -1,3 +1,12 @@ > > def get_days_to_goal(goal_date_obj, start_date_obj=None): > + """ > + > + Args: > + goal_date_obj: > + start_date_obj: (Default value = None) > + > + Returns: > + > + """ > pass > > Don't document days_to_goal in the docstring - it's just a variable (an > obvious one at that) internal to the function, which then is immediately > returned. I just finished rereading PEP 257. I had forgotten that the intent is to help someone to understand the function's use, so what you say makes sense in that context. > === > > Since this function has a very specific expectation of the types of the > arguments, you could add type hints to say so, and your tooling should > warn you if there are mismatches. e.g., assuming you've done > > from datetime import date Yes. > so that date is a known symbol, you can rewrite your signature annotated > like so: > > def get_days_to_goal(goal_date_obj: date, start_date_obj: date = None) > -> int: I have enabled MyPy linting in my editor, but as I have not yet read up on type hints/annotations, I currently have none to lint. > > I'm not (yet?) a "use type hints everywhere" guy, but this seems like a > good place for it - your function would blow up if sent parameters of > different types than a datetime.date, so it's useful to provide a way > for at least some tooling to detect that - or else program the function > a bit more defensively. The program from which I drew today's posting was meant to be a simple, throw-away script to inspire me to actually read and study to the end the BIG BOOK OF PYTHON, i.e., "Learning Python, 5th ed." by Lutz. Alas! Its inspiration proved to be short-lived. However, in typical boB style, I could not resist toying around with it to apply things to it as I learned them. IF I were to use type annotations as you suggest, would there be any point to the more expansive docstring? The combination of type annotations with already very descriptive variable names seems to make any more description superfluous. -- boB From jf_byrnes at comcast.net Tue Nov 12 16:07:50 2019 From: jf_byrnes at comcast.net (Jim) Date: Tue, 12 Nov 2019 15:07:50 -0600 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> Message-ID: <5ae878ba-5446-de09-4b2f-72fcce9436c7@comcast.net> On 11/11/19 9:33 PM, boB Stepp wrote: Bob, I haven't read this article and maybe you have already seen it, but I noticed it as I was scrolling through Reddit. Maybe it will be interesting to you. https://realpython.com/vim-and-python-a-match-made-in-heaven/#vim-extensions Regards, Jim From cs at cskk.id.au Tue Nov 12 16:42:38 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 13 Nov 2019 08:42:38 +1100 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: References: Message-ID: <20191112214238.GA7284@cskk.homeip.net> On 12Nov2019 15:00, boB Stepp wrote: >On Tue, Nov 12, 2019 at 1:08 PM Mats Wichmann wrote: >> On 11/12/19 10:43 AM, boB Stepp wrote: >> ...You can >> also configure pylint not to issue that particular warning - describing >> how is a bit out of scope for this message. > >A pity. Trying to determine how to configure pylint is what I am >currently struggling with. I am not finding its official >documentation easy to comprehend. Fortunately you don't need to rely on that. Look at the output. Here's an example: % python -m pylint --rcfile=/Users/cameron/.pylintrc --disable=bad-whitespace,invalid-name,useless-object-inheritance cs/vt/blockify.py ************* Module python.cs.vt.blockify cs/vt/blockify.py:323:10: E1307: Argument 'builtins.NoneType' does not match format type 'd' (bad-string-format-type) and: % grep pylint cs/vt/blockify.py # pylint: disable=too-many-nested-blocks,too-many-statements # pylint: disable=too-many-branches,too-many-locals # pylint: disable=broad-except and there's the ~/.pylintrc file referenced above. So: 1: The error message recites the pylint rule which caused it, so "bad-string-format-type" is fires on line 323 of cs/vt/blockify.py. 2: You can disable specific rules for a whole file by providing them on the command line. 3: You can enable or disable rules for all files in a .pylintrc file. 4: You can disable specific rules for a suite in the code by preceeding that suite with a special "# pylint: " comment. Example: def blocked_chunks_of( chunks, scanner=None, min_block=None, max_block=None, histogram=None, ): ''' Generator which connects to a scanner of a chunk stream in order to emit low level edge aligned data chunks. [...] ''' # pylint: disable=too-many-nested-blocks,too-many-statements # pylint: disable=too-many-branches,too-many-locals with Pfx("blocked_chunks_of"): if min_block is None: min_block = MIN_BLOCKSIZE elif min_block < 8: So my blocked_chunks_of function is rather exceptional: it is the performance bottleneck of the cs.vt library, and is deliberately written as a single huge function with several local variables because breaking it up brings significant performance degradation just from the function call overhead. There's even a C extension function to aid performance for the really low level part, and it still benefits from being a big inline function. So this particular function turns off 4 of the pylint rules just for itself, leaving them active for all the other code. Cheers, Cameron Simpson From mats at wichmann.us Tue Nov 12 16:51:49 2019 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 12 Nov 2019 14:51:49 -0700 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: References: Message-ID: <3b776e69-5c54-6067-a233-58525c76f238@wichmann.us> On 11/12/19 2:00 PM, boB Stepp wrote: > The program from which I drew today's posting was meant to be a > simple, throw-away script to inspire me to actually read and study to > the end the BIG BOOK OF PYTHON, i.e., "Learning Python, 5th ed." by > Lutz. Alas! Its inspiration proved to be short-lived. However, in > typical boB style, I could not resist toying around with it to apply > things to it as I learned them. in my humble opinion, this is the way to go anyway - when something you read inspires you to tinker, stop there and do it. don't wait to tinker... often I find I tried something out and after doing so I "got" that little tidbit the way I hadn't absorbed from what I read, and then that in turn helped out later when reading something further. > > IF I were to use type annotations as you suggest, would there be any > point to the more expansive docstring? The combination of type > annotations with already very descriptive variable names seems to make > any more description superfluous. > I don't think the community has settled on a style there, but in any case it should be what's comfortable. I've been known to "tune out" descriptions that say too much without adding value in its repetition - something I'm painfully aware of as I'm prone to making that error as well (just see some past emails to tutor). More is not always better when it comes to docs... Better is Better :) certainly if you've used type hints, there's no need to add the type in the docstring as well. there's docstring style (or perhaps more precisely, syntax that the popular Sphinx tool understands) for that otherwise, either :param foo: description of foo :type foo: int which can be abbreviated if the type is simple enough: :param int foo: description of foo the type stuff there would be excessive if the signature were already type hinted. From alan.gauld at yahoo.co.uk Tue Nov 12 18:39:27 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 Nov 2019 23:39:27 +0000 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> <0ccd1438-8e62-91e4-6088-712c96831ff6@DancesWithMice.info> Message-ID: On 12/11/2019 20:28, David L Neil via Tutor wrote: >> Hasn't this been a feature of vi since its origins - possibly even a >> feature of ex, before vi even existed? You just run a grep command >> then step through the results visiting each line in turn. Or am I >> missing something? > > Traditionally, a *nix/vi/emacs enthusiast would argue that (s)he can do > things faster - in part by never lifting hands from keyboard (cf the GUI > !usually being mouse-driven). However, in this (wider search) example, I > doubt that claim would stand. I'm not sure why not. After all you never leave vi. You just execute a vimgrep (or OS grep if you prefer) command and it opens a buffer with the results. You then use the next/previous commands(:cn or :cp) to step through them in sequence(forward or back). If you use gvim it's even easier because you can just click with the mouse on each line to open the line in the edit window. Its exactly the same as when you compile code and step through the errors in the editor. Of course that doesn't apply to python since we don't compile as such... -- 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 From alan.gauld at yahoo.co.uk Tue Nov 12 18:47:43 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 Nov 2019 23:47:43 +0000 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: References: Message-ID: <7824cf9f-9e0c-8d2d-0019-b49f88196958@yahoo.co.uk> On 12/11/2019 21:00, boB Stepp wrote: > IF I were to use type annotations as you suggest, would there be any > point to the more expansive docstring? The combination of type > annotations with already very descriptive variable names seems to make > any more description superfluous. I'm not a big type hints fan so don't use them. But I'm curious to know what they do in the context of the help() function. If there is no docstring what do type hints generate in help messages? I suppose I should just try it!... -- 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 From alan.gauld at yahoo.co.uk Tue Nov 12 18:54:04 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 Nov 2019 23:54:04 +0000 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: <7824cf9f-9e0c-8d2d-0019-b49f88196958@yahoo.co.uk> References: <7824cf9f-9e0c-8d2d-0019-b49f88196958@yahoo.co.uk> Message-ID: On 12/11/2019 23:47, Alan Gauld via Tutor wrote: > On 12/11/2019 21:00, boB Stepp wrote: >> IF I were to use type annotations as you suggest, would there be any >> point to the more expansive docstring? The combination of type >> annotations with already very descriptive variable names seems to make >> any more description superfluous. > > I'm not a big type hints fan so don't use them. But I'm curious to know > what they do in the context of the help() function. If there is no > docstring what do type hints generate in help messages? > > I suppose I should just try it!... > > OK, Here it is: >>> def f(x: int, y:str) ->str: pass >>> help(f) Help on function f in module __main__: f(x:int, y:str) -> str >>> So it gives the function prototype. The docstring would, hopefully, add an explanation of what the function did (and that is more than just repeating the name of the function!) but for simple "obvious" functions the typehints might be sufficient. -- 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 From robertvstepp at gmail.com Tue Nov 12 19:31:32 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 12 Nov 2019 18:31:32 -0600 Subject: [Tutor] CONSTANTS -- Is it appropriate to use uppercase names within a function or method? In-Reply-To: <7824cf9f-9e0c-8d2d-0019-b49f88196958@yahoo.co.uk> References: <7824cf9f-9e0c-8d2d-0019-b49f88196958@yahoo.co.uk> Message-ID: On Tue, Nov 12, 2019 at 5:47 PM Alan Gauld via Tutor wrote: > > On 12/11/2019 21:00, boB Stepp wrote: > > IF I were to use type annotations as you suggest, would there be any > > point to the more expansive docstring? The combination of type > > annotations with already very descriptive variable names seems to make > > any more description superfluous. > > I'm not a big type hints fan so don't use them... I think I may become a fan, though a year or two ago I had a different mindset. Now that I have added mypy linting to my editor -- which occurs as I type -- your comment inspired me to force it to give me an error. So I took Mats suggestion: 21 def get_days_to_goal(goal_date_obj: date, start_date_obj: date = None) -> int: 22 """Return the number of days to achieve a goal. 23 24 goal_date_obj: A date object giving the date by which the goal should be 25 attained. 26 27 start_date_obj: A date object giving the start date for further 28 calculations. 29 """ And added this which before I barely hit generated an error: >> 30 goal_date_obj = 1 And at the bottom of the editor in a QuickFix window: 1 pages_per_day.py|30 col 21 error| Incompatible types in assignment (expression has type "int", variable has type "date") which showed up in a nice bright orange color due to my recently added Airline plugin. I have to say, I think I'm game for a little extra typing if (1) It makes the function definition and docstring more informative to a later code reader; and (2) It so quickly flags a potentially bad error without even having to run a test or compile the code. -- boB From nathan.delboux at gmail.com Tue Nov 12 17:58:47 2019 From: nathan.delboux at gmail.com (Nathan D'Elboux) Date: Wed, 13 Nov 2019 09:58:47 +1100 Subject: [Tutor] Monitor directory Python3 script Message-ID: Hi all, Im a student learning Python3. i have a small script id like to make that would monitor some subdirectories for any new files that are placed in there and move them to another directory on the same partition Im looking around for modules to use and came across shutil. This seems ok at first but seems more for batch processing so copy files from dir1 to dir2 every time cron runs which could lead to the same file being copied. Im thinking if i used pyinotify to monitor the directory then only newly added files would be copied and not everything before it every time it copies. So if i had a dir structure like this /Mountpoint/directory1/ /2019-01-10 /2019-01-11 /Mountpoint/directory2 /2019-01-10 /2019-01-11 /Mountpoint/destination/directoryX/ So i have new files being dropped into the current date directory each day until end of day, i just want to monitor the current date each day and copy anything that comes into it over to the /destination/directoryX/ dir as a big bucket. Then i can process them further once they have reached their destination Is Pyinotify the best module for this within Python3 ecosystem? This will be on a linux system, i have started on writing some of the code based on this article https://www.linode.com/docs/development/monitor-filesystem-events-with-pyinotify/ just after feedback as if this concept is the right approach or if theres a better easier way to do it i may be ignoring. Thanks Nathan From tysonwbarber at gmail.com Wed Nov 13 12:50:36 2019 From: tysonwbarber at gmail.com (Tyson Barber) Date: Wed, 13 Nov 2019 12:50:36 -0500 Subject: [Tutor] Python Help - While Loops Message-ID: Hello Tutor, I am currently trying to make a online purchasing system where someone can choose certain types of donuts to buy. I had no issue with them only buying one type, but I am not too familiar with loops, and I cannot seem to find any examples of such online. I just want the menu to reappear after they buy one option. My code so far looks like this: print ("Welcome to The Donut Shop!") shopping = input ("To start shopping, press s. To leave the store, press q.") while shopping == s: name = (input("Please enter your name to begin: ") print ("Please select a donut from the menu: ") print ("1. Chocolate") print ("2. Honey Crueller") print ("3. Apple Fritter") print ("4. Boston Cream") donut = int(input ("Please select a number from 1 to 5: ") under that I have a line to ask the quantity of what donut, and a equation for the price, which calculates the total, but it only works for one time. How would I properly create the while loop so that it does not keep giving me errors in the while statement? Thank you, Tyson From david at lowryduda.com Wed Nov 13 14:30:03 2019 From: david at lowryduda.com (David Lowry-Duda) Date: Wed, 13 Nov 2019 14:30:03 -0500 Subject: [Tutor] Python Help - While Loops In-Reply-To: References: Message-ID: <20191113193003.GA24531@icerm-dld> > My code so far looks like this: > > print ("Welcome to The Donut Shop!") > shopping = input ("To start shopping, press s. To leave the store, press > q.") > > while shopping == s: > name = (input("Please enter your name to begin: ") > print ("Please select a donut from the menu: ") > print ("1. Chocolate") > print ("2. Honey Crueller") > print ("3. Apple Fritter") > print ("4. Boston Cream") > donut = int(input ("Please select a number from 1 to 5: ") You probably mean while shopping == "s": # note the quotes around the "s" name = (input("Please enter your name to begin: ")) # with second ) Aside from that, this code should run. But it probably doesn't quite do what you want. Within the while loop, the code will keep on running from the top of the loop to the bottom. Thus you will repeatedly ask for the user's name and repeately ask them to select a donut. You do not ever re-assign shopping. I might expect your code to be organized a bit more like this: ```python # Only ask a name once print("Welcome!") name = input("Please enter your name: ") shopping = input("Enter s to keep shopping: ") while shopping == "s": # print donut descriptions donut = int(input("Which donut? ")) # do something with donut shopping = input("Enter s to keep shopping: ") ``` This while loop only asks for the name once, and re-sets the `shopping` variable based on user input. > under that I have a line to ask the quantity of what donut, and a > equation for the price, which calculates the total, but it only works > for one time. How would I properly create the while loop so that it > does not keep giving me errors in the while statement? It's not clear what other problems you're having or how to fix them, since we don't have the code. The code you originally posted would not have run once (due to the missing quotes around "s" and the missing right parenthesis). If you have code whose behavior you want to debug with the list, you should post that code. Good luck - DLD -- David Lowry-Duda From PyTutor at danceswithmice.info Wed Nov 13 15:51:48 2019 From: PyTutor at danceswithmice.info (DL Neil) Date: Thu, 14 Nov 2019 09:51:48 +1300 Subject: [Tutor] Python Help - While Loops In-Reply-To: References: Message-ID: <12e2eea3-9f7a-ab8e-d7be-780472d9bb12@DancesWithMice.info> On 14/11/19 6:50 AM, Tyson Barber wrote: > Hello Tutor, > > I am currently trying to make a online purchasing system where someone can > choose certain types of donuts to buy. I had no issue with them only buying > one type, but I am not too familiar with loops, and I cannot seem to find > any examples of such online.... Complementing @DLD's reply: searching the likes of StackOverflow and Google is unlikely to yield a 'training plan' to show you the way forward when you know little/are learning 'new stuff'. They are better-suited (perhaps) to answer specific questions in specific situations. You might better-benefit from a more structured approach, in the style of a text book: 1 whole Python books have been made available on-line 2 Python courses are available from MOOC platforms such as Coursera and edX 3 there are Python training platforms/courses from other sources Then there are off-line sources such as book-stores and libraries. -- Regards =dn From cs at cskk.id.au Wed Nov 13 15:55:50 2019 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 14 Nov 2019 07:55:50 +1100 Subject: [Tutor] Monitor directory Python3 script In-Reply-To: References: Message-ID: <20191113205550.GA82883@cskk.homeip.net> On 13Nov2019 09:58, Nathan D'Elboux wrote: >Im a student learning Python3. i have a small script id like to make >that would monitor some subdirectories for any new files that are >placed in there and move them to another directory on the same >partition > >Im looking around for modules to use and came across shutil. This >seems ok at first but seems more for batch processing so copy files >from dir1 to dir2 every time cron runs which could lead to the same >file being copied. You make a point of saying "on the same partition" (which I'll take to imply on the same filesystem). So you can just rename (mv) things instead of copying them; very fast. shutil is overkill for that, just use os.rename. >Im thinking if i used pyinotify to monitor the >directory then only newly added files would be copied and not >everything before it every time it copies. If you know you're on Linux that is reasonable. Again, possibly overkill. Personally, I'd just have a loop while ran os.listdir on your target directory with a 1 second sleep between loops. Notice anything new, move it. You can keep a set() of names representing the "old" stuff, not to be moved. So for me: os.listdir, os.rename, os.path.{basename,dirname,join} would cover everything required. And time.sleep for a short end of loop pause. Cheers, Cameron Simpson From eggo at hotmail.com Wed Nov 13 15:22:02 2019 From: eggo at hotmail.com (Eggo why) Date: Wed, 13 Nov 2019 20:22:02 +0000 Subject: [Tutor] How to get the element from a list Message-ID: Hi All, I have a list like this "line = [{'logname; : 'c:/tmp/alert', 'creationTime': 1573664115985},{'logname; : 'c:/tmp/audit', 'creationTime': 1573664115985}]" and I would like to retrieve the "logname" from it. What is the easiest way to do so? Gary From mats at wichmann.us Wed Nov 13 18:06:39 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 13 Nov 2019 16:06:39 -0700 Subject: [Tutor] How to get the element from a list In-Reply-To: References: Message-ID: On 11/13/19 1:22 PM, Eggo why wrote: > Hi All, > I have a list like this "line = [{'logname; : 'c:/tmp/alert', 'creationTime': 1573664115985},{'logname; : 'c:/tmp/audit', 'creationTime': 1573664115985}]" and I would like to retrieve the "logname" from it. What is the easiest way to do so? > > Gary let me take a wild guess: you're processing some json files? presuming what you're looking for is to extract *each* logname value, you can use a list comprehension. You're going to loop over the elements of the list, each of which is a dictionary, and index into each element to pick out the value of the 'logname' key. At the risk of "solving a homework problem" (which I hope this is not), that could look like this: lognames = [ d['logname'] for d in line ] if there's a chance not all of the elements (dictionaries) have 'logname' entries, then you need to get a little more sophisticated, or it will fail with an exception. From mats at wichmann.us Wed Nov 13 18:10:28 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 13 Nov 2019 16:10:28 -0700 Subject: [Tutor] Monitor directory Python3 script In-Reply-To: <20191113205550.GA82883@cskk.homeip.net> References: <20191113205550.GA82883@cskk.homeip.net> Message-ID: <02538bbd-7816-0564-1514-2e685f182bed@wichmann.us> On 11/13/19 1:55 PM, Cameron Simpson wrote: > On 13Nov2019 09:58, Nathan D'Elboux wrote: >> Im a student learning Python3. i have a small script id like to make >> that would monitor some subdirectories for any new files that are >> placed in there and move them to another directory on the same >> partition >> >> Im looking around for modules to use and came across shutil. This >> seems ok at first but seems more for batch processing so copy files >> from dir1 to dir2 every time cron runs which could lead to the same >> file being copied. > > You make a point of saying "on the same partition" (which I'll take to > imply on the same filesystem). So you can just rename (mv) things > instead of copying them; very fast. > > shutil is overkill for that, just use os.rename. > >> Im thinking if i used pyinotify to monitor the >> directory then only newly added files would be copied and not >> everything before it every time it copies. > > If you know you're on Linux that is reasonable. Again, possibly overkill. > > Personally, I'd just have a loop while ran os.listdir on your target > directory with a 1 second sleep between loops. Notice anything new, move > it. You can keep a set() of names representing the "old" stuff, not to > be moved. > > So for me: os.listdir, os.rename, os.path.{basename,dirname,join} would > cover everything required. And time.sleep for a short end of loop pause. There's almost certainly code out there that does what you want, possibly buried in a framework of some sort. But as David just said (after I wrote this but before sending), it may not be easy to find. I'm going to agree with Cameron that you can hack this together very simply. inotify is the "official" Linux API for what you want to do, but you don't necessarily need to use it. Use if it you expect to have a long-running process that wants to be very low-impact on the system. polling is plenty good for a small simple case. it doesn't scale particularly well. Sounded like small is all you were looking for. you can hack together something quick, and then if it needs to be used long term you can refactor it into a more robust tool with config options, able to run as a daemon process, whatever. (sorry for the complete lack of Python content in this reply, it's all generic commentary) From bouncingcats at gmail.com Wed Nov 13 18:32:08 2019 From: bouncingcats at gmail.com (David) Date: Thu, 14 Nov 2019 10:32:08 +1100 Subject: [Tutor] How to get the element from a list In-Reply-To: References: Message-ID: On Thu, 14 Nov 2019 at 09:46, Eggo why wrote: > > I have a list like this "line = [{'logname; : 'c:/tmp/alert', 'creationTime': 1573664115985},{'logname; : 'c:/tmp/audit', 'creationTime': 1573664115985}]" and I would like to retrieve the "logname" from it. What is the easiest way to do so? Step 1: fix the mismatched quotes. From alan.gauld at yahoo.co.uk Wed Nov 13 19:01:51 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 14 Nov 2019 00:01:51 +0000 Subject: [Tutor] Python Help - While Loops In-Reply-To: References: Message-ID: <348ad4aa-392a-b7b2-c337-4d8a5e1853bc@yahoo.co.uk> On 13/11/2019 17:50, Tyson Barber wrote: > one type, but I am not too familiar with loops, and I cannot seem to find > any examples of such online. I don't know where you are looking but just about every online tutorial (including mine) has a section on loops with copious examples. Loops are a fundamental building block of programming. Here is my page on the subject: http://www.alan-g.me.uk/l2p2/tutloops.htm The full tutorial is here http://www.alan-g.me.uk/l2p2 -- 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 From PyTutor at danceswithmice.info Wed Nov 13 19:05:25 2019 From: PyTutor at danceswithmice.info (DL Neil) Date: Thu, 14 Nov 2019 13:05:25 +1300 Subject: [Tutor] What editor tools (plugins/extensions) would you consider essential for efficient Python development? In-Reply-To: References: <82753831-afba-2acf-d6e7-062a8a924402@DancesWithMice.info> Message-ID: <27d5c1a8-d6ea-0935-d424-73a04aaf6335@DancesWithMice.info> @boB et al, there have been a couple of editor-related reports on PlanetPython during the last 24-hours:- Real Python: Getting Started With Python IDLE https://realpython.com/python-idle/ Quansight Labs Blog: File management improvements in Spyder4 https://labs.quansight.org/blog/2019/11/File-management-improvements-in-Spyder4/ -- Regards =dn From hamnahxbaig at gmail.com Thu Nov 14 13:14:41 2019 From: hamnahxbaig at gmail.com (Hamnah Baig) Date: Thu, 14 Nov 2019 18:14:41 +0000 Subject: [Tutor] Hi there! Message-ID: Hi! I'm wondering if you could help me with some programming code I'm struggling with. I need to create a code that lets me save the input and output in an external file. I'm also struggling to make my code identify between an odd number and an even number and when I did create one it seemed a bit too long and I feel like I'm confusing myself. Could you help me out please? :) -Hamnah x From alan.gauld at yahoo.co.uk Thu Nov 14 13:32:37 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 14 Nov 2019 18:32:37 +0000 Subject: [Tutor] Hi there! In-Reply-To: References: Message-ID: On 14/11/2019 18:14, Hamnah Baig wrote: > I need to create a code that lets me save the input and output in an > external file. OK, it will go something like this open input.txt and output.txt files read input from user (or whereverit comes from) write input to input.txt process input data write result to output.txt close input.txt and output.txt Now which parts of that are you struggling with? Do you not know how to do any of the steps? > I'm also struggling to make my code identify between an odd number and an > even number and when I did create one it seemed a bit too long and I feel > like I'm confusing myself. The normal way to do that is to perform an integer division by 2 and check the remainder part to see if it is zero. If the remainder is zero then the number must be even. Python has a couple of tools to help with that. The first is the divmod() function and the second is the modulo operator (%) which returns the remainder part only. If you need more help please get back to us. -- 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 From robertvstepp at gmail.com Sun Nov 17 00:32:25 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 16 Nov 2019 23:32:25 -0600 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? Message-ID: My best effort so far to type annotate the dictionary below is to use "Any" for the dictionary values. Is there a better substitute for "Any" that would more precisely type annotate these dictionary values? goal_year_params: Dict[str, Any] = { "greeting_msg": "Please enter the date by which you wish to attain" " your goal.\n", "input_prompt": "Enter year of your goal as an integer: ", "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1), "err_msg": "That is not a valid year. Please try again.", "conditions": [ ( lambda goal_year: goal_year < date.today().year, lambda goal_year: print( "Have you invented a time machine? If not, please enter a" " year that makes more sense!" ), ), ( lambda goal_year: goal_year >= date.today().year + 100, lambda goal_year: print( "Have you discovered the secret to eternal life? And how" " long is this book anyway? Please enter a year that" " makes more sense." ), ), ], } -- boB From alan.gauld at yahoo.co.uk Sun Nov 17 03:52:31 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 17 Nov 2019 08:52:31 +0000 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: Message-ID: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> On 17/11/2019 05:32, boB Stepp wrote: > My best effort so far to type annotate the dictionary below is to use > "Any" for the dictionary values. Is there a better substitute for > "Any" that would more precisely type annotate these dictionary values? To be honest I wouldn't even be trying I'd be more concerned with getting rid of such a messy dict and replacing it with a class. Type hints are no substitute for clean code. > goal_year_params: Dict[str, Any] = { > "greeting_msg": "Please enter the date by which you wish to attain" > " your goal.\n", > "input_prompt": "Enter year of your goal as an integer: ", > "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1), > "err_msg": "That is not a valid year. Please try again.", > "conditions": [ > ( > lambda goal_year: goal_year < date.today().year, > lambda goal_year: print( > "Have you invented a time machine? If not, > please enter a" > " year that makes more sense!" > ), > ), > ( > lambda goal_year: goal_year >= date.today().year + 100, > lambda goal_year: print( > "Have you discovered the secret to eternal life? > And how" > " long is this book anyway? Please enter a year that" > " makes more sense." > ), > ), > ], > } -- 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 From mats at wichmann.us Sun Nov 17 10:25:52 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 17 Nov 2019 08:25:52 -0700 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> Message-ID: <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> On 11/17/19 1:52 AM, Alan Gauld via Tutor wrote: > On 17/11/2019 05:32, boB Stepp wrote: >> My best effort so far to type annotate the dictionary below is to use >> "Any" for the dictionary values. Is there a better substitute for >> "Any" that would more precisely type annotate these dictionary values? > > To be honest I wouldn't even be trying I'd be more concerned with > getting rid of such a messy dict and replacing it with a class. > > Type hints are no substitute for clean code. Indeed. It turns out that classes are (normally) expressed as a dict, so there's not even that much to do to convert. Here's a simple class definition that contains some of your dict, based on snipping a few lines and just changing the syntax, no attempt to make any logic changes: class Foo(): greeting_msg = "Please enter the date by which you wish to attain your goal.\n" input_prompt = "Enter year of your goal as an integer: " date_value_err_ck = lambda goal_year: date(goal_year, 1, 1) err_msg = "That is not a valid year. Please try again." print(Foo.__dict__) And when run the print gives you (I took the liberty of putting in line breaks for readability): {'__module__': '__main__', 'greeting_msg': 'Please enter the date by which you wish to attain your goal.\n', 'input_prompt': 'Enter year of your goal as an integer: ', 'date_value_err_ck': at 0x7f6f3d224c20>, 'err_msg': 'That is not a valid year. Please try again.', '__dict__': , '__weakref__': , '__doc__': None} look familiar? :) Python has added some special symbols as well but otherwise it's the same thing. So the choice of "use a dict instead of a class definition because it's simpler" isn't actually always simpler, and here it isn't as you've ended up defining a list of tuples or lambdas. Like Alan, I shudder :). The keys in your dict are all strings, those would map directly to the attribute and method names in the class. In addition, the general guideline is if you're going to give it a name, don't use a lamba, because it's no longer anonymous at that point, defeating the only purpose lambda actually has. You've given the first lambda the name date_value_err_check, which means it's actually: def date_value_err_ck(self, goal_year): return date(goal_year, 1, 1) you'd probably expand that to do all the work of "conditons" (though we don't see the code to use it) As you your actual question... >> goal_year_params: Dict[str, Any] = { the two types that the dict's values can be per your snip is str or list, so start there: goal_year_params: Dict[str, Union(str, List)] if you want to go further you can then specify what the list consists of, etc. >> "greeting_msg": "Please enter the date by which you wish to attain" >> " your goal.\n", >> "input_prompt": "Enter year of your goal as an integer: ", >> "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1), >> "err_msg": "That is not a valid year. Please try again.", >> "conditions": [ >> ( >> lambda goal_year: goal_year < date.today().year, >> lambda goal_year: print( >> "Have you invented a time machine? If not, >> please enter a" >> " year that makes more sense!" >> ), >> ), >> ( >> lambda goal_year: goal_year >= date.today().year + 100, >> lambda goal_year: print( >> "Have you discovered the secret to eternal life? >> And how" >> " long is this book anyway? Please enter a year that" >> " makes more sense." >> ), >> ), >> ], >> } > > From samharzghaier at gmail.com Sun Nov 17 11:42:37 2019 From: samharzghaier at gmail.com (samhar zghaier) Date: Sun, 17 Nov 2019 17:42:37 +0100 Subject: [Tutor] Searching through text with multiple answers Message-ID: Hello I'm trying to make a search function through a small text file i created a function to split my text and put into a list my goal right now is to create a search function that shows tha the results of my search and confirms its existence in the text file. however i do not know how to do it if a few of my elements share a name can you help me please This is how i am splitting my text: def split_text(): file_name = "text.txt" list_of_everything = [] with open(file_name) as file: for line in file: list_of_everything.append(line.strip()) From akleider at sonic.net Sun Nov 17 12:21:30 2019 From: akleider at sonic.net (Alex Kleider) Date: Sun, 17 Nov 2019 09:21:30 -0800 Subject: [Tutor] Searching through text with multiple answers In-Reply-To: References: Message-ID: <4edd6a1e299ab5eed4b0c9fab988eda2@sonic.net> On 2019-11-17 08:42, samhar zghaier wrote: > Hello > I'm trying to make a search function through a small text file > i created a function to split my text and put into a list > > my goal right now is to create a search function that shows tha the > results of my search and confirms its existence in the text file. > however i > do not know how to do it if a few of my elements share a name Can you be more specific as to for what it is that you are searching? Some examples would be most helpful. Then you'd be in a better position to begin writing a function to accomplish same. > def split_text(): > file_name = "text.txt" > list_of_everything = [] > > with open(file_name) as file: > for line in file: > list_of_everything.append(line.strip()) What follows might be another way of traversing your file: def my_traverse(f_name): ret = [] with open(f_name, 'r') as f_obj: for line in f_obj: function_yet_to_be_written(line, ret) #look for something in line and if found, append to ret return ret From alan.gauld at yahoo.co.uk Sun Nov 17 13:05:30 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 17 Nov 2019 18:05:30 +0000 Subject: [Tutor] Searching through text with multiple answers In-Reply-To: <4edd6a1e299ab5eed4b0c9fab988eda2@sonic.net> References: <4edd6a1e299ab5eed4b0c9fab988eda2@sonic.net> Message-ID: <68a022e0-fec5-fe83-99bf-ea81ea551f9d@yahoo.co.uk> On 17/11/2019 17:21, Alex Kleider wrote: > Can you be more specific as to for what it is that you are searching? > Some examples would be most helpful. I agree, its impossible to tell what you want from the description. Show us a few lines of your file and the kinds of search data you use and the expected results. > What follows might be another way of traversing your file: And another using a list comprehension... def my_traverse(f_name, search_token): with open(f_name, 'r') as f_obj: return [function_yet_to_be_written(line,search_token) for line in f_obj] Where the function returns whatever result you are searching for. -- 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 From mats at wichmann.us Sun Nov 17 13:09:42 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 17 Nov 2019 11:09:42 -0700 Subject: [Tutor] Searching through text with multiple answers In-Reply-To: References: Message-ID: On 11/17/19 9:42 AM, samhar zghaier wrote: > Hello > I'm trying to make a search function through a small text file > i created a function to split my text and put into a list > > my goal right now is to create a search function that shows tha the > results of my search and confirms its existence in the text file. however i > do not know how to do it if a few of my elements share a name > > can you help me please > > This is how i am splitting my text: > > def split_text(): > file_name = "text.txt" > list_of_everything = [] > > with open(file_name) as file: > for line in file: > list_of_everything.append(line.strip()) while we're waiting for your replies to the questions already raised, you could rewrite this little snippet as follows: def split_text_from_file(file_name): with open(file_name, "r") as f: return [line.strip() for line in f] list_of_everything = split_text_from_file("text.txt") i.e. don't wire in the filename to read, and process more concisely. there's not much reason to write a function if you're not going to pass it some data to work on; the way you have it written your function has "side effects", even "magic" (that it knows the filename) and that's usually considered less than optimal. If you haven't gotten to list comprehensions yet, that's okay, but they're certainly worth learning eventually. From mikael.lenander1 at gmail.com Sun Nov 17 12:02:11 2019 From: mikael.lenander1 at gmail.com (Mikael Lenander) Date: Sun, 17 Nov 2019 19:02:11 +0200 Subject: [Tutor] A Problem with pygame Message-ID: Hi! I have a problem concerning the site package "pygame". I have tried to use it in Pycharm in order to create simple games but it doesn't work. I tried to download it through Pycharm settings/Project Interpreter but it didn't work (see photo 1). Then I downloaded it through the command prompt and it actually worked (see photo 2). But when I try to import the module through Pycharm, it claims that the module pygame doesn't exist (see photo 3). So what is the problem and what should I do? From robertvstepp at gmail.com Sun Nov 17 14:12:48 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 17 Nov 2019 13:12:48 -0600 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> Message-ID: On Sun, Nov 17, 2019 at 2:52 AM Alan Gauld via Tutor wrote: > > On 17/11/2019 05:32, boB Stepp wrote: > > My best effort so far to type annotate the dictionary below is to use > > "Any" for the dictionary values. Is there a better substitute for > > "Any" that would more precisely type annotate these dictionary values? > > To be honest I wouldn't even be trying I'd be more concerned with > getting rid of such a messy dict and replacing it with a class. > > Type hints are no substitute for clean code. Chastisement taken, accepted and fully merited! As I was staring at this program last night I was trying to recreate in memory its history of "development" (Ha!). Originally it was an extremely short program with no comments, no docstrings, no input validation. It was just a quick and dirty throw-away program to accept a start date, goal date to finish reading a book, and returned how many pages to read each day to attain the goal. But it proved to be a convenient program to open up at need and try out different things I was currently reading about. So one day I was reading about proper code documentation, so it got docstrings in profusion and a few comments and renaming of variables, etc. Then I read something about input validation so I added that. And then I got interested in lambdas and trying things with them that I did not know if they could do or not, such as be tools for evaluating Boolean expressions and some other things and so it got like this dictionary snippet shows. That was several months ago. And so now I am getting intrigued by type annotations, so it was time to open up the toy program and play around with these new critters. And as I tried to add type annotations I wondered what in the heck I was thinking before! So I had the same thought last night that you expressed and almost did not ask my question since I knew some comments would be made, But! I really was curious how such a beast would be properly type annotated. One thing that trying to write tests has taught me: If it is difficult to write tests for whatever, then something probably needs to be refactored/done better. As you might guess, I did not write any tests for this program. And apparently type annotations teach a similar sort of wisdom: If it is hard to figure out how to annotate a given block of code, something really, really stinks! From PyTutor at DancesWithMice.info Sun Nov 17 14:30:03 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Mon, 18 Nov 2019 08:30:03 +1300 Subject: [Tutor] A Problem with pygame In-Reply-To: References: Message-ID: <9be7da3b-21df-d5b1-8066-b03d185c0b21@DancesWithMice.info> Hi, On 18/11/19 6:02 AM, Mikael Lenander wrote: > Hi! > I have a problem concerning the site package "pygame". I have tried to use > it in Pycharm in order to create simple games but it doesn't work. I tried > to download it through Pycharm settings/Project Interpreter but it didn't > work (see photo 1). Then I downloaded it through the command prompt and it > actually worked (see photo 2). But when I try to import the module through > Pycharm, it claims that the module pygame doesn't exist (see photo 3). So > what is the problem and what should I do? Sadly, this is a text-only list. So, the attachments were removed. Recommend copy-pasting exactly what appears on the screen into the email msg. -- Regards =dn From mats at wichmann.us Sun Nov 17 14:39:01 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 17 Nov 2019 12:39:01 -0700 Subject: [Tutor] A Problem with pygame In-Reply-To: References: Message-ID: <52af5914-9bb7-e86e-d5b5-5d66be54235d@wichmann.us> On 11/17/19 10:02 AM, Mikael Lenander wrote: > Hi! > I have a problem concerning the site package "pygame". I have tried to use > it in Pycharm in order to create simple games but it doesn't work. I tried > to download it through Pycharm settings/Project Interpreter but it didn't > work (see photo 1). Then I downloaded it through the command prompt and it > actually worked (see photo 2). But when I try to import the module through > Pycharm, it claims that the module pygame doesn't exist (see photo 3). So > what is the problem and what should I do? This problem is *always* paths. In Pycharm, click "Python Console". Type: import sys sys.path From the command prompt type (Note: if this is Windows, substitute "py" for "python"): pythom -m pip list # make sure it actually shows pygame python >>> import sys >>> sys.path what's different? From robertvstepp at gmail.com Sun Nov 17 14:46:39 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 17 Nov 2019 13:46:39 -0600 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> Message-ID: On Sun, Nov 17, 2019 at 9:26 AM Mats Wichmann wrote: > I will get back later to the class refactoring operation, but thanks for your example. It will be quite helpful! > As you your actual question... > > >> goal_year_params: Dict[str, Any] = { > > the two types that the dict's values can be per your snip is str or > list, so start there: > > goal_year_params: Dict[str, Union(str, List)] A typo in there. "Union" has to have brackets not parentheses. I tried that and got an error: pages_per_day.py|93 col 9 error| Dict entry 2 has incompatible type "str": "Callable[[Any], date]"; expected "str": "Union[str, List[Any]]" Apparently because of the lambda outside of the list, I apparently must annotate them as "Callable". Before making my post on this to Tutor, I had tried variations on this, but I must have gotten lost in the twisted unnecessary complications of my dictionary! ~(:>)) I will play around some more with getting the annotations right before addressing refactoring the dictionary mess into something reasonable. Point of honor, ya know! > if you want to go further you can then specify what the list consists > of, etc. > > >> "greeting_msg": "Please enter the date by which you wish to attain" > >> " your goal.\n", > >> "input_prompt": "Enter year of your goal as an integer: ", > >> "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1), > >> "err_msg": "That is not a valid year. Please try again.", > >> "conditions": [ > >> ( > >> lambda goal_year: goal_year < date.today().year, > >> lambda goal_year: print( > >> "Have you invented a time machine? If not, > >> please enter a" > >> " year that makes more sense!" > >> ), > >> ), > >> ( > >> lambda goal_year: goal_year >= date.today().year + 100, > >> lambda goal_year: print( > >> "Have you discovered the secret to eternal life? > >> And how" > >> " long is this book anyway? Please enter a year that" > >> " makes more sense." > >> ), > >> ), > >> ], > >> } > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- boB From PyTutor at danceswithmice.info Sun Nov 17 17:04:33 2019 From: PyTutor at danceswithmice.info (DL Neil) Date: Mon, 18 Nov 2019 11:04:33 +1300 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> Message-ID: <8785b091-e35d-5843-7c8e-b8f81c50655b@DancesWithMice.info> On 18/11/19 8:12 AM, boB Stepp wrote: > On Sun, Nov 17, 2019 at 2:52 AM Alan Gauld via Tutor wrote: >> On 17/11/2019 05:32, boB Stepp wrote: >>> My best effort so far to type annotate the dictionary below is to use >> To be honest I wouldn't even be trying I'd be more concerned with >> getting rid of such a messy dict and replacing it with a class. >> >> Type hints are no substitute for clean code. > > Chastisement taken, accepted and fully merited! +1 So, as you later allude, the *first* problem was the lack of tests... > As I was staring at this program last night I was trying to recreate > in memory its history of "development" (Ha!). Originally it was an > extremely short program with no comments, no docstrings, no input > validation. It was just a quick and dirty throw-away program to ... > really was curious how such a beast would be properly type annotated. ...which led to the second problem, not so apparently recognised: that whilst this situation is common, in the spirit of learning-by-experimentation ("constructivism") and insatiable curiosity, we end-up with fairly-messy code. During 'the grand experiment' it was finally wrangled into some semblance of working code; and we moved-on. However, in coming back to it, the realisation of today's superior knowledge and capability should be turned-into a re-factored and improved version of the existing code. Thereafter, today's experiment will build upon a more stable foundation! (else, some risk that today's learning-mistakes are actually side-effects from time-before) > One thing that trying to write tests has taught me: If it is > difficult to write tests for whatever, then something probably needs > to be refactored/done better. +1 As you might guess, I did not write any > tests for this program. And apparently type annotations teach a > similar sort of wisdom: If it is hard to figure out how to annotate a > given block of code, something really, really stinks! +1 and yes, +1 on the class-upgrade (gives more leg-room on the plane!). We keep the dictionary structure and add (more flexible) functionality. [oops, in saying that, I fear @Alan will come-after me: So, in a bid to prevent the tooth- and claw-marks: a class *first* gives function and *then* offers us a dictionary/data-structure 'for free' (sound of running footsteps to be heard, leaving stage right, rapidly)...] -- Regards =dn From mats at wichmann.us Sun Nov 17 17:09:10 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 17 Nov 2019 15:09:10 -0700 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> Message-ID: On 11/17/19 12:46 PM, boB Stepp wrote: > Apparently because of the lambda outside of the list, I apparently > must annotate them as "Callable". yup, you're right, I spaced out that bit when trying to definitively tell you the value was either a str or a List. Sigh... From PyTutor at DancesWithMice.info Sun Nov 17 17:15:27 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Mon, 18 Nov 2019 11:15:27 +1300 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> Message-ID: On 18/11/19 11:09 AM, Mats Wichmann wrote: > On 11/17/19 12:46 PM, boB Stepp wrote: > >> Apparently because of the lambda outside of the list, I apparently >> must annotate them as "Callable". > > yup, you're right, I spaced out that bit when trying to definitively > tell you the value was either a str or a List.? Sigh... There's another rule-of-thumb right there: if the parameter list consists of many and/or many different types of data, perhaps consider 'another way'... I've never tried an experiment (or, never found the need), but does mypy (or...) actually and effectively, look two- and three-deep into data-structures? -- Regards =dn From mats at wichmann.us Sun Nov 17 17:32:00 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 17 Nov 2019 15:32:00 -0700 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> Message-ID: On 11/17/19 3:15 PM, David L Neil via Tutor wrote: > On 18/11/19 11:09 AM, Mats Wichmann wrote: >> On 11/17/19 12:46 PM, boB Stepp wrote: >> >>> Apparently because of the lambda outside of the list, I apparently >>> must annotate them as "Callable". >> >> yup, you're right, I spaced out that bit when trying to definitively >> tell you the value was either a str or a List.? Sigh... > > There's another rule-of-thumb right there: if the parameter list > consists of many and/or many different types of data, perhaps consider > 'another way'... > > > I've never tried an experiment (or, never found the need), but does mypy > (or...) actually and effectively, look two- and three-deep into > data-structures? it does if told to, but you're likely right that this indicates something is overly complex. From robertvstepp at gmail.com Sun Nov 17 17:59:14 2019 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 17 Nov 2019 16:59:14 -0600 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <95d60a78-907d-bb85-3bdf-973a8322cda3@wichmann.us> Message-ID: Well, I am stumped on trying to navigate type annotation for this overly complex dictionary. On Sun, Nov 17, 2019 at 4:09 PM Mats Wichmann wrote: > > On 11/17/19 12:46 PM, boB Stepp wrote: > > > Apparently because of the lambda outside of the list, I apparently > > must annotate them as "Callable". > > yup, you're right, I spaced out that bit when trying to definitively > tell you the value was either a str or a List. Sigh... I thought I would make the mypy and Mats suggested changes and have this: goal_year_params: Dict[str, Union[str, Callable[[int], date], List[Any]]] = { "greeting_msg": "Please enter the date by which you wish to attain" " your goal.\n", "input_prompt": "Enter year of your goal as an integer: ", "date_value_err_ck": lambda goal_year: date(goal_year, 1, 1), "err_msg": "That is not a valid year. Please try again.", "conditions": [ ( lambda goal_year: goal_year < date.today().year, lambda goal_year: print( "Have you invented a time machine? If not, please enter a" " year that makes more sense!" ), ), ( lambda goal_year: goal_year >= date.today().year + 100, lambda goal_year: print( "Have you discovered the secret to eternal life? And how" " long is this book anyway? Please enter a year that" " makes more sense." ), ), ], } >> goal_year = get_input(**goal_year_params) It flags this function call using the dictionary, goal_year_params and lists the following (seemingly) contradictory errors for this flagged statement: 1 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has incompatible type "**Dict[str, Union[str, Callable[[int], date], List[Any]]]"; expected "Callable[[int], date]" 2 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has incompatible type "**Dict[str, Union[str, Callable[[int], date], List[Any]]]"; expected "List[Any]" 3 pages_per_day.py|113 col 29 error| Argument 1 to "get_input" has incompatible type "**Dict[str, Union[str, Callable[[int], date], List[Any]]]"; expected "str" How can mypy be expecting 3 separate and different types? Does it not understand the syntax **goal_year_params ? Or, the probable answer, what is it I don't understand about mypy in this instance? -- boB From alan.gauld at yahoo.co.uk Sun Nov 17 19:50:19 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 18 Nov 2019 00:50:19 +0000 Subject: [Tutor] How to type annotate complex dictionary containing lambdas? In-Reply-To: <8785b091-e35d-5843-7c8e-b8f81c50655b@DancesWithMice.info> References: <62a8196b-15c1-bd60-97dd-9c916e205d52@yahoo.co.uk> <8785b091-e35d-5843-7c8e-b8f81c50655b@DancesWithMice.info> Message-ID: <89330afd-e724-1b71-2aae-2ed4641f177c@yahoo.co.uk> On 17/11/2019 22:04, DL Neil via Tutor wrote: > and yes, +1 on the class-upgrade (gives more leg-room on the plane!). We > keep the dictionary structure and add (more flexible) functionality. > > [oops, in saying that, I fear @Alan will come-after me: So, in a bid to > prevent the tooth- and claw-marks: a class *first* gives function and > *then* offers us a dictionary/data-structure 'for free' :-) But the good news in this case is that the required methods are there for the picking within the dict. All we need are a few useful names. -- 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 From samharzghaier at gmail.com Mon Nov 18 06:23:09 2019 From: samharzghaier at gmail.com (samhar zghaier) Date: Mon, 18 Nov 2019 12:23:09 +0100 Subject: [Tutor] Searching through text Message-ID: Hello again Since last time my text was not clear enough i will give a new try I'm trying to build a mini-library where i will be able to search by book title and writer amongst other things I thought that i would start by storing my books in a text file that will look something like this Book name, writer, number (to make choosing a bit easier) Due to the fact that i'm going to search through the entire text file multiple times i thought of writing a function Would you guys help me write a function to search through the text please This is how i am reading the text: def split_text(): list_of_everything = [] with open(file_name) as file: for line in file: list_of_everything.append(line.strip()) From adameyring at gmail.com Mon Nov 18 09:13:27 2019 From: adameyring at gmail.com (Adam Eyring) Date: Mon, 18 Nov 2019 09:13:27 -0500 Subject: [Tutor] Searching through text In-Reply-To: References: Message-ID: Hi, You might want to search through this free online book for some answers. The pattern matching chapter may be what you're looking for. https://automatetheboringstuff.com/ AME On Mon, Nov 18, 2019 at 6:23 AM samhar zghaier wrote: > Hello again > > Since last time my text was not clear enough i will give a new try > > I'm trying to build a mini-library where i will be able to search by book > title and writer amongst other things > > I thought that i would start by storing my books in a text file that will > look something like this > Book name, writer, number (to make choosing a bit easier) > > Due to the fact that i'm going to search through the entire text file > multiple times i thought of writing a function > Would you guys help me write a function to search through the text please > This is how i am reading the text: > > > def split_text(): > list_of_everything = [] > with open(file_name) as file: > for line in file: > list_of_everything.append(line.strip()) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Mon Nov 18 13:45:01 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 18 Nov 2019 18:45:01 +0000 Subject: [Tutor] Hi there! In-Reply-To: References: Message-ID: <95853780-1a9e-9147-cf3e-9ae33975f89e@yahoo.co.uk> On 18/11/2019 17:37, Hamnah Baig wrote: > Yes I'm unsure how to do all of these steps, could you please add some > more detail?? > > open input.txt and output.txt files Read about file handling in my tutorial in the files topic http://www.alan-g.me.uk/l2p2/tutfiles.htm The basic method looks like this: with open(filename) as alias: use alias here In your case you need two files opened so it will look like with open("input.txt","w") as ilog: with open(output.txt","w") as olog: # your code goes here > read input from user (or wherever it comes from) You can read about user input in my tutorial here: http://www.alan-g.me.uk/l2p2/tutinput.htm Assuming you are reading input from a user you use the input() function (raw_input in Python v2) variable = input(prompt) > write input to input.txt The link above covers writing to files too. You write to a file by converting the data to a string and then using the files write() method Something like: ilog.write(str(mydata)+'\n') #add newline for file > process input data Only you know what you want to do here! > write result to output.txt This is the same as writing the input above except you write to olog > close input.txt and output.txt The with statements automatically close the files so you don't need to do anything extra. Now you need to write some code and, if it doesn't work, post it here so we can see where you are going wrong. -- 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 From akleider at sonic.net Mon Nov 18 14:59:32 2019 From: akleider at sonic.net (Alex Kleider) Date: Mon, 18 Nov 2019 11:59:32 -0800 Subject: [Tutor] Searching through text In-Reply-To: References: Message-ID: <77820f6d053fefdb76170ee389c52ded@sonic.net> On 2019-11-18 03:23, samhar zghaier wrote: .... > I thought that i would start by storing my books in a text file that > will > look something like this > Book name, writer, number (to make choosing a bit easier) It seems you are going to use a csv file as your data base. The Python csv library might be something that could prove useful to you. If you change the above line to """ book_name,writer,number """ and make it the first line in your file then: csv.DictReader might prove especially useful. https://docs.python.org/3/library/csv.html It will also let you look at your data using open/libreOffice (or the MicroSoft equivalent.) From asad.hasan2004 at gmail.com Wed Nov 20 07:22:57 2019 From: asad.hasan2004 at gmail.com (Asad) Date: Wed, 20 Nov 2019 17:52:57 +0530 Subject: [Tutor] ArgumentParser - Command Line arguments Message-ID: Hi All , Need advice or code how to proceed . I am executing python script as . python script.py file1 file2 parser = argparse.ArgumentParser() parser.add_argument("first", type = str, help = 'Input for sqlinvocation.log') parser.add_argument("second", nargs="?") args = parser.parse_args() if len(sys.argv) == 3: args.first = sys.argv[1] args.second = sys.argv[2] else: print "enter the sqlinvocation log and qopatch or sqlpatch_catcon_0.log" print("first:", args.first) print("second:", args.second) If I execute python script.py file1 file2 1. It gives the following error : error: unrecognized arguments: 1 I few questions . How can perform the following : 1) How can the python script process file1 and file2 and run the script with those command line arguments and drop 1 and other inputs if provided by user. 2)How can the script to consider always file1 as args.first even if the command is executed as : python script.py file3 file1 Somehow if its find the file1 in the list of arguments it should consider as args.first and the other file as args.second Thanks, -- Asad Hasan +91 9582111698 From mats at wichmann.us Wed Nov 20 09:35:26 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 20 Nov 2019 07:35:26 -0700 Subject: [Tutor] ArgumentParser - Command Line arguments In-Reply-To: References: Message-ID: <12195c0a-6920-1904-cf32-6ec883047407@wichmann.us> On 11/20/19 5:22 AM, Asad wrote: > Hi All , > > Need advice or code how to proceed . I am executing python script > as . > > python script.py file1 file2 > > parser = argparse.ArgumentParser() > parser.add_argument("first", type = str, help = 'Input for > sqlinvocation.log') > parser.add_argument("second", nargs="?") > > args = parser.parse_args() > > if len(sys.argv) == 3: > args.first = sys.argv[1] > args.second = sys.argv[2] > > else: > > print "enter the sqlinvocation log and qopatch or sqlpatch_catcon_0.log" > > print("first:", args.first) > print("second:", args.second) > > > > > If I execute python script.py file1 file2 1. You have defined a parser to accept two positional arguments, one of which is optional. Positional arguments are just that: they are collected in the position in which they are declared. That means your usage looks like this: usage: [-h] first [second] giving it one more argument means it's an error, and you indeed get that errror. if you want to have it collect just "known" things and you deal with the rest yourself, use parse_known_args instead of parse_args - that will give you back the matched args filled in, plus an array of everything left over, which you can then ignore. So far so good... > > It gives the following error : > > error: unrecognized arguments: 1 > > I few questions . How can perform the following : > > 1) How can the python script process file1 and file2 and run the script > with those command line arguments and drop 1 and other inputs if provided > by user. > > 2)How can the script to consider always file1 as args.first even if the > command is executed as : > > python script.py file3 file1 this you can't do with positional args: the first positional argument you declare will always collect the first word on the command line (that wasn't first picked up by the options processing). Meaning this: > if len(sys.argv) == 3: > args.first = sys.argv[1] > args.second = sys.argv[2] is what it does anyway. not sure what that section is for, since you're just repeating what you already had argparse do... > > Somehow if its find the file1 in the list of arguments it should consider > as args.first and the other file as args.second since presumably file1 is a variable name, that is it won't be exactly "file1" except for your testcase, how would it know this? if you want to collect things in an order-independent way, you should use options; positional arguments are always ordered. Or, just ignore argparse and do it all manually from sys.argv, which it looked like you were starting to do anyway. I don't see that argparse is adding you any value here. However, to look at helping this out with an option: parser.add_argument("file1", type=str, help='Input for sqlinvocation.log') parser.add_argument("--file2", nargs=1, help='patch file') now you can run as all of these and it should work out: python script.py somefilename python script.py --patch=patchfilename somefilename python script.py somefilename --patch=patchfilename From mats at wichmann.us Wed Nov 20 09:50:23 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 20 Nov 2019 07:50:23 -0700 Subject: [Tutor] ArgumentParser - Command Line arguments In-Reply-To: <12195c0a-6920-1904-cf32-6ec883047407@wichmann.us> References: <12195c0a-6920-1904-cf32-6ec883047407@wichmann.us> Message-ID: sorry, I made some thinkos when retyping these bits (no coffee yet :) ), just take the ideas, not the literal typing.... > parser.add_argument("file1", type=str, help='Input for sqlinvocation.log') > parser.add_argument("--file2", nargs=1, help='patch file') > > now you can run as all of these and it should work out: > > python script.py somefilename > python script.py --patch=patchfilename somefilename > python script.py somefilename --patch=patchfilename From asad.hasan2004 at gmail.com Thu Nov 21 03:33:12 2019 From: asad.hasan2004 at gmail.com (Asad) Date: Thu, 21 Nov 2019 14:03:12 +0530 Subject: [Tutor] ArgumentParser - Command Line arguments In-Reply-To: References: Message-ID: Hi All ,, I have python 2.6.4 on solaris therefore I am not able to use the argparse . The reason behind using argparse was to capture exception and print the statements within the except block . So here is the logic if len(sys.argv) == 3: first = sys.argv[1] second = sys.argv[2] else: print "enter the file1 and file2 or file3" if re.search("errr_pattern", file1): try : with open (file2,'r') as f4 : print "Hi hello" except TyeError : print " Hi" so this works fine if i use python script.py file1 file2 ==> It gives the required results (hi Hello) if I use python script.py file1 it errors out : print("first:", file1) NameError: name 'file1' is not defined Instead I want it to print "hi" actually whatever statements are in except block . If I use this : python script.py file1 file2 parser = argparse.ArgumentParser() parser.add_argument("first", type = str, help = 'Input for sqlinvocation.log') parser.add_argument("second", nargs="?") args = parser.parse_args() if len(sys.argv) == 3: args.first = sys.argv[1] args.second = sys.argv[2] else: print "enter the file1 and file2 or file3" It works as expected but unfortunately I cannot use argparse I was looked for alternative :from optparse import OptionParser was unable to get sucess , Please advice and recommend, Thanks, On Wed, Nov 20, 2019 at 5:52 PM Asad wrote: > Hi All , > > Need advice or code how to proceed . I am executing python > script as . > > python script.py file1 file2 > > parser = argparse.ArgumentParser() > parser.add_argument("first", type = str, help = 'Input for > sqlinvocation.log') > parser.add_argument("second", nargs="?") > > args = parser.parse_args() > > if len(sys.argv) == 3: > args.first = sys.argv[1] > args.second = sys.argv[2] > > else: > > print "enter the sqlinvocation log and qopatch or > sqlpatch_catcon_0.log" > > print("first:", args.first) > print("second:", args.second) > > > > > If I execute python script.py file1 file2 1. > > It gives the following error : > > error: unrecognized arguments: 1 > > I few questions . How can perform the following : > > 1) How can the python script process file1 and file2 and run the script > with those command line arguments and drop 1 and other inputs if provided > by user. > > 2)How can the script to consider always file1 as args.first even if the > command is executed as : > > python script.py file3 file1 > > Somehow if its find the file1 in the list of arguments it should consider > as args.first and the other file as args.second > > > Thanks, > > > > -- > Asad Hasan > +91 9582111698 > -- Asad Hasan +91 9582111698 From mats at wichmann.us Thu Nov 21 10:11:13 2019 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 21 Nov 2019 08:11:13 -0700 Subject: [Tutor] ArgumentParser - Command Line arguments In-Reply-To: References: Message-ID: <81806997-3303-d1fb-0005-d50ff60d509c@wichmann.us> On 11/21/19 1:33 AM, Asad wrote: > Hi All ,, > > I have python 2.6.4 on solaris therefore I am not able to use the argparse . have you thought of compiling a more recent Python, to make life a little easier? optparse doesn't have the ability to ignore unknown arguments, although it's not horribly hard to teach it by overriding a method or two - you'd need to subclass OptionParser (I work on a project which does this, although only for long options). > It works as expected but unfortunately I cannot use argparse > > I was looked for alternative :from optparse import OptionParser > > was unable to get sucess , From sfsoc at gmx.net Fri Nov 22 03:22:58 2019 From: sfsoc at gmx.net (Patrick Frank) Date: Fri, 22 Nov 2019 09:22:58 +0100 Subject: [Tutor] strings features versus lists Message-ID: Hello, at the moment I mainly learn basics from the excellent book "Think Python". As I walked through chapter 10 (which is about lists) I wondered why are strings immutable? I would like to understand this design decision. Thanks in advance, P. From joel.goldstick at gmail.com Fri Nov 22 15:01:27 2019 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 22 Nov 2019 15:01:27 -0500 Subject: [Tutor] strings features versus lists In-Reply-To: References: Message-ID: On Fri, Nov 22, 2019 at 2:57 PM Patrick Frank wrote: > > Hello, > > at the moment I mainly learn basics from the excellent book "Think > Python". As I walked through chapter 10 (which is about lists) I > wondered why are strings immutable? I would like to understand this > design decision. > > Thanks in advance, > P. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor I'm not a language maven, like some others here, but the first thing that comes to mind for me is that immutable strings can be used as keys for dictionaries. -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From mats at wichmann.us Fri Nov 22 18:29:50 2019 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 22 Nov 2019 16:29:50 -0700 Subject: [Tutor] strings features versus lists In-Reply-To: References: Message-ID: <2e687ca9-06d5-a9e6-9c57-4c7f544f08be@wichmann.us> On 11/22/19 1:01 PM, Joel Goldstick wrote: > On Fri, Nov 22, 2019 at 2:57 PM Patrick Frank wrote: >> >> Hello, >> >> at the moment I mainly learn basics from the excellent book "Think >> Python". As I walked through chapter 10 (which is about lists) I >> wondered why are strings immutable? I would like to understand this >> design decision. >> >> Thanks in advance, >> P. > > I'm not a language maven, like some others here, but the first thing > that comes to mind for me is that immutable strings can be used as > keys for dictionaries. That's such an old decision the full rationale might be lost in the mists of time. Simplicity, reliability, predicatbility are pretty much what I've heard. The use as a dictionary key is absolutely part of the equation; dictionaries as key-value pairs accomplish effective lookups by hashing the key, and if the key can change (mutable), you could no longer use the hash of the key to reliably find the location of that entry. Dictionaries could have been designed differently, of course, but as you can see a different choice for strings would have cascading effects. The core of Python is written in C, which is notorious for problems with strings. Actually, it doesn't have string as a fundamental data type, it uses arrays of characters and has a long history of issues with "string" operations; Python went a different way by saying it will always make a new string, not try to modify things in place. From nuno_ferreira at orange.fr Sat Nov 23 11:28:56 2019 From: nuno_ferreira at orange.fr (Nuno Ferreira) Date: Sat, 23 Nov 2019 17:28:56 +0100 Subject: [Tutor] Help needed configuring IDLE Message-ID: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> Hello, Trying to use Python + IDLE on my MAC. Would appreciate help on this very basic issue : When I write a script and save it, IDLE wants by default to save it in ~/Documents (as listed by File > Path Browser). Is here a way to change this default location to something different ? Thanks in advance. From alan.gauld at yahoo.co.uk Sat Nov 23 13:10:16 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 23 Nov 2019 18:10:16 +0000 Subject: [Tutor] Help needed configuring IDLE In-Reply-To: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> References: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> Message-ID: <7cececa0-1fa5-9232-68c7-84698c2bcd2e@yahoo.co.uk> On 23/11/2019 16:28, Nuno Ferreira wrote: > Trying to use Python + IDLE on my MAC. > When I write a script and save it, IDLE wants by default to save it in ~/Documents I had a look at my Linux IDLE configuration files and I can't see any way to change it. FWIW, On my system it targets my home directory (~) rather than Documents (~/Documents). You could try asking on the IDLE-dev mailing list, these guys are pretty good at responding to these kinds of issues. -- 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 From mats at wichmann.us Sat Nov 23 13:25:09 2019 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 23 Nov 2019 11:25:09 -0700 Subject: [Tutor] Help needed configuring IDLE In-Reply-To: <7cececa0-1fa5-9232-68c7-84698c2bcd2e@yahoo.co.uk> References: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> <7cececa0-1fa5-9232-68c7-84698c2bcd2e@yahoo.co.uk> Message-ID: <31a6e9f5-849a-39a3-738b-ea46fab0c28a@wichmann.us> On 11/23/19 11:10 AM, Alan Gauld via Tutor wrote: > On 23/11/2019 16:28, Nuno Ferreira wrote: >> Trying to use Python + IDLE on my MAC. >> When I write a script and save it, IDLE wants by default to save it in ~/Documents > > I had a look at my Linux IDLE configuration files and I can't > see any way to change it. FWIW, On my system it targets my > home directory (~) rather than Documents (~/Documents). > > You could try asking on the IDLE-dev mailing list, > these guys are pretty good at responding to these kinds > of issues. > I recall from past times that you have to actually edit the code of IDLE. I don't even know where at this point; there's someplace it figures out a path by doing "expanduser" if I haven't forgotten the logic - the difference in paths between Linux and Mac is just what expanduser works out to. [sorry, from memory] From phillor9 at gmail.com Sat Nov 23 19:43:13 2019 From: phillor9 at gmail.com (Phil) Date: Sun, 24 Nov 2019 11:43:13 +1100 Subject: [Tutor] Help needed configuring IDLE In-Reply-To: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> References: <8D93C28B-DB69-4C56-9541-B5943B55F208@orange.fr> Message-ID: On 24/11/19 3:28 am, Nuno Ferreira wrote: > Hello, > > Trying to use Python + IDLE on my MAC. > > Would appreciate help on this very basic issue : If it's of any value to you, I use "save as" into my Python directory. -- Regards, Phil From mikael.lenander1 at gmail.com Mon Nov 25 07:20:10 2019 From: mikael.lenander1 at gmail.com (Mikael Lenander) Date: Mon, 25 Nov 2019 14:20:10 +0200 Subject: [Tutor] Issues with converting python file to .exe Message-ID: I tried to make an .exe file with python so that I could run my program without python and I could send it to my friends. I installed pyinstaller and gave this command through the command prompt successfully: "pyinstaller --onefile p??.py". The application is saved in the same folder as all the dependencies (for example images). However, when I try to open my program, this error occurs: "pygame 1.9.6 Hello from the pygame community. https://www.pygame.org/contribute.html Traceback (most recent call last): File "p??.py", line 91, in fontti = pygame.font.Font('freesansbold.ttf', 22) File "site-packages\pygame\pkgdata.py", line 50, in getResource File "site-packages\pkg_resources\__init__.py", line 1134, in resource_exists File "site-packages\pkg_resources\__init__.py", line 1404, in has_resource File "site-packages\pkg_resources\__init__.py", line 1472, in _has NotImplementedError: Can't perform this operation for unregistered loader type [2636] Failed to execute script p??". I tried the same thing with a more simple python file and everything worked flawlessly. So, I suppose there is an issue with my program "p??.py", but I don't know what the problem is. I don't know if it has anything to do with this but when I run the program "p??.py" through Pycharm, it throws at me this warning "DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python. screen.blit(vastus[i], (x, y))". Versions: pygame 1.9.6, python 3.8, pyinstaller 4.0.dev0+1eadfa55f2, windows Kind regards Mikael From oscar.j.benjamin at gmail.com Mon Nov 25 09:16:46 2019 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 25 Nov 2019 14:16:46 +0000 Subject: [Tutor] Issues with converting python file to .exe In-Reply-To: References: Message-ID: On Mon, 25 Nov 2019 at 13:54, Mikael Lenander wrote: > > I tried to make an .exe file with python so that I could run my program > without python and I could send it to my friends. I installed pyinstaller > and gave this command through the command prompt successfully: "pyinstaller > --onefile p??.py". The application is saved in the same folder as all the > dependencies (for example images). However, when I try to open my program, > this error occurs: > > "pygame 1.9.6 > Hello from the pygame community. https://www.pygame.org/contribute.html > Traceback (most recent call last): > File "p??.py", line 91, in > fontti = pygame.font.Font('freesansbold.ttf', 22) > File "site-packages\pygame\pkgdata.py", line 50, in getResource > File "site-packages\pkg_resources\__init__.py", line 1134, in > resource_exists > File "site-packages\pkg_resources\__init__.py", line 1404, in has_resource > File "site-packages\pkg_resources\__init__.py", line 1472, in _has > NotImplementedError: Can't perform this operation for unregistered loader > type > [2636] Failed to execute script p??". The problem is that pygame is attempting to load a font file. I guess that font file would normally be located somewhere among the pygame source code so pygame attempts to load it using pkg_resources which should be able to handle extracting it from e.g. a zip file. However given that the resource is embedded within the exe it seems that pkg_resources doesn't understand somehow how to extract the file from the exe. It looks like someone has some advice on this here: https://stackoverflow.com/a/36456473/9450991 I think that the one file approach for Python applications is generally problematic though so I would recommend investigating alternatives. Given that Python is now easily installed from the Windows app store you might want to see what it would take to make your program runnable for someone who already has Python installed. For example you could bundle pygame and your app code in a zip file and that might work better: https://docs.python.org/3/library/zipapp.html#creating-standalone-applications-with-zipapp -- Oscar From angeltheabad at gmail.com Tue Nov 26 13:57:46 2019 From: angeltheabad at gmail.com (Angel Abad) Date: Tue, 26 Nov 2019 10:57:46 -0800 Subject: [Tutor] tutoring Message-ID: hello, i was wondering if i could get help with my homework? this is the examples that was given in class that i don't seem to understand how to do. ###TODO 1: Convert this to a function that takes a string as ###input ### (i.e., the string to print, "Welcome..." in this example) ### and prints the string with the border. The function should ### not return anything. (Optional: take the border character to print ### and the # of characters, e.g., = and 50 in this example) print("=" * 50) print("Welcome to the GeoCalc program!") print("=" * 50) ### END TODO 1 print() ###TODO 2: Convert this to a function that takes the square side length ### as input, and returns the calculated area of the square. ### Save the value returned from the function in firstSquareArea firstSquareArea = squareSide ** 2 ### END TODO 2 squareSideString = input("Please enter the side length for your 2nd square: ") while not squareSideString.isdigit(): squareSideString = input("Please enter the side length for your 2nd square: ") squareSide = int(squareSideString) ###TODO 3: use your function from TODO 2 here. ### Save the value returned from the function in secondSquareArea secondSquareArea = squareSide ** 2 ### END TODO 3 triangleBaseString = input("Please enter the base for your 1st triangle: ") while not triangleBaseString.isdigit(): triangleBaseString = input("Please enter the base for your 1st triangle: ") triangleHeightString = input("Please enter the height for your 1st triangle: ") while not triangleHeightString.isdigit(): triangleHeightString = input("Please enter the height for your 1st triangle: ") triangleBase = float(triangleBaseString) triangleHeight = float(triangleHeightString) ###TODO 4: Convert this to a function that takes the triangle base AND height ### as inputs, and returns the calculated area of the triangle. ### Save the value returned from the function in firstTriangleArea firstTriangleArea = 1/2 * triangleBase * triangleHeight ### END TODO 4 triangleBaseString = input("Please enter the base for your 2nd triangle: ") while not triangleBaseString.isdigit(): triangleBaseString = input("Please enter the base for your 2nd triangle: ") triangleHeightString = input("Please enter the height for your 2nd triangle: ") while not triangleHeightString.isdigit(): triangleHeightString = input("Please enter the height for your 2nd triangle: ") triangleBase = float(triangleBaseString) triangleHeight = float(triangleHeightString) ###TODO 5: use your function from TODO 4 here. ### Save the value returned from the function in secondTriangleArea secondTriangleArea = 1/2 * triangleBase * triangleHeight ### END TODO 5 #Print the results print() print("Your first square area is:", firstSquareArea) print("Your second square area is:", secondSquareArea) print("Your first triangle area is:", firstTriangleArea) print("Your second triangle area is:", secondTriangleArea) print() ###TODO 6: Use your function from TODO 1 to print this message with border. print("=" * 50) print("Goodbye, thank you for using the GeoCalc program!") print("=" * 50) ### END TODO 6 thank you, angel From llawlis at uwo.ca Tue Nov 26 14:03:50 2019 From: llawlis at uwo.ca (Lisa Patricia Lawlis) Date: Tue, 26 Nov 2019 19:03:50 +0000 Subject: [Tutor] Help with Bulk Uploading to Internet Archive Message-ID: Hello, I'm new to Python (and coding in general!) and need some help bulk uploading to Internet Archive. I managed to install Python, Pip and configure my command line/terminal but I can't figure out how to properly upload files into Internet Archive (following their recommended steps). Any help is greatly appreciated! Thank you, Lisa From alan.gauld at yahoo.co.uk Tue Nov 26 18:11:55 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Nov 2019 23:11:55 +0000 Subject: [Tutor] Help with Bulk Uploading to Internet Archive In-Reply-To: References: Message-ID: On 26/11/2019 19:03, Lisa Patricia Lawlis wrote: > I managed to install Python, Pip and configure my command line/terminal > but I can't figure out how to properly upload files into Internet Archive > (following their recommended steps). You need to give us a lot more information. Which internet archive? Have you an internet address you can share? Following who's recommended steps? And what are these steps? Again do you have a web site? Or can you paste them in a mail? And show us your code. Even if it doesn't work it will help us see where you are going astray. Without that its pure guesswork and speculation. Also a note of your OS and Python version might prove useful. -- 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 From alan.gauld at yahoo.co.uk Tue Nov 26 18:19:08 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 26 Nov 2019 23:19:08 +0000 Subject: [Tutor] tutoring In-Reply-To: References: Message-ID: <0c5dcd72-4e66-a2d7-30b4-4f61a8392356@yahoo.co.uk> On 26/11/2019 18:57, Angel Abad wrote: > hello, i was wondering if i could get help with my homework? We will offer suggestions but we won't do it for you... > this is the examples that was given in class that i don't seem to > understand how to do. What exactly don't you understand? You need to be specific if you want specific answers. Did you try it and it didn't work? If so show us your code plus any error messages(in full) > > ###TODO 1: Convert this to a function that takes a string as ###input Do you know how to define a function that takes an input value? > ### (i.e., the string to print, "Welcome..." in this example) > ### and prints the string with the border. Do you know how to print a string with border? The code below is a pretty strong hint! > The function should ### not return anything. Do you know how to write a function that does not return anything? > (Optional: take the border character to print Let's leave the border and other stuff till later. Focus on one problem at a time... > print("=" * 50) > print("Welcome to the GeoCalc program!") > print("=" * 50) So can you put those three lines into a function that takes an input and returns nothing. Lets call it: print_welcome? So I should call it as print_welcome("Hello there!") and it should print out ======================================================= Hello there! ======================================================= Show us your best attempt and tell us what went wrong. Include any error messages in full. -- 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 From mats at wichmann.us Tue Nov 26 18:19:44 2019 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 26 Nov 2019 16:19:44 -0700 Subject: [Tutor] Help with Bulk Uploading to Internet Archive In-Reply-To: References: Message-ID: <7029d49a-01f0-14c0-c651-c6ad974afd21@wichmann.us> On 11/26/19 4:11 PM, Alan Gauld via Tutor wrote: > On 26/11/2019 19:03, Lisa Patricia Lawlis wrote: > >> I managed to install Python, Pip and configure my command line/terminal >> but I can't figure out how to properly upload files into Internet Archive >> (following their recommended steps). > > You need to give us a lot more information. > > Which internet archive? > Have you an internet address you can share? > > Following who's recommended steps? And what are these steps? > Again do you have a web site? Or can you paste them in a mail? to save a little bit of time, it's "the" Internet Archive (aka Wayback Machine), unless I completely misunderstood, and there's a Python module for talking to it (https://archive.org/services/docs/api/internetarchive/). We had corresponded briefly elsewhere before I pushed Lisa in this direction. Yes, description of efforts needed! > > And show us your code. > Even if it doesn't work it will help us see where you > are going astray. > > Without that its pure guesswork and speculation. > > Also a note of your OS and Python version might prove useful. > From PyTutor at DancesWithMice.info Tue Nov 26 18:34:14 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Wed, 27 Nov 2019 12:34:14 +1300 Subject: [Tutor] tutoring In-Reply-To: References: Message-ID: <38fd956b-b408-0da4-f141-9ad91103b040@DancesWithMice.info> On 27/11/19 7:57 AM, Angel Abad wrote: > hello, i was wondering if i could get help with my homework? > > this is the examples that was given in class that i don't seem to > understand how to do. > > ###TODO 1: Convert this to a function that takes a string as ###input > ### (i.e., the string to print, "Welcome..." in this example) > ### and prints the string with the border. The function should > ### not return anything. (Optional: take the border character to print > ### and the # of characters, e.g., = and 50 in this example) > print("=" * 50) > print("Welcome to the GeoCalc program!") > print("=" * 50) > ### END TODO 1 People here are happy to help - emphasis on the last word! Why don't we start with the first assignment? What you learn from that will probably help you with the others... What code have you written? (include it in your reply) If there are error messages, copy-paste them into your reply (do not use email-attachments, put it 'all' in 'here') What does the code do successfully? What does it not do (that it should)? If you are unable to formulate code at this stage, then study the Python documentation (also downloadable). 'Step 1' is likely to search for "input" (per the question-text). We look forward to helping you along your Python journey! WebRef: https://docs.python.org/3/ (adjust for the version you use)-- Regards =dn From samharzghaier at gmail.com Wed Nov 27 08:56:23 2019 From: samharzghaier at gmail.com (samhar zghaier) Date: Wed, 27 Nov 2019 14:56:23 +0100 Subject: [Tutor] function for loaning a book Message-ID: Hello I creatred a function to read each of my text files and read them into the program, im now trying to delete a certain item from one of the two lists i created and add it to the other one currently i am not able to add a certain element to the loan list This is the code i have currently written file_name = "text.txt" loan_file = "loan.txt" class Book(): def __init__(self, title, writer): self.title = title self.writer = writer def get_book_list(): book_list = [] with open(file_name, "r") as file: lines = file.readlines() for line in lines: line = line.split(",") book_list.append(Book(line[0].strip(), line[1].strip())) return book_list def get_loan_list(): loan_list = [] with open(loan_file, "r") as file: lines = file.readlines() for line in lines: line = line.split(",") loan_list.append(Book(line[0].strip(), line[1].strip())) return loan_list def loan_book(): book_title = input("What is the name of the book") info = book_list for line in info: if line.title == book_title: loan_list.append(line) def main(): loan_list = get_loan_list() book_list = get_book_list() loan_book() main() Help please From wrw at mac.com Wed Nov 27 11:04:26 2019 From: wrw at mac.com (William Ray Wing) Date: Wed, 27 Nov 2019 11:04:26 -0500 Subject: [Tutor] function for loaning a book In-Reply-To: References: Message-ID: > On Nov 27, 2019, at 8:56 AM, samhar zghaier wrote: > > Hello > I creatred a function to read each of my text files and read them into the > program, im now trying to delete a certain item from one of the two lists i > created and add it to the other one > currently i am not able to add a certain element to the loan list Please copy and paste the entire error message traceback and show us what happens. > This is the code i have currently written > > file_name = "text.txt" > loan_file = "loan.txt" > > class Book(): > def __init__(self, title, writer): > self.title = title > self.writer = writer > def get_book_list(): > book_list = [] > with open(file_name, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > book_list.append(Book(line[0].strip(), line[1].strip())) > return book_list > > def get_loan_list(): > loan_list = [] > with open(loan_file, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > loan_list.append(Book(line[0].strip(), line[1].strip())) > return loan_list > > def loan_book(): > book_title = input("What is the name of the book") > info = book_list > for line in info: > if line.title == book_title: > loan_list.append(line) > > > def main(): > loan_list = get_loan_list() > book_list = get_book_list() > loan_book() > main() > > > Help please > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From samharzghaier at gmail.com Wed Nov 27 11:06:21 2019 From: samharzghaier at gmail.com (Sam) Date: Wed, 27 Nov 2019 17:06:21 +0100 Subject: [Tutor] function for loaning a book In-Reply-To: References: Message-ID: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> There is no error, it?s just that it doesn?t work Sent from Mail for Windows 10 From: William Ray Wing Sent: Wednesday, 27 November 2019 17:04 To: samhar zghaier Cc: William R. Wing; Tutor Subject: Re: [Tutor] function for loaning a book > On Nov 27, 2019, at 8:56 AM, samhar zghaier wrote: > > Hello > I creatred a function to read each of my text files and read them into the > program, im now trying to delete a certain item from one of the two lists i > created and add it to the other one > currently i am not able to add a certain element to the loan list Please copy and paste the entire error message traceback and show us what happens. > This is the code i have currently written > > file_name = "text.txt" > loan_file = "loan.txt" > > class Book(): > def __init__(self, title, writer): > self.title = title > self.writer = writer > def get_book_list(): > book_list = [] > with open(file_name, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > book_list.append(Book(line[0].strip(), line[1].strip())) > return book_list > > def get_loan_list(): > loan_list = [] > with open(loan_file, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > loan_list.append(Book(line[0].strip(), line[1].strip())) > return loan_list > > def loan_book(): > book_title = input("What is the name of the book") > info = book_list > for line in info: > if line.title == book_title: > loan_list.append(line) > > > def main(): > loan_list = get_loan_list() > book_list = get_book_list() > loan_book() > main() > > > Help please > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wrw at mac.com Wed Nov 27 11:20:48 2019 From: wrw at mac.com (William Ray Wing) Date: Wed, 27 Nov 2019 11:20:48 -0500 Subject: [Tutor] function for loaning a book In-Reply-To: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> References: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> Message-ID: > On Nov 27, 2019, at 11:06 AM, Sam wrote: > > There is no error, it?s just that it doesn?t work > Please elaborate ?doesn?t work.? Does it not run? Does it run and not produce the expected result? Since we don?t have your data files, we can?t see what is happening. > Sent from Mail for Windows 10 > > From: William Ray Wing > Sent: Wednesday, 27 November 2019 17:04 > To: samhar zghaier > Cc: William R. Wing ; Tutor > Subject: Re: [Tutor] function for loaning a book > > > > > On Nov 27, 2019, at 8:56 AM, samhar zghaier wrote: > > > > Hello > > I creatred a function to read each of my text files and read them into the > > program, im now trying to delete a certain item from one of the two lists i > > created and add it to the other one > > currently i am not able to add a certain element to the loan list > > Please copy and paste the entire error message traceback and show us what happens. > > > > This is the code i have currently written > > > > file_name = "text.txt" > > loan_file = "loan.txt" > > > > class Book(): > > def __init__(self, title, writer): > > self.title = title > > self.writer = writer > > def get_book_list(): > > book_list = [] > > with open(file_name, "r") as file: > > lines = file.readlines() > > for line in lines: > > line = line.split(",") > > book_list.append(Book(line[0].strip(), line[1].strip())) > > return book_list > > > > def get_loan_list(): > > loan_list = [] > > with open(loan_file, "r") as file: > > lines = file.readlines() > > for line in lines: > > line = line.split(",") > > loan_list.append(Book(line[0].strip(), line[1].strip())) > > return loan_list > > > > def loan_book(): > > book_title = input("What is the name of the book") > > info = book_list > > for line in info: > > if line.title == book_title: > > loan_list.append(line) > > > > > > def main(): > > loan_list = get_loan_list() > > book_list = get_book_list() > > loan_book() > > main() > > > > > > Help please > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor From samharzghaier at gmail.com Wed Nov 27 11:30:31 2019 From: samharzghaier at gmail.com (samhar zghaier) Date: Wed, 27 Nov 2019 17:30:31 +0100 Subject: [Tutor] function for loaning a book In-Reply-To: References: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> Message-ID: Ok The code doesn't move the file to the loan list here is what my text file looks like: book of y, sma book of d, adam book of f, blag book of b, sam On Wed, 27 Nov 2019 at 17:20, William Ray Wing wrote: > > > On Nov 27, 2019, at 11:06 AM, Sam wrote: > > There is no error, it?s just that it doesn?t work > > > > Please elaborate ?doesn?t work.? Does it not run? Does it run and not > produce the expected result? Since we don?t have your data files, we can?t > see what is happening. > > > Sent from Mail for > Windows 10 > > *From: *William Ray Wing > *Sent: *Wednesday, 27 November 2019 17:04 > *To: *samhar zghaier > *Cc: *William R. Wing ; Tutor > *Subject: *Re: [Tutor] function for loaning a book > > > > > On Nov 27, 2019, at 8:56 AM, samhar zghaier > wrote: > > > > Hello > > I creatred a function to read each of my text files and read them into > the > > program, im now trying to delete a certain item from one of the two > lists i > > created and add it to the other one > > currently i am not able to add a certain element to the loan list > > Please copy and paste the entire error message traceback and show us what > happens. > > > > This is the code i have currently written > > > > file_name = "text.txt" > > loan_file = "loan.txt" > > > > class Book(): > > def __init__(self, title, writer): > > self.title = title > > self.writer = writer > > def get_book_list(): > > book_list = [] > > with open(file_name, "r") as file: > > lines = file.readlines() > > for line in lines: > > line = line.split(",") > > book_list.append(Book(line[0].strip(), line[1].strip())) > > return book_list > > > > def get_loan_list(): > > loan_list = [] > > with open(loan_file, "r") as file: > > lines = file.readlines() > > for line in lines: > > line = line.split(",") > > loan_list.append(Book(line[0].strip(), line[1].strip())) > > return loan_list > > > > def loan_book(): > > book_title = input("What is the name of the book") > > info = book_list > > for line in info: > > if line.title == book_title: > > loan_list.append(line) > > > > > > def main(): > > loan_list = get_loan_list() > > book_list = get_book_list() > > loan_book() > > main() > > > > > > Help please > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > From wrw at mac.com Wed Nov 27 11:40:50 2019 From: wrw at mac.com (William Ray Wing) Date: Wed, 27 Nov 2019 11:40:50 -0500 Subject: [Tutor] function for loaning a book In-Reply-To: References: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> Message-ID: > On Nov 27, 2019, at 11:30 AM, samhar zghaier wrote: > > Ok > The code doesn't move the file to the loan list > here is what my text file looks like: > book of y, sma > book of d, adam > book of f, blag > book of b, sam > Ah, OK, now liberally salt your code with print statements and watch what is happening. > > On Wed, 27 Nov 2019 at 17:20, William Ray Wing > wrote: > > >> On Nov 27, 2019, at 11:06 AM, Sam > wrote: >> >> There is no error, it?s just that it doesn?t work >> > > Please elaborate ?doesn?t work.? Does it not run? Does it run and not produce the expected result? Since we don?t have your data files, we can?t see what is happening. > > >> Sent from Mail for Windows 10 >> >> From: William Ray Wing >> Sent: Wednesday, 27 November 2019 17:04 >> To: samhar zghaier >> Cc: William R. Wing ; Tutor >> Subject: Re: [Tutor] function for loaning a book >> >> >> >> > On Nov 27, 2019, at 8:56 AM, samhar zghaier > wrote: >> > >> > Hello >> > I creatred a function to read each of my text files and read them into the >> > program, im now trying to delete a certain item from one of the two lists i >> > created and add it to the other one >> > currently i am not able to add a certain element to the loan list >> >> Please copy and paste the entire error message traceback and show us what happens. >> >> >> > This is the code i have currently written >> > >> > file_name = "text.txt" >> > loan_file = "loan.txt" >> > >> > class Book(): >> > def __init__(self, title, writer): >> > self.title = title >> > self.writer = writer >> > def get_book_list(): >> > book_list = [] >> > with open(file_name, "r") as file: >> > lines = file.readlines() >> > for line in lines: >> > line = line.split(",") >> > book_list.append(Book(line[0].strip(), line[1].strip())) >> > return book_list >> > >> > def get_loan_list(): >> > loan_list = [] >> > with open(loan_file, "r") as file: >> > lines = file.readlines() >> > for line in lines: >> > line = line.split(",") >> > loan_list.append(Book(line[0].strip(), line[1].strip())) >> > return loan_list >> > >> > def loan_book(): >> > book_title = input("What is the name of the book") >> > info = book_list >> > for line in info: >> > if line.title == book_title: >> > loan_list.append(line) >> > >> > >> > def main(): >> > loan_list = get_loan_list() >> > book_list = get_book_list() >> > loan_book() >> > main() >> > >> > >> > Help please >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > https://mail.python.org/mailman/listinfo/tutor From mats at wichmann.us Wed Nov 27 11:46:11 2019 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 27 Nov 2019 09:46:11 -0700 Subject: [Tutor] function for loaning a book In-Reply-To: References: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> Message-ID: <96d34ba6-a7e4-2bf7-a0fe-aefe63faa307@wichmann.us> On 11/27/19 9:30 AM, samhar zghaier wrote: > Ok > The code doesn't move the file to the loan list > here is what my text file looks like: > > book of y, sma > book of d, adam > book of f, blag > book of b, sam at the most basic level, you don't do anything with the results of the operation. >>> This is the code i have currently written >>> >>> file_name = "text.txt" >>> loan_file = "loan.txt" >>> >>> class Book(): >>> def __init__(self, title, writer): >>> self.title = title >>> self.writer = writer >>> def get_book_list(): >>> book_list = [] >>> with open(file_name, "r") as file: >>> lines = file.readlines() >>> for line in lines: >>> line = line.split(",") >>> book_list.append(Book(line[0].strip(), line[1].strip())) >>> return book_list >>> >>> def get_loan_list(): >>> loan_list = [] >>> with open(loan_file, "r") as file: >>> lines = file.readlines() >>> for line in lines: >>> line = line.split(",") >>> loan_list.append(Book(line[0].strip(), line[1].strip())) >>> return loan_list >>> >>> def loan_book(): >>> book_title = input("What is the name of the book") >>> info = book_list >>> for line in info: >>> if line.title == book_title: >>> loan_list.append(line) and? your local copy of loan_list (see Note on that which follows) has the line appended... but that is not saved back to your loan file so it's just lost once the program quits. >>> def main(): >>> loan_list = get_loan_list() >>> book_list = get_book_list() >>> loan_book() and here: how can you tell what changed? you don't do anything with the updated list so it's not in the file, and you don't print any results here either, so there's no way to tell if anything changed. Note: you obtain loan_list and book_list, but you don't pass them to loan_book, so you should actually be getting an error in loan_book. they're not globals... >>> main() there are other comments to make, but let's keep it to just the question. From samharzghaier at gmail.com Wed Nov 27 11:49:06 2019 From: samharzghaier at gmail.com (Sam) Date: Wed, 27 Nov 2019 17:49:06 +0100 Subject: [Tutor] function for loaning a book In-Reply-To: <96d34ba6-a7e4-2bf7-a0fe-aefe63faa307@wichmann.us> References: <5dde9eff.1c69fb81.b88a2.637c@mx.google.com> <96d34ba6-a7e4-2bf7-a0fe-aefe63faa307@wichmann.us> Message-ID: <5ddea903.1c69fb81.cf81a.76cf@mx.google.com> Oh now I understand, wo the value of the book I loaned Is added to the list within the program but never written to my text file. Thank you for your help Sent from Mail for Windows 10 From: Mats Wichmann Sent: Wednesday, 27 November 2019 17:46 To: tutor at python.org Subject: Re: [Tutor] function for loaning a book On 11/27/19 9:30 AM, samhar zghaier wrote: > Ok > The code doesn't move the file to the loan list > here is what my text file looks like: > > book of y, sma > book of d, adam > book of f, blag > book of b, sam at the most basic level, you don't do anything with the results of the operation. >>> This is the code i have currently written >>> >>> file_name = "text.txt" >>> loan_file = "loan.txt" >>> >>> class Book(): >>> def __init__(self, title, writer): >>> self.title = title >>> self.writer = writer >>> def get_book_list(): >>> book_list = [] >>> with open(file_name, "r") as file: >>> lines = file.readlines() >>> for line in lines: >>> line = line.split(",") >>> book_list.append(Book(line[0].strip(), line[1].strip())) >>> return book_list >>> >>> def get_loan_list(): >>> loan_list = [] >>> with open(loan_file, "r") as file: >>> lines = file.readlines() >>> for line in lines: >>> line = line.split(",") >>> loan_list.append(Book(line[0].strip(), line[1].strip())) >>> return loan_list >>> >>> def loan_book(): >>> book_title = input("What is the name of the book") >>> info = book_list >>> for line in info: >>> if line.title == book_title: >>> loan_list.append(line) and? your local copy of loan_list (see Note on that which follows) has the line appended... but that is not saved back to your loan file so it's just lost once the program quits. >>> def main(): >>> loan_list = get_loan_list() >>> book_list = get_book_list() >>> loan_book() and here: how can you tell what changed? you don't do anything with the updated list so it's not in the file, and you don't print any results here either, so there's no way to tell if anything changed. Note: you obtain loan_list and book_list, but you don't pass them to loan_book, so you should actually be getting an error in loan_book. they're not globals... >>> main() there are other comments to make, but let's keep it to just the question. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Wed Nov 27 11:59:53 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 27 Nov 2019 16:59:53 +0000 Subject: [Tutor] function for loaning a book In-Reply-To: References: Message-ID: <4838207c-60af-f4da-1e60-30d7350be895@yahoo.co.uk> On 27/11/2019 13:56, samhar zghaier wrote: > file_name = "text.txt" > loan_file = "loan.txt" > > class Book(): > def __init__(self, title, writer): > self.title = title > self.writer = writer > def get_book_list(): > book_list = [] > with open(file_name, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > book_list.append(Book(line[0].strip(), line[1].strip())) > return book_list > > def get_loan_list(): > loan_list = [] > with open(loan_file, "r") as file: > lines = file.readlines() > for line in lines: > line = line.split(",") > loan_list.append(Book(line[0].strip(), line[1].strip())) > return loan_list Note that these two functions are identical. You only need one, into which you pass the required file: def get_list(fileName): theList = [] with open(fileName, "r") as file: lines = file.readlines() for line in lines: line = line.split(",") theList.append(Book(line[0].strip(), line[1].strip())) return theList Then you can call it with loan_list = get_list(loan_file) book_list = get_list(file_name) Another tweak would be not to read the file with readlines but just iterate over the file directly: with open(fileName, "r") as file: for line in file: ... > def loan_book(): > book_title = input("What is the name of the book") It is usually better to place user interaction outside of the processing functions. You culd read the input then pass the value into the function. def loan_book(book_title): ... > info = book_list This tries to assign book_list to info. But book_list is a local variable declared inside main() and loan_book() cannot see it, so you should be getting an error here. Yu would need to make book_list a global variable. > for line in info: line is a terrible choice of name since the list isa list of Books. It should probably be: for book in info: > if line.title == book_title: > loan_list.append(line) Similarly loan_list only exists inside main() so this function cannot see it. You need to make loan_list a global variable. Better still pass them in as parameters: def loan_book(title, books, loans): for book in books: if book.title == title: loans.append(line) > def main(): > loan_list = get_loan_list() > book_list = get_book_list() book_title = input(("What is the name of the book") > loan_book(book_title, book_list, loan_list) Finally, how do you know whether this works or not? You never print any output. I'd suggest adding the following at the end of main(): print("books: ", book_list) print("loans: ", loan_list) To see if the book has in fact transferred. -- 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 From alan.gauld at yahoo.co.uk Wed Nov 27 12:26:17 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 27 Nov 2019 17:26:17 +0000 Subject: [Tutor] function for loaning a book In-Reply-To: <4838207c-60af-f4da-1e60-30d7350be895@yahoo.co.uk> References: <4838207c-60af-f4da-1e60-30d7350be895@yahoo.co.uk> Message-ID: <039efacd-6eac-7509-8c7b-faa632f8edd1@yahoo.co.uk> On 27/11/2019 16:59, Alan Gauld via Tutor wrote: > Similarly loan_list only exists inside main() so this function cannot > see it. You need to make loan_list a global variable. Better still pass > them in as parameters: > > def loan_book(title, books, loans): > for book in books: > if book.title == title: > loans.append(line) Oops, cut n paste error, that last line should be: loans.append(book) Also you could do the whole thing with a list comprehension: def loan_book(title, books, loans): return [book for book in books if book.title == title] -- 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 From PyTutor at DancesWithMice.info Wed Nov 27 23:54:33 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Thu, 28 Nov 2019 17:54:33 +1300 Subject: [Tutor] function for loaning a book In-Reply-To: References: Message-ID: <3fd88c87-3b14-26ef-0f9f-37752613dc72@DancesWithMice.info> On 28/11/19 2:56 AM, samhar zghaier wrote: > Hello > I creatred a function to read each of my text files and read them into the > program, im now trying to delete a certain item from one of the two lists i > created and add it to the other one > currently i am not able to add a certain element to the loan list > This is the code i have currently written Thanks for showing us your code! (a line or two of book-data may have helped, but wasn't strictly necessary) This has the flavor of a homework assignment. Correct? Some of the answers have been quite complex and offer advanced coding techniques. Perhaps we should concentrate on 'the basics' first? When we can't 'see' what's happening 'inside' a Python pgm, the (easy) 'solution' is to add print statements which 'show the working' (as my math teacher used to say). For example: > def loan_book(): > book_title = input("What is the name of the book") print( f"Book name = { book_title }" ) or print( "Book name =", book_title ) # both reveal the same information > info = book_list > for line in info: > if line.title == book_title: > loan_list.append(line) print( f"New loan list: { loan_list }" ) These have removed the guess-work. Either they show that the code is working exactly as you expect - or not! Another way (a better way?) to approach code for the first time is to use the Python REPL. On my machine, I open a terminal (?DOS Box on MS-Win), issue the command "python3" and can then experiment with Python code, eg: [dn at JrBrown ~]$ python3 Python 3.7.4 (default, Jul 9 2019, 16:48:28) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> loan_list = [ 'book1', 'book2' ] >>> print( loan_list ) ['book1', 'book2'] >>> loan_list.append( 'book3' ) >>> print( loan_list ) ['book1', 'book2', 'book3'] >>> Ahah, so that's how to extend a list! NB in the REPL, using print() is optional, typing only "loan_list" would produce the same output. Notice how this snippet 'proves' my understanding of list-manipulation, without all the other detail, eg pulling the book data from a file. 1 broke the larger problem down into smaller problems 2 focussed on a single detail - solve one (of the smaller) problem at a time! Having learned/confirmed the process of extending a (loan_)list, you could now use the REPL to experiment with the next step: how to remove the book's entry from the book_list... Which brings me to ask a design question (cf "coding"): why lists? If the answer is basically: "this is how the assignment tells me to do things", then read no further. When we have 'lists' (the more general, and more pythonic word, is "collections") which we will later have to "search" (an important ComSc word), we need to think about how the collection will be "accessed" (more ComSc). In this case, the individual books (in the collection) are identified by some "key", eg the title, author, or accession number, which the user will input. The code (as is) then searches the list by "sequentially" (more ComSc!) checking/"searching" each entry in the list against the "key". An alternate way to design a solution to this problem, having identified both "collection" and "key", is to use a Python dict (dictionary). Whereas someone using a list may have based his/her decision upon 'what the data looks-like', the dict-approach is thinking about how that data is going to be used! Hopefully you can detect the difference in approach? In this case, each 'entry' in the collection is logically split into two parts: the "key" and the "data" (ComSc talks about "independent" and "dependent" parts, but that is unnecessarily formal), eg python_coder = dict() python_coder[ "Samhar" ] = 1 Here, your name is the key, and the value "1" is 'whatever data you want it to be', eg your position in class. Note that the 'data' part can be any Python data construct, eg a list(): python_coder = dict() python_coder[ "sz" ] = [ 'good-looking', 'intelligent', 'happy' ] python_coder[ "dn" ] = [ 'ugly', 'bottom of the class', 'grumpy' ] Why bother? Because, now instead of searching (potentially the entire) list sequentially, we can use the "key" to go straight ("direct access") to the data: initials = input( "Who you gonna call?" ) print( f"You called { initials } who is { python_coder[ initials ] }" ) Which is (a) faster to write the code, and (b) faster to execute! (and probably more effective than calling "Ghostbusters") That is the essence of data access. Perhaps you were required to use a list. So do that. In which case, perhaps you are now one-step-ahead when it comes to the introduction of dict(ionaries)! As others have observed, there are more advanced concepts we can - or even "should" consider, eg what if the user enters a 'key' that doesn't exist in the list/dict? However, I suspect that such fit into a more advanced course. OTOH I hope this wasn't too simple for you... -- Regards =dn From asad.hasan2004 at gmail.com Fri Nov 29 07:32:37 2019 From: asad.hasan2004 at gmail.com (Asad) Date: Fri, 29 Nov 2019 18:02:37 +0530 Subject: [Tutor] How to Compare rpm version using Python Script Message-ID: Hi All , I am thinking to write a script to compare the rpm version installed in a Linux system with a defined list of the rpm's . It the elements matches or the system has a higher version show success or else show failed . I was planning to use the rpm command : /bin/rpm -q --queryformat '%{name}-%{ARCH}-%{version}-%{release}\n' to get the list of rpm's installed in the system . How to do the comparison for example : Expected Value:compat-libcap1-1.10 INFO: Actual Value:compat-libcap1-1.10-7.el7 This should show success . Please share some knowledge and logic to code this . Thanks, -- Asad Hasan +91 9582111698 From mats at wichmann.us Fri Nov 29 09:20:06 2019 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 29 Nov 2019 07:20:06 -0700 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: Message-ID: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> On 11/29/19 5:32 AM, Asad wrote: > Hi All , > > I am thinking to write a script to compare the rpm version > installed in a Linux system with a defined list of the rpm's . It the > elements matches or the system has a higher version show success or else > show failed . > > I was planning to use the rpm command : > > /bin/rpm -q --queryformat '%{name}-%{ARCH}-%{version}-%{release}\n' > > to get the list of rpm's installed in the system . How to do the comparison > for example : > > Expected Value:compat-libcap1-1.10 > INFO: Actual Value:compat-libcap1-1.10-7.el7 > > This should show success . > > Please share some knowledge and logic to code this . We're going to ask that you think about it a bit and show what you've tried. How might you compare individual entries in two lists that are each coming from external sources - one from running a command, one read from a file (note: I wouldn't advice doing an rpm query individually on each packagename, that will become rather...slow...) Will say that a challenge is going to be to distinguish the package names from the versions when you're reading from a file. For the installed packages this is easy, rpm already knows how to do that, and it's not a Python problem at all - your example above already shows how, you just put a separator between the pieces you want to look like different words, for example '%{name} %{version}'. rpm packages are named in a way that makes it a challenge to figure out where the name ends and the version begins. It's not the first dash, because you have package names like "python3-libs" (and there are packages with more than two levels in the naming). It's not the first digit, with the same name providing an example of that problem. It's not the last dash either, since there's one after the upstream version and before the build number in most pkgs, like 'python3-libs-3.7.5-1.fc30.x86_64'. Can you see a pattern? Is there a Python function you could use to help with this? From akleider at sonic.net Fri Nov 29 12:06:18 2019 From: akleider at sonic.net (Alex Kleider) Date: Fri, 29 Nov 2019 09:06:18 -0800 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: Message-ID: <2cb0fa5947650756e3513dcf7063d3de@sonic.net> On 2019-11-29 04:32, Asad wrote: > Hi All , > > I am thinking to write a script to compare the rpm version > installed in a Linux system with a defined list of the rpm's . It the > elements matches or the system has a higher version show success or > else > show failed . > > I was planning to use the rpm command : > > /bin/rpm -q --queryformat '%{name}-%{ARCH}-%{version}-%{release}\n' > > to get the list of rpm's installed in the system . How to do the > comparison > for example : > > Expected Value:compat-libcap1-1.10 > INFO: Actual Value:compat-libcap1-1.10-7.el7 > > This should show success . > > Please share some knowledge and logic to code this . > > Thanks, The following _might_ help you get started: >>> "hello" in "hello world" True >>> From david at graniteweb.com Fri Nov 29 19:16:32 2019 From: david at graniteweb.com (David Rock) Date: Fri, 29 Nov 2019 18:16:32 -0600 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> Message-ID: <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> * Mats Wichmann [2019-11-29 07:20]: > > Will say that a challenge is going to be to distinguish the package names > from the versions when you're reading from a file. For the installed > packages this is easy, rpm already knows how to do that, and it's not a > Python problem at all - your example above already shows how, you just put a > separator between the pieces you want to look like different words, for > example '%{name} %{version}'. To reinforce this idea... do NOT use hyphens in your rpm -q command; use spaces instead. It will make it a LOT easier to separate the name from the version (many names contain hyphens) to compare against the lists. -- David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Fri Nov 29 20:00:25 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Nov 2019 01:00:25 +0000 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> Message-ID: On 30/11/2019 00:16, David Rock wrote: > To reinforce this idea... do NOT use hyphens in your rpm -q command; use > spaces instead. It will make it a LOT easier to separate the name from the > version (many names contain hyphens) to compare against the lists. In a me-too kind of way... I used to work beside a data processing team who spent their lives creating reports from old COBOL based systems. They used to write their processed (ie pre-report) data extracts into CSV format files but instead of commas they used the cedilla character(?), as it was hardly ever found in real world data (at least not in our area, maybe in Romance based language areas that might not hold good). But the point was to use a character that you will not actually find in the text as a separator. -- 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 From bouncingcats at gmail.com Fri Nov 29 21:07:31 2019 From: bouncingcats at gmail.com (David) Date: Sat, 30 Nov 2019 13:07:31 +1100 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> Message-ID: On Sat, 30 Nov 2019 at 12:01, Alan Gauld via Tutor wrote: > I used to work beside a data processing team who spent their lives > creating reports from old COBOL based systems. They used to write > their processed (ie pre-report) data extracts into CSV format files > but instead of commas they used the cedilla character(?), as it > was hardly ever found in real world data (at least not in our area, > maybe in Romance based language areas that might not hold good). > But the point was to use a character that you will not actually > find in the text as a separator. Years ago I noticed that ASCII contains several control characters that are specifically intended as data separators: https://en.wikipedia.org/wiki/Control_character#Data_structuring I sometimes use them in my shell scripting where appropriate, due to the limited data structures available there, but I've never seen them used or advocated anywhere else. Are there reasons why they are not used more widely by programmers to solve simple textual data separation problems? I assume that they would still work with utf8, although I've not tested that. From david at graniteweb.com Fri Nov 29 21:27:28 2019 From: david at graniteweb.com (David Rock) Date: Fri, 29 Nov 2019 20:27:28 -0600 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> Message-ID: <20191130022728.4lvezo37nuimcmca@apple.graniteweb.com> * David [2019-11-30 13:07]: > On Sat, 30 Nov 2019 at 12:01, Alan Gauld via Tutor wrote: > > I sometimes use them in my shell scripting where appropriate, due to > the limited data structures available there, but I've never seen them used > or advocated anywhere else. > > Are there reasons why they are not used more widely by programmers > to solve simple textual data separation problems? Two obvious reasons come to mind: 1. People are generally not aware of them 2. They are often overkill when something simpler will work In the case of our RPM example, using a simple space will get the job done. While using the unit separator would work, it's a lot more complicated to use it in practice, and unnecessary. Typing multiple ^V^_ characters to build the format string is a lot more painful than just hitting the spacebar. That's not to say these characters don't have value. The RPM case is an overly-simplistic example where using them is unnecessary, but there are definitely plenty of cases where finding a character that isn't in your data is a lot harder. -- David Rock david at graniteweb.com From Richard at Damon-Family.org Fri Nov 29 22:20:01 2019 From: Richard at Damon-Family.org (Richard Damon) Date: Fri, 29 Nov 2019 22:20:01 -0500 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> Message-ID: <5bf44bb0-6dd5-4717-bf6f-853ded148542@Damon-Family.org> On 11/29/19 9:07 PM, David wrote: > On Sat, 30 Nov 2019 at 12:01, Alan Gauld via Tutor wrote: > >> I used to work beside a data processing team who spent their lives >> creating reports from old COBOL based systems. They used to write >> their processed (ie pre-report) data extracts into CSV format files >> but instead of commas they used the cedilla character(?), as it >> was hardly ever found in real world data (at least not in our area, >> maybe in Romance based language areas that might not hold good). >> But the point was to use a character that you will not actually >> find in the text as a separator. > Years ago I noticed that ASCII contains several control characters that > are specifically intended as data separators: > https://en.wikipedia.org/wiki/Control_character#Data_structuring > > I sometimes use them in my shell scripting where appropriate, due to > the limited data structures available there, but I've never seen them used > or advocated anywhere else. > > Are there reasons why they are not used more widely by programmers > to solve simple textual data separation problems? > > I assume that they would still work with utf8, although I've not tested > that. I would say that one big reason is they have no visible representation. Generally their intended use was in transmission or 'binary' formats, with an access program that processed them for visual display. -- Richard Damon From PyTutor at DancesWithMice.info Sat Nov 30 02:59:37 2019 From: PyTutor at DancesWithMice.info (David L Neil) Date: Sat, 30 Nov 2019 20:59:37 +1300 Subject: [Tutor] How to Compare rpm version using Python Script In-Reply-To: References: <1c8702ee-e30a-fd40-c0e3-2b87c34dfb40@wichmann.us> <20191130001632.zltebp32xhrr4zl5@apple.graniteweb.com> Message-ID: <2a0d939f-9622-291d-5e74-87511ea70ca7@DancesWithMice.info> On 30/11/19 3:07 PM, David wrote: > On Sat, 30 Nov 2019 at 12:01, Alan Gauld via Tutor wrote: > >> I used to work beside a data processing team who spent their lives >> creating reports from old COBOL based systems. They used to write >> their processed (ie pre-report) data extracts into CSV format files >> but instead of commas they used the cedilla character(?), as it >> was hardly ever found in real world data (at least not in our area, >> maybe in Romance based language areas that might not hold good). >> But the point was to use a character that you will not actually >> find in the text as a separator. > > Years ago I noticed that ASCII contains several control characters that > are specifically intended as data separators: > https://en.wikipedia.org/wiki/Control_character#Data_structuring > > I sometimes use them in my shell scripting where appropriate, due to > the limited data structures available there, but I've never seen them used > or advocated anywhere else. > > Are there reasons why they are not used more widely by programmers > to solve simple textual data separation problems? > > I assume that they would still work with utf8, although I've not tested > that. Many of the "control characters" had specific purposes, perhaps in certain situations or in relation to particular devices, eg xOA is still used as printer/screen/etc LineFeed to this day. So, need to be careful in case the output is ever printed (for example). In ASCII there were official "separator" characters (x1C-1F), to which users could assign their own particular meaning, even though they were assigned names, eg "Record Separator". These (latter) have carried-through to UTF-8, eg "INFORMATION SEPARATOR ONE" through "...FOUR", and seem quite appropriate to the OP's application. -- Regards =dn From alan.gauld at yahoo.co.uk Sat Nov 30 07:50:53 2019 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Nov 2019 12:50:53 +0000 Subject: [Tutor] Handy cheat sheet References: <65fc89c5-6445-9dec-7f48-26a04b39a962.ref@yahoo.co.uk> Message-ID: <65fc89c5-6445-9dec-7f48-26a04b39a962@yahoo.co.uk> A reader of my tutorial recently sent me this link: https://www.comparitech.com/net-admin/python-network-programming-cheat-sheet/ It is a one page cheat sheet available on-line or as PDF. It looks useful, although network focused, so I thought I'd share. -- 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