sqlite & python 2.5
Hi, I am using python 2.5 under windows. I am trying to do the below: cursor.execute("SELECT postid, title, body, teaser, postdate, posttime, author, status, format, allow_comments, notify_on_comments, catname \ FROM ton_posts p, ton_category c \ where c.catid = p.category and status = 1 and strftime('%Y', p.postdate) in(?) and strftime('%m', p.postdate) in(?) and c.catid in(?)\ order by postdate desc, posttime desc",sqlvars) print cursor.fetchall() But it always returns empty (though there is value in db). For ref: sqlvars = ("select distinct strftime('%Y',postdate) from ton_posts", "select distinct strftime('%m',postdate) from ton_posts", 'select catid from ton_category') Is there anyway I can find out the sql that gets executed (after the varible substitution)? Also can anyone help me out in finding out what is wrong here? Thanks a lot Joseph -- http://mail.python.org/mailman/listinfo/python-list
Import Error
Hi, I am using Karrigell & Sprite for web development. Sprite is placed in the main folder of my app. I got a sub-folder called admin. I am using the below line to import Sprite from the subfolder. from ..sprite import Sprite Most of the time it works. However time to time, it will throw an error that there is no module called Sprite. I delete the .pyc file, call a page in the main folder, then it will work. Any help how I can resolve it? Thank you in advance, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Import Error
Hi, I am using Karrigell & Sprite for web development. Sprite is placed in the main folder of my app. I got a sub-folder called admin. I am using the below line to import Sprite from the subfolder. from ..sprite import Sprite Most of the time it works. However time to time, it will throw an error that there is no module called Sprite. I delete the .pyc file, call a page in the main folder, then it will work. Any help how I can resolve it? Thank you in advance, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Import Error
Hi, I am using Karrigell & Sprite for webdevelopment. Sprite is placed in the main folder of my app. I got a sub-folder called admin. I am using the below line to import Sprite within the subfolder. from ..sprite import Sprite Most of the time it works. However time to time, it will throw an error that there is no module called Sprite. I delete the .pyc file, call a page in the main folder, then it will work. Any help how I can resolve it? Thanks in advance, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Web queries in Python
Hi, Excel uses web queries to read data (like financial/weather data) from web. How to do the same in python? Even pointers to such would be of help. Thank you, Joseph -- http://mail.python.org/mailman/listinfo/python-list
real time info to web browser from apache side ?
I know about writing CGI application using Perl and Apache to refresh a static webpage that displays on the browser. But now i have an application requirement that I hope someone can help me. The server side sits in another room down the factory plant, its monitoring some hardware environment, namely temperatures and pressures etc inside the plant. This server of course have Apache running. I would like to be able to have a browser in the comfortable office somewhere point to the apache server, and after I enter the password, it would display the temperature and pressures etc in the plant (in real time, ie. as the temperate changes from a degree to another, the browser will immediately display this). So I am looking more for a push technology than a pull from teh browser (user hit Ctrl-R to refresh is a pull). What are the current technology that allows for this. I know its possible because I can use my browser sometimes to chat with people online, and I swear that I don't have to do a Control-R everytime to see that the other person's typing is updating constantly on my browser. Thanks in advance, Push technology wannabe -- http://mail.python.org/mailman/listinfo/python-list
adding python libraries (for shared hosting)
Hi all, My shared host provides python 2.3. Since it is a shared hosting, he is not willing to upgrade to a newer version. I am looking for option to upload 2.5 on my own. Is this possible and if so, can anyone please provide a pointer to how this can be achieved? Thank you, Joseph http://www.jjude.com | http://twitter.com/jjude -- http://mail.python.org/mailman/listinfo/python-list
ISBN Barecode reader in Python?
All: I have written a program to query Amazon with ISBN and get the book details. I would like to extend so that I can read ISBN from the barcode (I will take a photo of the same using webcam or mobile). Are there any opensource/free SDK doing the same? As it is a hobby project, I don't like to spend money on the SDK. Thank you all for your suggestions/time, Joseph http://www.jjude.com -- http://mail.python.org/mailman/listinfo/python-list
formatted output
Dear members, I need to print few arrays in a tabular form for example below array IL has 25 elements, is there an easy way to print this as 5x5 comma separated table? in python IL=[] for i in np.arange(1,bno+1): IL.append(i) print(IL) % in fortran I could do it as below % integer matrix(5,5) in=0 do, k=1,5 do, l=1,5 in=in+1 matrix(k,l)=in enddo enddo m=5 n=5 do, i=1,m write(*,"(5i5)") ( matrix(i,j), j=1,n ) enddo end -- http://mail.python.org/mailman/listinfo/python-list
netcdF4 variables
Dear members, I have been using python NetcdF for some time. I understand that we can get variables from a netcdf one by one by using temp=ncf.variable['temp'][:] but is there a way to get a list of variables with out the rest of the stuff as seen below? some hing like a list xx=nc,variables[:] should get me all variable names with out other surrounding stuff?? with best regards. Sudheer In [4]: ncf.variables Out[4]: OrderedDict([(u'LON', ), (u'LAT', ), (u'DEPTH1_1', ), (u'TAX', ), (u'DIF_FD1', ), (u'DIF_FD2', ), (u'DIF_FD3', ), (u'DIF_FD4', ), (u'DIF_FD5', ), (u'DEPTH', ), (u'DEPTH_bnds', ), (u'TIME', ), (u'TEMP_BIAS', )]) -- http://mail.python.org/mailman/listinfo/python-list
Re: netcdF4 variables
Thank you very much it works for me. with best regards, Sudheer On Saturday, June 1, 2013 12:51:01 PM UTC+5:30, Andreas Perstinger wrote: > On 01.06.2013 05:30, Sudheer Joseph wrote: > > > some hing like a list > > > xx=nc,variables[:] > > > should get me all variable names with out other surrounding stuff?? > > > > > > In [4]: ncf.variables > > > Out[4]: OrderedDict([(u'LON', ), > > [SNIP] > > > > It looks like "variables" is an OrderedDict. Thus > > > > >>> ncf.variables.keys() > > > > should return a view (or list, depending on your python version) of all > > keys, i.e. all variable names. > > > > Bye, Andreas -- http://mail.python.org/mailman/listinfo/python-list
python netcdf
Dear Members, Is there a way to get the time:origin attribute from a netcdf file as string using the Python netcdf? with best regards, Sudheer -- http://mail.python.org/mailman/listinfo/python-list
Re: python netcdf
Thank you very much Jason With best regards Sudheer On Thursday, June 6, 2013, Jason Swails wrote: > > > > On Wed, Jun 5, 2013 at 9:07 PM, Sudheer Joseph > > > wrote: > >> Dear Members, >> Is there a way to get the time:origin attribute from a >> netcdf file as string using the Python netcdf? >> > > Attributes of the NetCDF file and attributes of each of the variables can > be accessed via the dot-operator, as per standard Python. > > For instance, suppose that your NetCDF file has a Conventions attribute, > you can access it via: > > ncfile.Conventions > > Suppose that your variable, time, has an attribute "origin", you can get > it via: > > ncfile.variables['time'].origin > > Of course there's the question of what NetCDF bindings you're going to > use. The options that I'm familiar with are the ScientificPython's > NetCDFFile class (Scientific.IO.NetCDF.NetCDFFile), pynetcdf (which is just > the ScientificPython's class in a standalone format), and the netCDF4 > package. Each option has a similar API with attributes accessed the same > way. > > An example with netCDF4 (which is newer, has NetCDF 4 capabilities, and > appears to be more supported): > > from netCDF4 import Dataset > > ncfile = Dataset('my_netcdf_file.nc', 'r') > > origin = ncfile.variables['time'].origin > > etc. etc. > > The variables and dimensions of a NetCDF file are stored in dictionaries, > and the data from variables are accessible via slicing: > > time_data = ncfile.variables['time'][:] > > The slice returns a numpy ndarray. > > HTH, > Jason > -- Sent from my iPad Mini -- http://mail.python.org/mailman/listinfo/python-list
RE: Homework help requested (not what you think!)
Not to open Pandora's box or anything, but are you aware of the Roguelike community (subculture?) (cult?) of game development? Rogue was an old "text-based" role playing game for Unix, "text-based" in the sense that it used the console as a 2D map and ASCII characters as graphics. There has been a sort of revival of the genre and a lot of amateur game developers have done some simple or complex variations on the theme. They're not all RPGs. The category is defined by a few commonalities like procedural content generation. There are very active forums and an extensive wiki. I think these might be particularly appropriate fodder for a tutoring experience because they are neatly broken down into bite-sized chunks. One day you could do procedural map generation, another day AI, etc. And all these lessons generalize to the "professional" game development world. Look at this forum: http://forums.roguetemple.com/index.php?board=7.0 This wiki: http://roguebasin.roguelikedevelopment.org/index.php?title=Main_Page This Python tutorial: http://roguebasin.roguelikedevelopment.org/index.php?title=Complete_Roguelike_Tutorial,_using_python%2Blibtcod By the way, I tried my hand at Markov chain name generation, too. My python code is at https://github.com/joeclark77net/jc77rogue/blob/master/program/namegen.py and what it does is read a corpus of names and generate new names that sound like that corpus. So you feed it a list of Roman names and it will give you fake names that sound Roman. // joseph w. clark , phd , visiting research associate \\ university of nebraska at omaha - college of IS&T > Date: Tue, 16 Jul 2013 15:43:45 -0700 > Subject: Homework help requested (not what you think!) > From: john_lada...@sbcglobal.net > To: python-list@python.org > > Hi folks, > > No, I'm not asking for YOU to help ME with a Python homework assignment! > > Previously, I mentioned that I was starting to teach my son Python. > > https://groups.google.com/d/msg/comp.lang.python/I7spp6iC3tw/8lxUXfrL-9gJ > > He just took a course at his high school called Web Technology and Design. > They had the students use tools like Dream Weaver, but they also hand-coded > some HTML and JavaScript. He has a little experience. I am building on it. > > Well, a few other parents caught wind of what I was doing with my son, and > they asked me whether I could tutor their kids, too. I accepted the jobs (for > pay, actually). > > The kids all claim to be interested. They all want to write the next great 3D > video game. Thus, I'm a little surprised that the kids don't actually try to > sit down and code without me prompting them. I think that they're > disappointed when I show them how much they have to understand just to write > a program that plays Tic Tac Toe. > > Where programming is concerned, I'm an autodidact. I started programming when > I was twelve, with little more guidance than the Applesoft Basic manual and > the occasional issue of Byte Magazine. I hacked away. Over the years, I have > acquired a working knowledge of BASIC, 6502 assembly language, Pascal, C, and > finally Python (my favorite). If I knew how to impart a love of > experimentation to my students, I would do that. > > One kid looks like he's ready to forge ahead. In the mean time, one parent > has recognized his son's lack of independence, and has asked me to assign > programming homework. I hope it doesn't kill the kid's enthusiasm, but I'm > willing to try it. > > So, what I am seeking are suggestions for programming assignments that I can > give to brand-new students of Python. Please keep in mind that none of them > are even up to the task of a simple algorithm like Bubble Sort -- at least, > not yet. > > Many thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
RE: Homework help requested, thanks to everyone.
John, have you taken a look at pyglet? It's an alternative to pygame and I found it pretty slick once I got the hang of it. There is a development version that's compatible with python 3 and I've never had a bug with it. It wraps OpenGL itself so there are no additional dependencies. // joseph w. clark , phd , visiting research associate \\ university of nebraska at omaha - college of IS&T > Date: Sun, 21 Jul 2013 13:49:40 -0700 > Subject: Homework help requested, thanks to everyone. > From: john_lada...@sbcglobal.net > To: python-list@python.org > > Thanks to everyone for their wealth of suggestions. I already had my > students playing with turtle. And I had asked them to alphabetize a string > (without having previously revealed the sorted() function). > > So far, I have taken up the suggestion of the number-guessing game. One of > my students has a working version. The logic is a bit clumsy, but it's a > fine first attempt. > > I will also take up the Twenty Questions idea. My son and I played that game > a lot over the years, to pass the time on long car rides. And it would be a > great way to introduce the binary tree data structure. > > Another project I thought of was a Pig Latin translator. (But do kids today > even know what Pig Latin is? Am I showing my age?) > > Concerning more advanced, real-time, game-oriented graphics, I am trying to > figure out how to build PyGame on top of Python3.x. Supposedly it is > possible. I just haven't figured out how. It's 2013: I refuse to complicate > my students' programming education with Python 2.x. > > I used wxPython happily for years, and I think that its graphical > capabilities would probably be up to the task of a simple 2D game. > Unfortunately, it has the same problem as PyGame, at least for now. The > Py3-compatible version of wxPython, to be known as Phoenix, is still under > development. > > I'll keep Unity, Panda3D, and Blender in mind for later. Again, one of my > main concerns will be Python 3.x compatibility. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
PEP 20 - Silly Question?
I have used Python for some time and ran a windows build-bot for a bit. This morning, I told a fellow developer "There should be only one obvious way to do it." and then I proceeded to forward him to the Zen of Python and sent him a link to: http://www.python.org/dev/peps/pep-0020/ I noticed that it says only 19 of 20 have been written down. Which one was not written down? Thank You, Joseph Armbruster -- http://mail.python.org/mailman/listinfo/python-list
Learn Python the Hardway exercise 11 question 4
print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) Note: Notice that we put a , (comma) at the end of each print line. This is so that print doesn’t end the line with a newline and go to the next line. What You Should See Extra Credit 1. Go online and find out what Python’s raw_input does. $ python ex11.py How old are you? 35 How tall are you? 6'2" How much do you weigh? 180lbs So, you're '35' old, '6\'2"' tall and '180lbs' heavy. Related to escape sequences, try to find out why the last line has ’6\’2"’ with that \’ sequence. See how the single-quote needs to be escaped because otherwise it would end the string? -- http://mail.python.org/mailman/listinfo/python-list
Amazon Simple Queue Service Worker
Hi all, Little new to the python world, please excuse the Noobness. We are writing a server which will subscribe to the Amazon Simple Queue Service. I am looking for a good service container. I saw Twisted and Zope out there. It's going to be a server which polls on a queue via the Boto api. Do you have any suggestions for a framework to start? Best Regards, Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: Amazon Simple Queue Service Worker
Thanks! On 7 April 2011 10:13, Joseph Ziegler wrote: > Hi all, > > Little new to the python world, please excuse the Noobness. > > We are writing a server which will subscribe to the Amazon Simple Queue > Service. I am looking for a good service container. I saw Twisted and Zope > out there. It's going to be a server which polls on a queue via the Boto > api. Do you have any suggestions for a framework to start? > > Best Regards, > > Joe > -- http://mail.python.org/mailman/listinfo/python-list
RE: lambda issues
Re: "...which takes a callable (the lambda here)" Python lamdas have some severe restrictions. In any place that takes a callable, if a lambda can't serve, just use def to write a function and use the function name. Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Python-list On Behalf Of python-list-requ...@python.org Sent: Wednesday, April 20, 2022 12:00 PM To: python-list@python.org Subject: Python-list Digest, Vol 223, Issue 20 ---External Email--- Send Python-list mailing list submissions to python-list@python.org To subscribe or unsubscribe via the World Wide Web, visit https://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-requ...@python.org You can reach the person managing the list at python-list-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." -- https://mail.python.org/mailman/listinfo/python-list
RE: Python/New/Learn
Buy the book "Python 101" and do the examples. When you're done with that buy the book "Python 201" and study it. There is much more than is in both those books that you could learn about Python, but that's a very good way to start. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Patrick 0511 Sent: Wednesday, May 4, 2022 9:36 PM To: python-list@python.org Subject: Python/New/Learn Hello, I'm completely new here and don't know anything about python. Can someone tell me how best to start? So what things should I learn first? -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem when scraping the 100 Movie titles.
#Try using, it's save in json format of the website: import json import requests from bs4 import BeautifulSoup url = "https://www.empireonline.com/movies/features/best-movies-2/"; soup = BeautifulSoup(requests.get(url).content, "html.parser") data = json.loads(soup.select_one("#__NEXT_DATA__").contents[0]) # uncomment this to print all data: #print(json.dumps(data, indent=4)) def find_articles(data): if isinstance(data, dict): for k, v in data.items(): if k.startswith("ImageMeta:"): yield v['image']['name'] else: yield from find_articles(v) elif isinstance(data, list): for i in data: yield from find_articles(i) for a in find_articles(data): print(a) -- https://mail.python.org/mailman/listinfo/python-list
Re: How do you debug in Python? Coming from a Matlab and R user. I'm already aware of pdb.
To debug python code I use spyder from the anaconda distribution Am Mittwoch, 27. Januar 2021 schrieb C W : > Hi Michael, > Here's the code again, class should be called PERSONDatabase, misspelled > earlier: > class PERSONDatabase: >def __init__(self, id, created_at, name, attend_date, distance): > self._id = id > self.created_at = created_at > self.name= name > self.attend_date = attend_date > self.distance = distance > >@classmethod >def get_person(self, employee): > return PERSONDatabase(employee['created_at'], > employee['id'], > employee['name'], > employee['attend_date'], > employee['distance']) > > The PERSONDatabase class is called from main. This is the trace back I got > from the VS code: > > Traceback (most recent call last): >File "/Users/Mike/Documents/Mike/main.py", line 95, in > main() >File "/Users/Mike/Documents/Mike/main.py", line 86, in main > args = get_feed() >File "/Users/Mike/DocumentsMike/main.py", line 32, in get_feed > result = [PERSONatabase.get_person(raw_person) for raw_neo in > raw_objects] >File "/Users/Mike/Documents/Mike/main.py", line 32, in > result = [NEODatabase.get_person(raw_person) for raw_neo in > raw_objects] >File "/Users/Mike/Documents/Mike/database.py", line 24, in get_person > return PERSONDatabase(person['created_at'], > KeyError: 'created_at' > > Thank you very much! > > On Wed, Jan 27, 2021 at 12:10 AM Michael Torrie wrote: > > > On 1/26/21 8:37 PM, C W wrote: > > > I have a naive question. How do I use traceback or trace the stack? In > > > particular, I'm using VS Code with Python interactive console. > > > > Show us the traceback here and we can help you interpret it. Copy and > > paste it from the VS Code console. > > > > > Say, I want to print the value of employee['name']. Can I do it? > > > > Yes I would think so. > > > > > My understanding is that these classes are just "skeletons". I must > > > create an instance, assign values, then test? > > > > Can't you just do something like this? > > > > class NEODatabase: > > def __init__(self, id, created_at, name, attend_date, distance): > > self._id = id > > self.created_at = created_at > > self.name = name > > self.attend_date = attend_date > > self.distance = distance > > > > @classmethod > > def get_person(self, employee): > > print (employee['name']) > > > > return PERSONDatabase(employee['created_at'], > > employee['id'], > > employee['name'], > > employee['attend_date'], > > employee['distance']) > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
RE: IDE tools to debug in Python?
Indeed there are many. One I have not seen listed here yet, that is quite light, starts quickly, but does have good debugging capability is PyScripter. Completely free, downloadable from SourceForge, 32 or 64 bit versions (must match your Python type). --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Alan Gauld Sent: Friday, February 5, 2021 3:34 AM To: python-list@python.org Subject: Re: IDE tools to debug in Python? On 27/01/2021 18:32, flaskee via Python-list wrote: > > While print() is groovy and all, > if anyone runs across a non-pdb python debugger (standalone or > IDE-based) please let me know. > There are many. But why must it be non-pdb? That seems rather arbitrary. Or do you really mean you want a non-command-line debugger? One standalone option is winpdb But most Python IDEs have basic debugging tools built in. -- 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 -- https://mail.python.org/mailman/listinfo/python-list
RE: Python cannot count apparently
This code works: mystr = "hello" for ch in mystr: print(ch, end="") result is: hello Note that the for loop does not use range. Strings are iterable, that is they support Python's iteration protocol. So, for ch in mystr: assigns one character from mystr to ch each time, each iteration gets the next character. To prevent each character from appearing on a separate line (in Python 3) you need end="". That is, don't put in the usual end-of-line ending. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Michael F. Stemper Sent: Monday, February 8, 2021 9:19 AM To: python-list@python.org Subject: Re: Python cannot count apparently On 07/02/2021 13.34, Philipp Daher wrote: > Hello, > > I recently coded this snippet of code: > myString=„hello“ > for i in range(len(myString): > print(string[i]) > > And now for the weird part: > > SOMETIMES, the output is this: > > hello Strange. When I fix the errors in what you posted: - wrong character to start the string - wrong variable name in the call to print() I get[1]: ... myString="hello" ... for i in range(len(myString)): ... print( myString[i] ) ... h e l l o ... You must have done something to suppress the newlines after each call to print(). So it's quite obvious that the code you posted has very little to do with the code you ran. If you really want us to help, please directly copy and paste the exact code that you ran. We can't really help you with only guesses as to what you did. [1] (leading > replaced with . to fool news clients) -- Michael F. Stemper Galatians 3:28 -- https://mail.python.org/mailman/listinfo/python-list
RE: .title() - annoying mistake
I agree. If the documentation notes this issue, and the (possibly new) Python user has to replace the .title() with a different function that uses regular expression and a lambda function to work around the issue, then perhaps it's time for a proposal to address this. Perhaps there needs to be an optional argument to .title() which if supplied should tell it do the workaround. Or, perhaps better, only capitalize the first word and subsequent words that are preceded by a white space. That should solve "Someone's Apostrophe" and "Hyphenated-expressions". Someone who looks into this should check if the second part of a hyphenated expression needs to be capitalized. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Abdur-Rahmaan Janhangeer Sent: Friday, March 19, 2021 11:02 AM To: Paul Bryan Cc: Python Subject: Re: .title() - annoying mistake Thanks very much! That's annoying. You have to roll your own solution! Kind Regards, Abdur-Rahmaan Janhangeer about <https://compileralchemy.github.io/> | blog <https://www.pythonkitchen.com> github <https://github.com/Abdur-RahmaanJ> Mauritius > -- https://mail.python.org/mailman/listinfo/python-list
HELP Please, Python Program Help
Hi, Im looking for some help with my program, I have been set a task to make a Strain Calculator. I need it to input two numbers, choosing either Metres or Inches for the 'Change in Length' divided by the 'Original Length' which can also be in Metres or Inches, the out put number also needs to give an option for the answer to be in metres or inches. this is what i have come up with so far... txt = "Strain Calculator" x = txt.title() print(x) # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Strain") while True: # Take input from the user choice = input("Enter choice(1): ") # Check if choice is one of the five options if choice in ('1'): num1 = float(input("Change in Length: ")) num2 = float(input("Original Length: ")) if choice == '1': print(num1, "/", num2, "=", divide(num1, num2)) break else: print("Invalid Input") -- https://mail.python.org/mailman/listinfo/python-list
RE: neoPython : Fastest Python Implementation: Coming Soon
"Slow" is in the eye of the beholder and depends on the job the needs to be done. Where I work, we write scripts in Python that control our measuring instruments, make them acquire data and compute results, the Python script reads the results, compares results to limits, and eventually produces a lovely report. In some scripts, we make the instrument acquire and save data and our Python script launches another program on the instrument that will read in the data and perform specified analysis. That program can take a couple of minutes to complete. If we have to do this for multiple runs we launch them at the same time and they finish at the same time, the time of one run. So we are doing easy multiprocessing using Python. Now let's consider, if our controlling Python script were instead written in a highly optimized blazingly fast compiled language, how much faster could this script be? It would still have to wait for the instrument to compute results; if running a separate analysis program it would still have to launch it (perhaps several of them) and wait for until they finished. I doubt the compiled script would finish even a second faster. I think this kind of application is just perfect for Python. We considered other (commercially supported) languages before we went with Python. I'm very happy that we did. We can find people who want to program in Python and already know Python. I haven't yet seen an employee complaint about our scripts being written in Python, and I don't expect to. -- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -- https://mail.python.org/mailman/listinfo/python-list
RE: learning python ...
OMG that is awful abuse of Python! You have overloaded two Python keywords by making variables of that name. As a result, float is no longer a type name, it is a variable name that refers to the value 6.67 ! Type(int) is int; type(float) is float, but isinstance(int,float) doesn't work because float is not a type in your script because you assigned float=6.67 and the local variable dictionary is searched first! To fix this, make your variable name myfloat. Change it wherever the variable name is wanted. In particular, the last line should be print(isinstance(myfloat, float)). The first argument is the variable, the second should be type name. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: hw Sent: Sunday, May 23, 2021 3:34 PM To: python-list@python.org Subject: Re: learning python ... On 5/23/21 7:28 PM, Peter Otten wrote: > On 23/05/2021 06:37, hw wrote: >> >> Hi, >> >> I'm starting to learn python and have made a little example program >> following a tutorial[1] I'm attaching. >> >> Running it, I'm getting: >> >> >> Traceback (most recent call last): >> File "[...]/hworld.py", line 18, in >> print(isinstance(int, float)) >> TypeError: isinstance() arg 2 must be a type or tuple of types >> >> >> I would understand to get an error message in line 5 but not in 18. >> Is this a bug or a feature? > > It is a bug in your code (which you don't provide). Did you assign > some value to float, e. g.: > > >>> float = 42.0 > >>> isinstance(int, float) > Traceback (most recent call last): > File "", line 1, in > isinstance(int, float) > TypeError: isinstance() arg 2 must be a type or tuple of types > > If you do not shadow the built-in you should get > > >>> isinstance(int, float) > False > Apparently the attachment was stripped from my message. I'll put a smaller version directly into this message instead of an attachment: #!/usr/bin/python print("world!") int = 17 print("world", int) float = 6.670 print("world", float) foo = 0 print(type(int)) print(type(float)) print(type(foo)) print(isinstance(foo, str)) print(isinstance(int, float)) print(isinstance(float, float)) I don't know about shadowing. If I have defeated a whole variable type by naming a variable like a variable type, I would think it is a bad idea for python to allow this without warning. It seems like a recipie for creating chaos. -- https://mail.python.org/mailman/listinfo/python-list
Re: Posting code on stackoverflow
you need to put the code between 2 lines defined as follows: ``` then it will be formatted for you Am Sa., 5. Juni 2021 um 23:40 Uhr schrieb Rich Shepard < rshep...@appl-ecosys.com>: > I tried to post a question on stackoverflow.com which included a bunch of > code (entered after clicking the box 'code'). I noticed that lines were > wrapped but could not find how to expand the input box so they would not > wrap. > > SO wouldn't let me post the question because of the wrapped code. As I've > not asked a question ther for a long time, and it didn't involve long lines > of code, I need to learn a) how to enter code if it's not just clicking on > the 'code' box before pasting text and b) how to keep code lines from > wrapping so a horizontal scroll bar is made available. > > TIA, > > Rich > -- > https://mail.python.org/mailman/listinfo/python-list > -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
Is there a conference in the US that is similar to EuroPython?
I am not going to fly to Europe for a Python conference. But, would consider going if in the U.S.A. Especially if drivable ... NYC area would be ideal. I ask because I have seen ads for EuroPython over several years, and I don't remember seeing similar ads for something similar in the U.S.A. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -- https://mail.python.org/mailman/listinfo/python-list
[Errno 2] No such file or directory:
The following code fails as shown in the title: *import subprocesscmd = 'ls -l /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48 | awk "{print $9 }"'process = subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr = process.communicate()print('stdout ',stdout)print('stderr ',stderr)* Traceback (most recent call last): File "PreProcess_1a.py", line 3, in process = subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'ls -l /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48 | awk "{print $9 -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
Re: [Errno 2] No such file or directory:
indeed. There are better options than the one I attempted. Thanks for the advice Am Mi., 28. Juli 2021 um 18:19 Uhr schrieb Chris Angelico : > On Thu, Jul 29, 2021 at 2:10 AM joseph pareti > wrote: > > > > The following code fails as shown in the title: > > > > > > > > > > > > > > *import subprocesscmd = 'ls -l > > > /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48 > > | awk "{print $9 }"'process = subprocess.Popen([cmd], > > stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr = > > process.communicate()print('stdout ',stdout)print('stderr ',stderr)* > > > > > > > > Traceback (most recent call last): > > File "PreProcess_1a.py", line 3, in > > process = subprocess.Popen([cmd], stdout=subprocess.PIPE, > > stderr=subprocess.PIPE) > > File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line > 854, > > in __init__ > > self._execute_child(args, executable, preexec_fn, close_fds, > > File "/home/joepareti54/anaconda3/lib/python3.8/subprocess.py", line > > 1702, in _execute_child > > raise child_exception_type(errno_num, err_msg, err_filename) > > FileNotFoundError: [Errno 2] No such file or directory: 'ls -l > > > /media/joepareti54/Elements/x/finance-2020/AI/Listen_attend_spell/VCTK-Corpus/wav48 > > | awk "{print $9 > > > > First off, you'll want to post code in a way that keeps the > formatting, otherwise it becomes very hard to read. > > But the immediate problem here is that Popen takes an array of command > arguments, NOT a shell command line. You cannot invoke ls and pipe it > into awk this way. > > Don't think like a shell script. Python has very good > directory-listing functionality, and you will very very seldom need to > shell out to pipelines. Figure out what you actually need to learn > from the directory listing and get that information directly, rather > than trying to use two external commands and text parsing. It's far > FAR easier, cleaner, and safer that way. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
RE: Defining a Python enum in a C extension - am I doing this right?
Instead of struggling to define an enum in C that can be read in Python - I'm assuming you can pass strings back and forth - why not just print whatever you need to give to Python into a string (or maybe 2 strings) and send it to Python as string? Python is a dynamic language, it can quickly build an enum type from one string and instantiate enums of that type from the other string. In short, if you have problems creating an enum in C and passing it to Python, give the problems to Python! Let it create the enum. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Serhiy Storchaka Sent: Friday, July 30, 2021 4:22 AM To: python-list@python.org Subject: Re: Defining a Python enum in a C extension - am I doing this right? 23.07.21 11:20, Bartosz Golaszewski пише: > I'm working on a Python C extension and I would like to expose a > custom enum (as in: a class inheriting from enum.Enum) that would be > entirely defined in C. I think that it would be much easier to define it in Python, and then either import a Python module in your C code, or exec a Python code as a string. -- https://mail.python.org/mailman/listinfo/python-list
question on trax
In the following code, where does tl.Fn come from? i see it nowhere in the documents, i.e I was looking for trax.layers.Fn : import numpy as np *from trax import layers as tl* from trax import shapes from trax import fastmath # def Addition(): layer_name = "Addition" # don't forget to give your custom layer a name to identify # Custom function for the custom layer def func(x, y): return x + y return *tl.Fn*(layer_name, func) # Test it add = Addition() # Inspect properties print("-- Properties --") print("name :", add.name) print("expected inputs :", add.n_in) print("promised outputs :", add.n_out, "\n") # Inputs x = np.array([3]) y = np.array([4]) print("-- Inputs --") print("x :", x, "\n") print("y :", y, "\n") # Outputs z = add((x, y)) print("-- Outputs --") print("z :", z) -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
Re: question on trax
yes, but I do not see Fn anywhere. Another question is on this line: z = add((x, y)) If I code: z = add(x, y) Then the following exception occurs : *Expected input to be a tuple or list; instead got .* Am Di., 17. Aug. 2021 um 19:21 Uhr schrieb MRAB : > On 2021-08-17 16:50, joseph pareti wrote: > > In the following code, where does tl.Fn come from? i see it nowhere in > the > > documents, i.e I was looking for trax.layers.Fn : > > > > import numpy as np > > *from trax import layers as tl* > > from trax import shapes > > from trax import fastmath > > # > > def Addition(): > > layer_name = "Addition" # don't forget to give your custom layer a > > name to identify > > > > # Custom function for the custom layer > > def func(x, y): > > return x + y > > > > return *tl.Fn*(layer_name, func) > > > [snip] > It comes from using the line: > > from trax import layers as tl > > so it's equivalent to 'trax.layers.Fn'. > -- > https://mail.python.org/mailman/listinfo/python-list > -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
RE: matplotlib questions
Complete documentation link (this link works) : https://matplotlib.org/stable/contents.html --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Steve Sent: Thursday, August 26, 2021 11:48 AM To: python-list@python.org Subject: matplotlib questions I am trying to modify the "Bar Graph Demo" at https://matplotlib.org/stable/gallery/index.html, Lines, bars, and markers but the more I experiment and change the code, the more messed up it becomes. I have the demo code working. This is my second attempt. I guess I accidentally got my first chart working but this second one, not so good. Is there any source to help me understand how the code works and how to change it? Among many others options, how do I change the font size? How are the labels placed on the X-axis and Y-axis? -- https://mail.python.org/mailman/listinfo/python-list
code to initialize a sequence
In the code attached below, the A-variant is from somebody else who knows Python better than I. But I do not like to just use any code without having a grasp, specifically the line in* bold*, so I wrote the B-variant which gives the same results. The C-variant is identical to A and is there for verification: after resetting the seed I expect the same sequence. The D-variant is closer to the way I code, and it does not work. import random from random import randint, seed def generate_sequence(length, n_unique): *return [randint(0, n_unique-1) for k in range(length)]* def generate_sequence_JP(length, n_unique): LI = [] for k in range(length): LI.append(randint(0, n_unique-1)) return(LI) def generate_sequence_EXPLICIT(length, n_unique): X =[None] * length for i in range(length): X[i] = [randint(0, n_unique-1)] return X # # MAIN PROGRAM # random.seed(2) A = generate_sequence(4, 10 ) random.seed(2) B = generate_sequence_JP(4, 10) random.seed(2) C = generate_sequence(4, 10 ) random.seed(2) D = generate_sequence_EXPLICIT(4, 10 ) print(A) print(type(A)) print('-') print(B) print(type(B)) print('-') print(C) print(type(C)) print('-') print(D) print(type(D)) Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
RE: on floating-point numbers
What's really going on is that you are printing out more digits than you are entitled to. 39.61 : 16 decimal digits. 4e16 should require 55 binary bits (in the mantissa) to represent, at least as I calculate it. Double precision floating point has 52 bits in the mantissa, plus one assumed due to normalization. So 53 bits. The actual minor difference in sums that you see is because when you put the largest value 1st it makes a difference in the last few bits of the mantissa. I recommend that you print out double precision values to at most 14 digits. Then you will never see this kind of issue. If you don't like that suggestion, you can create your own floating point representation using a Python integer as the mantissa, so it can grow as large as you have memory to represent the value; and a sign and an exponent. It would be slow, but it could have much more accuracy (if implemented to preserve accuracy). By the way, this is why banks and other financial institutions use BCD (binary coded decimal). They cannot tolerate sums that have fraction of a cent errors. I should also point out another float issue: subtractive cancellation. Try 1e14 + 0.1 - 1e14. The result clearly should be 0.1, but it won't be. That's because 0.1 cannot be accurately represented in binary, and it was only represented in the bottom few bits. I just tried it: I got 0.09375 This is not a Python issue. This is a well known issue when using binary floating point. So, when you sum a large array of data, to avoid these issues, you could either 1) sort the data smallest to largest ... may be helpful, but maybe not. 2) Create multiple sums of a few of the values. Next layer: Sum a few of the sums.Top layer: Sum the sum of sums to get the final sum. This is much more likely to work accurately than adding up all the values in one summation except the last, and then adding the last (which could be a relatively small value). --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Hope Rouselle Sent: Thursday, September 2, 2021 9:51 AM To: python-list@python.org Subject: on floating-point numbers Just sharing a case of floating-point numbers. Nothing needed to be solved or to be figured out. Just bringing up conversation. (*) An introduction to me I don't understand floating-point numbers from the inside out, but I do know how to work with base 2 and scientific notation. So the idea of expressing a number as mantissa * base^{power} is not foreign to me. (If that helps you to perhaps instruct me on what's going on here.) (*) A presentation of the behavior >>> import sys >>> sys.version '3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)]' >>> ls = [7.23, 8.41, 6.15, 2.31, 7.73, 7.77] >>> sum(ls) 39.594 >>> ls = [8.41, 6.15, 2.31, 7.73, 7.77, 7.23] >>> sum(ls) 39.61 All I did was to take the first number, 7.23, and move it to the last position in the list. (So we have a violation of the commutativity of addition.) Let me try to reduce the example. It's not so easy. Although I could display the violation of commutativity by moving just a single number in the list, I also see that 7.23 commutes with every other number in the list. (*) My request I would like to just get some clarity. I guess I need to translate all these numbers into base 2 and perform the addition myself to see the situation coming up? -- https://mail.python.org/mailman/listinfo/python-list
RE: on floating-point numbers
Actually, Python has an fsum function meant to address this issue. >>> math.fsum([1e14, 1, -1e14]) 1.0 >>> Wow it works. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Hope Rouselle Sent: Thursday, September 2, 2021 9:51 AM To: python-list@python.org Subject: on floating-point numbers Just sharing a case of floating-point numbers. Nothing needed to be solved or to be figured out. Just bringing up conversation. (*) An introduction to me I don't understand floating-point numbers from the inside out, but I do know how to work with base 2 and scientific notation. So the idea of expressing a number as mantissa * base^{power} is not foreign to me. (If that helps you to perhaps instruct me on what's going on here.) (*) A presentation of the behavior >>> import sys >>> sys.version '3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)]' >>> ls = [7.23, 8.41, 6.15, 2.31, 7.73, 7.77] >>> sum(ls) 39.594 >>> ls = [8.41, 6.15, 2.31, 7.73, 7.77, 7.23] >>> sum(ls) 39.61 All I did was to take the first number, 7.23, and move it to the last position in the list. (So we have a violation of the commutativity of addition.) Let me try to reduce the example. It's not so easy. Although I could display the violation of commutativity by moving just a single number in the list, I also see that 7.23 commutes with every other number in the list. (*) My request I would like to just get some clarity. I guess I need to translate all these numbers into base 2 and perform the addition myself to see the situation coming up? -- https://mail.python.org/mailman/listinfo/python-list
RE: ANN: Dogelog Runtime, Prolog to the Moon (2021)
Opinion: Anyone who is counting on Python for truly fast compute speed is probably using Python for the wrong purpose. Here, we use Python to control Test Equipment, to set up the equipment and ask for a measurement, get it, and proceed to the next measurement; and at the end produce a nice formatted report. If we wrote the test script in C or Rust or whatever it could not run substantially faster because it is communicating with the test equipment, setting it up and waiting for responses, and that is where the vast majority of the time goes. Especially if the measurement result requires averaging it can take a while. In my opinion this is an ideal use for Python, not just because the speed of Python is not important, but also because we can easily find people who know Python, who like coding in Python, and will join the company to program in Python ... and stay with us. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Mostowski Collapse Sent: Tuesday, September 14, 2021 8:56 AM To: python-list@python.org Subject: Re: ANN: Dogelog Runtime, Prolog to the Moon (2021) I am testing a Prolog interpreter written in Python. So fibonacci number routine is written in Prolog and I am running the fibonnaci number routine inside the Prolog interpreter that is written in Python. The factor 6x times faster of GraalVM can be reproduced also for other Prolog programs running inside the Prolog interpreter that is written in Python. I have a benchmark suite, where I get, the figures are milliseconds: TestStandardGraalVM Total170'996 28'523 This means the factor is: 170'996 / 28'523 = 5.9950 The test harness, test cases and individual results for all test cases are found here: And we could test GraalVM Python, results are from 14.09.2021, tested with Dogelog Runtime 0.9.5, Python Version: https://gist.github.com/jburse/f4e774ebb15cac722238b26b1a620f84#gistcomment-3892587 Terry Reedy wrote: > On 9/13/2021 8:46 AM, Mostowski Collapse wrote: >> The Standard Python version of Dogelog runtime is annoyingly slow. So >> we gave it a try with andother Python, and it was 6x times faster. >> >> We could test GraalVM. We worked around the missing match in Python >> 3.8 by replacing it with if-then-else. >> Performance is a little better, we find: >> >> /* Standard Python Version, Warm Run */ >> ?- time(fibo(23,X)). >> % Wall 3865 ms, gc 94 ms, 71991 lips >> X = 46368. >> >> /* GraalVM Python Version, Warm Warm Run */ >> ?- time(fibo(23,X)). >> % Wall 695 ms, gc 14 ms, 400356 lips >> X = 46368. >> >> See also: >> >> JDK 1.8 GraalVM Python is 6x faster than Standard Python >> https://twitter.com/dogelogch/status/1437395917167112193 >> >> JDK 1.8 GraalVM Python is 6x faster than Standard Python >> https://www.facebook.com/groups/dogelog > > You need to test more than fibonacci to make that claim. There is a > benchmark test that times around 40 different similarly small benchmarks. > > -- https://mail.python.org/mailman/listinfo/python-list
RE: New assignmens ...
Why force unpacking? Why not assign a tuple? That would look like a simple assignment: x := (alpha, beta, gamma) And you could access x[0], x[1] and x[2]. I think asking := to support x, y := alpha, beta is a request to address an unnecessary, easily worked around, issue. And as previously pointed out you can still just use = . --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Chris Angelico Sent: Monday, October 25, 2021 6:25 PM To: Python Subject: Re: New assignmens ... On Tue, Oct 26, 2021 at 9:19 AM dn via Python-list wrote: > Back on-topic, I am slightly curious:- > > aside from 'starting small' with an option to widen/'open-up' later, > is there a particular reason why 'the walrus' has not been made > available (could not be ...?) for use with object-attributes? I can't think of any other reasons. But the one you cite is quite an important one. In order to get real-world usage examples, the feature was rolled out in the restricted form, because threads like this are *exactly* how the value can be judged. So I do not in any way regret that assignment expressions were accepted in their current form, but also, don't be afraid to propose an opening up of the syntax. Be specific, and cite usage examples that would benefit. TBH, I don't think there's a lot of value in multiple-assignment, since it has a number of annoying conflicts of syntax and few viable use-cases. But if you have great examples of "x.y :=" or "x[y] :=", then by all means, post on python-ideas to propose widening the scope. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
RE: Problem with concatenating two dataframes
The problem I see here is use of Pandas. I know I have he losing opinion, but people who use Python to load Panadas and then only use Pandas are missing out on the functionality of Python. I'll bet you could code combining this data in pure Python, into one dictionary. In fact I'd be shocked if you couldn't do it. Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Mahmood Naderan Sent: Saturday, November 6, 2021 6:01 PM To: python-list@python.org; MRAB Subject: Re: Problem with concatenating two dataframes >The second argument of pd.concat is 'axis', which defaults to 0. Try >using 1 instead of 0. Unfortunately, that doesn't help... dict[name] = pd.concat( [dict[name],values], axis=1 ) {'dummy': Value M1 0 M2 0 M3 0, 'K1':Value Value 0 10.0NaN 15.0NaN 2 10.0NaN 6NaN2.0 7NaN2.0 8NaN2.0, 'K2':Value 3 20 4 10 5 15} Regards, Mahmood -- https://mail.python.org/mailman/listinfo/python-list
RE: Behavior of the for-else construct
Useful: On rare occasions (when a loop has a "break" in it) Used: Yes Know how it works: Yes Even is such a thing: Yes Your suggestion: Also useful. Will require a different keyword. I don't know what that would be. "finally" is available 😊 Write up a feature request. --- Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: computermaster360 Sent: Thursday, March 3, 2022 8:24 AM To: python-list@python.org Subject: Behavior of the for-else construct I want to make a little survey here. Do you find the for-else construct useful? Have you used it in practice? Do you even know how it works, or that there is such a thing in Python? I have used it maybe once. My issue with this construct is that calling the second block `else` doesn't make sense; a much more sensible name would be `then`. Now, imagine a parallel universe, where the for-else construct would have a different behavior: for elem in iterable: process(elem) else: # executed only when the iterable was initially empty print('Nothing to process') Wouldn't this be more natural? I think so. Also, I face this case much more often than having detect whether I broke out of a loop early (which is what the current for-else construct is for). Now someone may argue that it's easy to check whether the iterable is empty beforehand. But is it really? What if it's an iterator? Then one would have to resort to using a flag variable and set it in each iteration of the loop. An ugly alternative would be trying to retrieve the first element of the iterable separately, in a try block before the for-loop, to find out whether the iterable is empty. This would of course require making an iterator of the iterable first (since we can't be sure it is already an iterator), and then -- if there are any elements -- processing the first element separately before the for-loop, which means duplicating the loop body. You can see the whole thing gets really ugly really quickly... What are your thoughts? Do you agree? Or am I just not Dutch enough...? -- https://mail.python.org/mailman/listinfo/python-list
RE: Behavior of the for-else construct
Can someone please change the topic of this thread? No longer about for-else. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Dennis Lee Bieber Sent: Sunday, March 6, 2022 1:29 PM To: python-list@python.org Subject: Re: Behavior of the for-else construct On Sun, 6 Mar 2022 17:39:51 +0100, "Peter J. Holzer" declaimed the following: > >(* *) for comments was actually pretty commonly used - maybe because it >stands out more than { }. I don't know if I've ever seen (. .) instead >of [ ]. > Or some terminals provided [ ] but not { } Modula-2 appears to have fixed on (* *) for comments, and only [ ] for indexing. Consider the potential mayhem going from a language where { } are comment delimiters to one where they are block delimiters >C also has alternative rerpresentations for characters not in the >common subset of ISO-646 and EBCDIC. However, the trigraphs are >extremely ugly (e.g ??< ??> instead of { }). I have seen them used (on >an IBM/390 system with an EBCDIC variant without curly braces) and it's >really no fun to read that. > My college mainframe used EBCDIC, but the available languages did not include C or Pascal. We had APL, FORTRAN-IV (in full separate compilation form, and FLAG [FORTRAN Load and Go] which was a "all in one file, compile & run" used by first year students), COBOL (74?), BASIC, SNOBOL, Meta-Symbol and AP (both assemblers, though Meta-Symbol could, provided the proper definition file, generate absolute binary code for pretty much any processor), and something called SL-1 (Simulation Language-1, which produced FORTRAN output for discrete event models). UCSD Pascal, and PDP-11 assembly were run on a pair of LSI-11 systems. Assembly used for the operating system principles course. I didn't encounter "real" C until getting a TRS-80 (first as integer LC, then Pro-MC), along with Supersoft LISP (on cassette tape!). (I had books for C and Ada before encountering compilers for them) -- Wulfraed Dennis Lee Bieber AF6VN wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
RE: Reportlab / platypus bug?
I realize this is Python code, but I doubt that the question is a Python question. I have used Python +numpy, scipy, matplotlib for years. I have not used reportlab and have no idea about the reported problem except that I will be very surprised if it turns out to be a Python language issue. Is there possibly a better place to ask this question? Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Les Sent: Sunday, March 13, 2022 4:56 PM To: python-list@python.org Subject: Reportlab / platypus bug? Hello, I have found an error, and I created a minimal working example. The minimal working example starts with the very first example from Platypus user guide: from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import A4 from reportlab.lib.units import inch PAGE_HEIGHT = A4[1] PAGE_WIDTH = A4[0] styles = getSampleStyleSheet() Title = "Hello world" pageinfo = "platypus example" def myFirstPage(canvas, doc): canvas.saveState() canvas.setFont('Times-Bold', 16) canvas.drawCentredString(PAGE_WIDTH / 2.0, PAGE_HEIGHT - 108, Title) canvas.setFont('Times-Roman', 9) canvas.drawString(inch, 0.75 * inch, "First Page / %s" % pageinfo) canvas.restoreState() def myLaterPages(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 9) canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo)) canvas.restoreState() def go(): Story = [Spacer(1, 2 * inch)] style = styles["Normal"] for i in range(100): bogustext = ("This is Paragraph number %s. " % i) * 20 p = Paragraph(bogustext, style) Story.append(p) Story.append(Spacer(1, 0.2 * inch)) doc = SimpleDocTemplate("phello.pdf") doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) go() If I change it to this (e.g. generate two identical files): doc = SimpleDocTemplate("phello.pdf") doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc = SimpleDocTemplate("phello2.pdf") doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) then it builds phello.pdf correctly, but builds a totally empty phello2.pdf (960 bytes, a single white empty page). It is hard to explain as it is, but something even more interesting happens if you try to make them totally independent, and create a copy of the story as well: import copy doc = SimpleDocTemplate("phello.pdf") doc.build(copy.copy(Story), onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc = SimpleDocTemplate("phello2.pdf") doc.build(copy.copy(Story), onFirstPage=myFirstPage, onLaterPages=myLaterPages) This will render phello.pdf correctly, and it will throw this error when rendering phello2.pdf: Traceback (most recent call last): File "C:\Projects\test\test2.py", line 48, in go() File "C:\Projects\test\test2.py", line 45, in go doc.build(copy.copy(Story), onFirstPage=myFirstPage, onLaterPages=myLaterPages) File "C:\Users\nagyl\.virtualenvs\test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py", line 1314, in build BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker) File "C:\Users\nagyl\.virtualenvs\ test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py", line 1079, in build self.handle_flowable(flowables) File "C:\Users\nagyl\.virtualenvs\ test-NC9-O-tN\lib\site-packages\reportlab\platypus\doctemplate.py", line 958, in handle_flowable raise LayoutError(ident) reportlab.platypus.doctemplate.LayoutError: Flowable This is Paragraph number 6. This is Paragraph number 6. This(439.27559055118115 x 72) too large on page 1 in frame 'normal'(439.27559055118115 x 685.8897637795277) of template 'First' And finally, here is the "solution" that solves all problems: def go(): def create_story(): Story = [Spacer(1, 2 * inch)] style = styles["Normal"] for i in range(100): bogustext = ("This is Paragraph number %s. " % i) * 20 p = Paragraph(bogustext, style) Story.append(p) Story.append(Spacer(1, 0.2 * inch)) return Story doc = SimpleDocTemplate("phello.pdf") doc.build(create_story(), onFirstPage=myFirstPage, onLaterPages=myLaterPages) doc = SimpleDocTemplate("phello2.pdf") doc.build(create_story(), onFirstPage=myFirstPage, onLaterPages=myLaterPages) This does not throw an error, and it renders both files correctly. But I do not see why this last version works, and the previous one (that uses copy.copy) does not. I was looking for an explanation in the user guide. I was looking for a note, telling me that a story can be used for document generation only once. But there is no such thing in the docs. Or maybe I just did not find it. Can somebody please explain what is happening here? Environment details: Python 3.10.1 amd64 on Windows, reportla
RE: Functionality like local static in C
Yes, python has something like that. In fact, two things. 1) Generator. Use a "yield" statement. Every call "yields" a new value. The state of the function (local variables) is remembered from each previous call to the next. 2) In a file, declare a variable to be global. In the function declare global var, so that it will not only read the global but will also write it. That variable does not go away. On the next time the function is called, It will hold whatever value it had when the function finished previously. Joseph S. Teledyne Confidential; Commercially Sensitive Business Data -Original Message- From: Cecil Westerhof Sent: Thursday, April 14, 2022 11:02 AM To: python-list@python.org Subject: Functionality like local static in C In C when you declare a variable static in a function, the variable retains its value between function calls. The first time the function is called it has the default value (0 for an int). But when the function changes the value in a call (for example to 43), the next time the function is called the variable does not have the default value, but the value it had when the function returned. Does python has something like that? -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list
Re: Question regarding stdlib distutils strtobool behavior
On 8/9/16 1:42 PM, Terry Reedy wrote: > On 8/9/2016 9:22 AM, Joseph Bane wrote: >> Hello. >> >> It recently came to my attention that the strtobool function in the >> standard library doesn't return Python native boolean values, but >> rather returns integer 0 or 1: >> >> https://hg.python.org/cpython/file/3.5/Lib/distutils/util.py#l304 >> >> I am curious why this is the defined behavior and whether anyone can >> fill me in regarding this approach. For clarity, I would expect the >> code to `return True` and `return False` rather than `return 1` and >> `return 0`. > > I am rather sure distutils predates 2.2 and the addition of bool. Much > code has been converted from 0/1 to False/True. I don't know if this > particular holdover is intentional -- fear of breaking something -- or > oversight/inertia. > > I searched the tracker for 'strtobool' in component 'distutiles', status > "don't care", and there were no hits. (Search is not perfect, though.) > > Thanks for the legwork here! I have created the following issue after I read this: http://bugs.python.org/issue27721 Hopefully it will get some more discussion going. Thanks also to Michael Selik for his great advice in his last response! I think it's great we're having such positive conversations! -- https://mail.python.org/mailman/listinfo/python-list
issues when buidling python3.* on centos 7
I have a VM in the cloud running centos that comes with python 2.7 installed on it. For my purpose, I need python 3.5 (or 6?) However there is an issue with urlgrabber, and I believe this is due to inconsistencies with the 2 python versions, whcih I am not able to resolve. DETAILS INSTALL PYTHON 3 from scratch https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-centos-7 change /usr/bin/yum because yum does not support python 3 so force it to use python 2 in first line, else you get this: except KeyboardInterrupt, e: edits in /usr/libexec/urlgrabber-ext-down to remove syntax errors sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm [joepareti54@xxx ~]$ sudo yum -y install python36u Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * epel: ftp.nluug.nl * ius: mirror.amsiohosting.net Traceback (most recent call last): File "/usr/libexec/urlgrabber-ext-down", line 22, in from urlgrabber.grabber import \ ModuleNotFoundError: No module named 'urlgrabber' Exiting on user cancel [joepareti54@xxx ~]$ therefore wget http://mirror.centos.org/centos/7/os/x86_64/Packages/python-urlgrabber-3.10-8.el7.noarch.rpm sudo yum install python-urlgrabber-3.10-8.el7.noarch.rpm now rerun sudo yum -y install python36u basically same as here https://www.centos.org/forums/viewtopic.php?t=52325 the urlgrabber is not found The following may give a clue because of inconsistent python versions: [joepareti54@xxx ~]$ python -V Python 3.5.2 :: Anaconda 4.3.0 (64-bit) [joepareti54@xxx ~]$ rpm -ql python-urlgrabber | xargs -i dirname '{}' | sort | uniq | grep site-packages /usr/lib/python2.7/site-packages /usr/lib/python2.7/site-packages/urlgrabber [joepareti54@xxx ~]$ so the install of python-urlgrabber-3.10-8.el7.noarch.rpm landed in the wrong place as suggested here https://forums.fedoraforum.org/showthread.php?95680-yum-broken-(-quot-No-module-named-urlgrabber-quot-) and the inconsistency explains why the grabber module is not found -- https://mail.python.org/mailman/listinfo/python-list
Re: issues when buidling python3.* on centos 7
thank you so much. here's more detail on my troubleshooting. - STARTING POINT: https://github.com/google/FluidNet as shown in the readme files, the deployment calls for the following step: cd FluidNet/manta/build ./manta ../scenes/_trainingData.py --dim 3 --addModelGeometry True --addSphereGeometry True The above command should produce the training data, so that torch will work on it to train the deep network. However, it fails due to incompatibilities of python 2.7 and 3.x; the problem is described in: https://stackoverflow.com/questions/49296737/invalid-syntax-in-python-function The option of removing python constructs that are only supported in python 3 is not successful because there are more dependencies than just a couple of statements, namely in the Simplified Wrapper Interface Generator (or SWIG) which assumes python3. Therefore, I need a python 3 environment. STEPS: sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm sudo yum shell remove python36-3.6.3-7.el7.x86_64 remove python36-libs-3.6.3-7.el7.x86_64 install python36u-3.6.4-1.ius.centos7.x86_64 install python36u-libs-3.6.4-1.ius.centos7.x86_64 run [joepareti54@xxx ~]$ sudo yum install python36u Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * epel: epel.mirror.wearetriple.com * ius: mirror.amsiohosting.net Package python36u-3.6.4-1.ius.centos7.x86_64 already installed and latest version Nothing to do [joepareti54@xxx ~]$ ASSUMING python36 is now fine, so moving to the next step. sudo yum -y install python36u-pip sudo yum install python36u-devel >From here on, it's manta-application specific: cmake .. -DGUI='OFF' >> cmake-10.log 2>&1 make -j8 >> make-10.log 2>&1 ./manta ../scenes/_trainingData.py --dim 3 --addModelGeometry True --addSphereGeometry True Version: mantaflow 64bit fp1 commit dd3bb0c0a65cc531d3c33487bde5edcb4aa6784f from Mar 29 2018, 15:21:34 Loading script '../scenes/_trainingData.py' Traceback (most recent call last): File "../scenes/_trainingData.py", line 13, in from voxel_utils import VoxelUtils File "/home/joepareti54/FluidNet/manta/scenes/voxel_utils.py", line 1, in import numpy as np ModuleNotFoundError: No module named 'numpy' Script finished. cmake options are specified in the CMakeCache.txt file, and those can be edited to select the right python environment as explained in: https://stackoverflow.com/questions/15291500/i-have-2-versions-of-python-installed-but-cmake-is-using-older-version-how-do In my case i have following settings: joepareti54@xxx build]$ cat CMakeCache.txt | grep -i python //Compile without python support (limited functionality!) PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3.6m PYTHON_INCLUDE_DIR:PATH=/usr/include/python3.6m PYTHON_LIBRARY:FILEPATH=/usr/lib64/libpython3.6m.so FIND_PACKAGE_MESSAGE_DETAILS_PythonLibs:INTERNAL=[/usr/lib64/ libpython3.6m.so][/usr/include/python3.6m][v3.6.4()] I don't see why manta cannot find numpy, because python does find it: [joepareti54@xxx ~]$ python Python 3.5.2 |Anaconda 4.3.0 (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> [joepareti54@xxx ~]$ Also note that system wide python 2.7 is still there, and it is required by centos: [joepareti54@xxx ~]$ ls -l /usr/bin/python lrwxrwxrwx. 1 root root 18 Mar 29 08:00 /usr/bin/python -> /usr/bin/python2.7 [joepareti54@xxx ~]$ In addition: [joepareti54@xxx build]$ python3.6 -V Python 3.6.3 [joepareti54@xxx build]$ which python /anaconda/envs/py35/bin/python [joepareti54@xxx build]$ file /anaconda/envs/py35/bin/python /anaconda/envs/py35/bin/python: symbolic link to `python3.5' [joepareti54@xxx build]$ ls -l /anaconda/envs/py35/bin/python lrwxrwxrwx. 1 root root 9 Nov 10 2016 /anaconda/envs/py35/bin/python -> python3.5 [joepareti54@xxx build]$ ls -l /usr/bin/python lrwxrwxrwx. 1 root root 18 Mar 29 08:00 /usr/bin/python -> /usr/bin/python2.7 [joepareti54@xxx build]$ CONCLUSION In summary, I don't know whether this configuration is consistent or not for building the manta application, and whether the python set-up is consistent. Also to be noted that the manta application was built by the authors on an ubuntu platform, so my work is an adaption to centos 2018-03-27 4:07 GMT+02:00 Michael Torrie : > On 03/25/2018 10:15 AM, joseph pareti wrote: > > The following may give a clue because of inconsistent python versions: > > > > [joepareti54@xxx ~]$ python -V > > Python 3.5.2 :: Anaconda 4.3.0 (64-bit) > > What does 'which python' return? As Joseph said, hopefully you didn't > overwrite /usr/bin/python with Python 3.5. If you did, you're hosed. > You
permission denied when installing tensorflow on centos 7
here are details on my attempt: tensorflow for centos 7 installation guidelines are in: https://gist.github.com/thoolihan/28679cd8156744a62f88 sudo yum -y install epel-release sudo yum -y install gcc gcc-c++ python-pip python-devel atlas atlas-devel gcc- gfortran openssl-devel libffi-devel # use pip or pip3 as you prefer for python or python3 pip install --upgrade virtualenv virtualenv --system-site-packages ~/venvs/tensorflow source ~/venvs/tensorflow/bin/activate pip install --upgrade numpy scipy wheel cryptography #optional pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0rc0-cp35- cp35m-linux_x86_64.whl # or below if you want gpu, support, but cuda and cudnn are required, see docs for more install instructions pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.10.0rc0-cp35- cp35m-linux_x86_64.whl EXECUTION /STEP 1 OK EXECUTION /STEP 2 OK EXECUTION /STEP 3 [joepareti54@xxx tensorflow_tmpdir]$ pip3 install --upgrade virtualenv >> step3.txt 2>&1 [joepareti54@xxx tensorflow_tmpdir]$ cat step3.txt Collecting virtualenv Downloading https://files.pythonhosted.org/packages/ed/ea/e20b5cbebf45d3096e8138ab74eda139595d827677f38e9dd543e6015bdf/virtualenv-15.2.0-py2.py3-none-any.whl (2.6MB) Installing collected packages: virtualenv Exception: Traceback (most recent call last): File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/anaconda/envs/py35/lib/python3.5/site-packages/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/anaconda/envs/py35/lib/python3.5/shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: '/anaconda/envs/py35/lib/python3.5/site-packages/virtualenv.py' You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. [joepareti54@xxx tensorflow_tmpdir]$ -- https://mail.python.org/mailman/listinfo/python-list
syntax error (?) on ubuntu
$ python tf_simple.py /anaconda/envs/py35/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Traceback (most recent call last): File "tf_simple.py", line 29, in import uniio File "../tools/uniio.py", line 132 if(PY3K): ID = ID.decode("utf-8") ^ TabError: inconsistent use of tabs and spaces in indentation -- https://mail.python.org/mailman/listinfo/python-list
ImportError: cannot import name _remove_dead_weakref
on an Ubuntu VM with : 1. Linux JP-Paid-UBUNTU-DSVM 4.13.0-1014-azure 2. Python 3.5.4 :: Anaconda custom (64-bit) $ manta manta_genSimData.py Loading script 'manta_genSimData.py' Traceback (most recent call last): skipping some details ... File "/anaconda/lib/python2.7/weakref.py", line 14, in from _weakref import ( *ImportError: cannot import name _remove_dead_weakref* Script finished. -- https://mail.python.org/mailman/listinfo/python-list
Re: ImportError: cannot import name _remove_dead_weakref
please excuse my full python ignorance, however if I set PYTHONPTAH as shown below, then the results are quite different than before: $ echo $PYTHONPATH /backupdata/anaconda/lib/python2.7/ $ python tf_train_pressure.py Fatal Python error: Py_Initialize: Unable to get the locale encoding File "/backupdata/anaconda/lib/python2.7/encodings/__init__.py", line 124 raise CodecRegistryError,\ ^ SyntaxError: invalid syntax Current thread 0x7f2b4459f700 (most recent call first): Aborted (core dumped) 2018-05-03 19:15 GMT+02:00 Chris Angelico : > On Fri, May 4, 2018 at 1:53 AM, joseph pareti > wrote: > > on an Ubuntu VM with : > > > > > >1. Linux JP-Paid-UBUNTU-DSVM 4.13.0-1014-azure > >2. Python 3.5.4 :: Anaconda custom (64-bit) > > > > $ manta manta_genSimData.py > > Loading script 'manta_genSimData.py' > > Traceback (most recent call last): > > > > skipping some details > > > > ... > > File "/anaconda/lib/python2.7/weakref.py", line 14, in > > from _weakref import ( > > *ImportError: cannot import name _remove_dead_weakref* > > Script finished. > > Somehow, the details you're skipping include jumping from a Python > 3.5.4 into a Python 2.7's standard library. Check your Anaconda > settings and see if you have something bizarre going on with your > PYTHONPATH. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: ImportError: cannot import name _remove_dead_weakref
thank you for the advice: depending on the value of PYTHONPATH (version 2.7, 3.5, or unset), tensorflow stops with 3 different error traps 2018-05-04 7:55 GMT+02:00 dieter : > Chris Angelico writes: > > ... > > Somewhere, you have a mismatch of versions. Make sure you're using the > > same Python version for everything. You have some Python 2.7 messing > > up your 3.5. > > I have had similar problems. In my case, an active "PYTHONPATH" envvar > was responsible -- "unset"ting this envar has resolved the problem for me. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: ImportError: cannot import name _remove_dead_weakref
thanks for the hint, virtualenv looks like an interesting option, however in my case I need to rely on several components that are already installed in the VM in Azure, including tensorflow, etc. If I use virtualenv, do I need to start from scratch? In addition, I am not sure this will solve my problem: all I have seen is that the error code changes depending on the PYTHONPATH value. Perhaps it is a bug in the application code? 2018-05-05 9:12 GMT+02:00 dieter : > joseph pareti writes: > > thank you for the advice: depending on the value of PYTHONPATH (version > > 2.7, 3.5, or unset), tensorflow stops with 3 different error traps > > "PYTHONPATH" usually is used when you have private Python modules > not installed at the standard place. Nowadays, you can use > a so called "virtual environment" for your local installations. > Look whether "virtualenv" (or "venv") is installed in your environment. > It can be used to create a virtual environment. > Then install your own modules in this virtual environment -- > ensuring not to mix things for Python 2 and Python 3. > Finally unset "PYTHONPATH" and run your Python in the virtual environment. > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
RE: "Data blocks" syntax specification draft
I understand that the /// data representation is meant to emphasize data structure (and de-emphasize existing Python syntax for that purpose). It's already been discussed that Python can export to pickle format, JSON, csv, XML and possibly others I can't think of right now. So having a data representation format is not a foreign concept. All I want to say is that I don't really feel that there is a need for another data representation. Also, even if we leave out parentheses, "/// a,b,c" is 9 characters, whereas "(a,b,c)" is 7 characters. And "a,b,c" is only 5 characters. I think I would actually prefer the usual Python syntax, because to me it is clear (I already know Python) and typing fewer characters to achieve the same result appeals to me. Perhaps I just don't value the benefit of this data representation technique, or perhaps there really is a benefit that I didn't get. If so forgive me. But I do think that a good exposition of the benefit obtained by using this data representation will need to be made, or you may find that there are many other people like me. --- Joseph S. -Original Message- From: Chris Angelico Sent: Wednesday, May 23, 2018 9:56 AM To: Python Subject: Re: "Data blocks" syntax specification draft On Wed, May 23, 2018 at 11:11 PM, Steven D'Aprano wrote: > On Wed, 23 May 2018 11:10:33 +0100, bartc wrote: >> 0 items within the list: >> >> ()Empty tuple >> []Empty list >> {}Empty dict > > Aye ... as we've acknowledged numerous times now, the empty tuple *is* > a genuine special case, one which *does* rely on an empty pair of > round brackets. We actually have THREE special cases and only two types that follow the general case. Here's the general case: List of three: [1, 2, 3] or [1, 2, 3,] List of two: [1, 2] or [1, 2,] List of one: [1] or [1,] List of zero: [] Dict of three: {1:1, 2:2, 3:3} or {1:1, 2:2, 3:3,} Dict of two: {1:1, 2:2} or {1:1, 2:2,} Dict of one: {1:1} or {1:1,} Dict of zero: {} Perfect! Now let's try that with other types. Tuple of three: 1, 2, 3 or 1, 2, 3, Tuple of two: 1, 2 or 1, 2, Tuple of one: 1, # no other way to do it Tuple of zero: () Set of three: {1, 2, 3} or {1, 2, 3,} Set of two: {1, 2} or {1, 2,} Set of one: {1} or {1,} Set of zero: set() The empty set and empty tuple are special, as is the single-element tuple (you can't omit the comma). So, yes, there are definitely special cases in the grammar, and they come about because practicality beats purity. If we wanted perfectly clean grammar with no special cases, we'd probably have to use two-character bracketings, to ensure that everything is uniquely spellable, and there'd be no omitting them from tuples - so it really WOULD be the bracketing characters that define a tuple. But what would we gain? Very little. A few less special cases, maybe, in return for needing to write more verbose syntax for every literal/display type. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
RE: logging with multiprocessing
Multiprocessing, not multithreading. Different processes. This is pretty easy to do. I have done this from a Python script to run an analysis program on many sets of data, at once. To do it: 1) if there is going to be an output file, each output file must have a distinct name. 2) To use logging, log to file, and each log file will have to have a distinct name. This is not hard to do. I assume input data is different for each run, so we don't have to do anything about that. Then there won't be any conflict. Input files are distinct output files are distinct, and log files are distinct. When I did this, we had the pleasure of running on a 20 core dual Xeon based system, I don't remember if ran 20 processes at a time or slightly less. Anyway, we really did achieve nearly linear speed up. Windows did assign these processes to separate cores. --- Joe S. -Original Message- From: jenil.desa...@gmail.com Sent: Thursday, June 7, 2018 2:46 PM To: python-list@python.org Subject: logging with multiprocessing Hello, I am new to logging module. I want to use logging module with multiprocessing. can anyone help me understand how can I do it?. Any help would be appreciated. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
RE: mutable sequences
No, it says lists are mutable and tuples are immutable. Mutable has the same root as "mutation". Mutable means "can be changed in place". Immutable means "cannot be changed in place". Examples: 1) pass your list to a function, the function modifies the list. When the function returns your script gets control back. Your list is modified. 2) pass a tuple to a function. The function wants to modify the tuple. It can't Append( ) to it, if it tries Python will throw an exception because tuples don't have an append method. It can't assign a new value to an element of the tuple. But it can assign different content to the tuple entirely. When the function returns your script gets control back. YOUR tuple is NOT modified. When the function assigned to it, a new tuple with a different ID was created. Basically, from that point on, the function had its own tuple. The original was not modified because it can't be modified. It's immutable. 3) You use a list constructor, i.e., function( list(mylist) ). That passes a copy of your list, which has a different ID, to the function. The function can append to it, or otherwise modify it. When the function returns, YOUR list is not modified because you didn't pass your list to the function; you passed a newly constructed copy of your list to the function. (Advanced comment: If a tuple has an element which is a list, that list is mutable. Thinking about whether the list inside the tuple should be modifiable gives me a headache. Try it and see what happens.) If you don't like the terms mutable and immutable, think of them as related to "pass by reference" and "pass by value" in some other languages. If you pass by reference, you give the function a reference to your object; it modifies your object. If you pass by value, you load a copy of your object probably onto the stack, to pass to the function; the function can modify the copy but your object is not modified (this seems most similar to example 3 above). To avoid having to copy huge things onto the stack, C++ grew a const keyword so that you can pass a const reference to a function, which means the function won't be allowed to modify it. I think this is very much like immutable. I think it's fair to say Python always passes by reference. Immutable types allow Python to have behavior that acts sort of like pass by value, or very much like passing a const reference in C++. (One difference is Python allows a line that looks like it's assigning to the tuple, but really it makes a new tuple.) In example 3 above Python didn't actually pass a copy of your list (which could be huge), it passed a reference to a copy of your list. --- Joseph Schachner -Original Message- From: Sharan Basappa Sent: Wednesday, June 13, 2018 10:57 PM To: python-list@python.org Subject: mutable sequences The term mutable appears quite often in Python. Can anyone explain what is meant by mutable and immutable sequences. For example, Python lists are mutable. BTW, is the below explanation correct (it is taken from a book I am reading) Python lists are mutable sequences. They are very similar to tuples, but they don't have the restrictions due to immutability. It says lists are mutable and then says they are immutable??? -- https://mail.python.org/mailman/listinfo/python-list
RE: syntax difference
As soon as I sent the previous message I realized it's "doc string" not def string. Pardon me. --- Joe S. -Original Message- From: Ed Kellett Sent: Monday, June 18, 2018 8:47 AM To: python-list@python.org Subject: Re: syntax difference On 2018-06-18 13:18, Chris Angelico wrote: > 1) Parse the code, keeping all the non-essential parts as well as the > essential parts. > 2) Find the comments, or find the annotations > 3) If comments, figure out if they're the ones you want to remove. > 4) Reconstruct the file without the bits you want to remember. > > Step 3 is removed if you're using syntactic annotations. Otherwise, > they're identical. It's likely that Python comments are much easier to remove than arbitrary bits of Python syntax--you need to know the answer to "am I in a string literal?", which is a lexical analysis problem you could hack together a solution for over the course of about one coffee, as opposed to "where exactly am I in the Python parse tree?", which is... harder. The information you need to keep track of and later reconstruct is substantially simpler, too. I don't think "they're hard to mechanically remove" is a particularly good argument against type hints, but considered on its own it probably is true. -- https://mail.python.org/mailman/listinfo/python-list
RE: syntax difference (type hints)
Assuming that we want Python to remain a dynamically typed (but strongly typed) language, I believe the proposed type hints are only necessary for function definitions, where the caller really needs to know the types of arguments to pass in. At the moment that purpose is (I think adequately) served by def strings, triple quoted strings immediately following the function declaration. When I do code reviews for Python developed here, if the argument names of a function do not hint at the type they should be and there is no def string then I insist that something be added. Often what gets added is a def string that says something about what the function does and explains what argument types are expected. -- Joseph S. -Original Message- From: Ed Kellett Sent: Monday, June 18, 2018 8:47 AM To: python-list@python.org Subject: Re: syntax difference On 2018-06-18 13:18, Chris Angelico wrote: > 1) Parse the code, keeping all the non-essential parts as well as the > essential parts. > 2) Find the comments, or find the annotations > 3) If comments, figure out if they're the ones you want to remove. > 4) Reconstruct the file without the bits you want to remember. > > Step 3 is removed if you're using syntactic annotations. Otherwise, > they're identical. It's likely that Python comments are much easier to remove than arbitrary bits of Python syntax--you need to know the answer to "am I in a string literal?", which is a lexical analysis problem you could hack together a solution for over the course of about one coffee, as opposed to "where exactly am I in the Python parse tree?", which is... harder. The information you need to keep track of and later reconstruct is substantially simpler, too. I don't think "they're hard to mechanically remove" is a particularly good argument against type hints, but considered on its own it probably is true. -- https://mail.python.org/mailman/listinfo/python-list
RE: syntax difference
On YouTube you can watch videos of Guido van Rossum presenting at PyCon from a few years ago, in which he makes clear that he has been thinking about this since 2000, that he wants someone else to guide this PEP along its path because he is too close to it, and that NOTHING about having a typing module requires you to use it. In fact, you can use it without affecting your source code and interleaving the (helpful) information into the source code. They support "stub" files, with a ".pyi" extension, in which you can place the declarations with the typing information. The type checker will read that an use it along with your unmodified source code to do its checking. He also thanked multiple people for their contributions bringing this from an idea to a preliminary implementation in 3.5 and now possibly final form in 3.6.6rc1. Now that you know that 1) You are not required to modify your source code at all, even if you want to get full utility from typing, and 2) you really don't have use typing at all, nothing forces you to, and 3) it's been developed by the Python community for years and was proposed by Guido years before he went to DropBox, does that help? -- Joe S. -Original Message- From: Rick Johnson Sent: Monday, June 18, 2018 1:16 PM To: python-list@python.org Subject: Re: syntax difference Steven D'Aprano wrote: > Moving the type-checking out of the core language into the IDE or > linter which can be used or not used according to the desire of the > programmer Except, what your poppycock commentary seems to glaze over is the fact that whilst a programmer can certainly decided to "use or not use" the type-hints feature in his or her own code, he or she certainly cannot "see or _unsee_" type-hints that are written by other programmers. -- https://mail.python.org/mailman/listinfo/python-list
RE: ironpython not support py3.6
Wait. -Original Message- From: fantasywan...@gmail.com Sent: Friday, June 22, 2018 2:45 AM To: python-list@python.org Subject: ironpython not support py3.6 We have a project implemented with c# and python, iron python is a good choice for us to integrate these two tech together but iron python not support python 3.6 yet, any suggest for this? -- https://mail.python.org/mailman/listinfo/python-list
Re: range
Re: "I know I'm going to get flak for bringing this up this old issue, but remember when you used to write a for-loop and it involved creating an actual list of N integers from 0 to N-1 in order to iterate through them? Crazy. But that has long been fixed - or so I thought. When I wrote, today: for i in range(1): pass # 100 million on Python 2, it used up 1.8GB, up to the limit of my RAM, and it took several minutes to regain control of my machine (and it never did finish). You don't expect that in 2018 when executing a simple empty loop. On Py 2 you have to use xrange for large ranges - that was the fix. Somebody however must have had to gently and tactfully point out the issue. I'm afraid I'm not very tactful." It HAS been fixed in Python 3, since the beginning of that branch. In Python 3 range is what xrange was in Python 2. I used past tense there on purpose. Python 2 actual demise is scheduled. See: https://python3statement.org/ It's a list of project that have pledged to drop support for Python2.7 no later than January 1, 2020. You will recognize many of them: Pandas, IPython, NumPy, Matplotlib, Jupyter... etc Anyone talking about the future of Python and features that might be added to Python really has to be talking about Python 3, because Python 2 support is already ramping down and will completely end on January 1, 2020. The original plan was to end it in 2015, but the extra five years were added to give everyone plenty of time to switch. -- Joseph S. -- https://mail.python.org/mailman/listinfo/python-list
RE: PEP 526 - var annotations and the spirit of python
It is interesting to contemplate how this could transform Python into nearly a statically typed language: x = 3 x = f(x) If you say the type checker should infer that x is an int, and then therefore complain about x=f(x) if f() does not return an int, then we have what in new C++ is auto type declaration by default, and after that it's statically typed. So this would still work valStr = QueryMeasuringInstrument("app.Meas.P1.Result.Mean") val = float(valStr) but this would not: val = QueryMeasuringInstrument("app.Meas.P1.Result.Mean") val = float(val) even though it works today in both Python 2 and Python 3. I don't think the intent of var annotations is to automatically extract the type for variables that are not annotated, and then insist that they retain the same type at all times. It would break this example. I think if I do annotate a variable, THEN the type checker can insist that I do not change its type. So this could cause an error: string val = QueryMeasuringInstrument("app.Meas.P1.Result.Mean") val = float(val) --- Joe S. -Original Message- From: Steven D'Aprano Sent: Wednesday, July 4, 2018 11:31 AM To: python-list@python.org Subject: Re: PEP 526 - var annotations and the spirit of python On Wed, 04 Jul 2018 13:48:26 +0100, Bart wrote: > Presumably one type hint applies for the whole scope of the variable, > not just the one assignment. You know how in C you can write int x = 1; # the type applies for just this one assignment x = 2.5;# perfectly legal, right? Wait, no, of course you can't do that. Why would you suggest that as even a possibility? Of course the type (whether inferred or annotated) applies for the entire scope of that variable. > Which means that here: > > x: int = 3 > x = f(x) > > you know x should still an int after these two statements, because the > type hint says so. Without it: > > x = 3 > x = f(x) > > x could be anything. That's not how type checking works. It makes *no difference* whether the type is inferred or hinted. Type hints only exist to cover the cases the type inference engine can't determine, or determine too strictly. See below. In the Dark Ages of type-checking, the compiler was too dumb to work out for itself what the type of variables is, so you have to explicitly declare them all, even the most obvious ones. Given such a declaration: int x = 3; # using C syntax the type checker is smart enough to look at the next line: x = f(x); and complain with a type-error if f() returns (say) a string, or a list. Checking that the types are compatible is the whole point of type checking. Now fast forward to the Enlightenment of type-inference, first used in a programming language in 1973 (so older than half the programmers alive today). That purpose doesn't go away because we're using type inference. With type-inference, the type-checker is smart enough to recognise what type a variable is supposed to be (at least sometimes): x = 3; # of course it's an int, what else could it be? x = f(x); and likewise complain if f(x) returns something other than an int. There's no point in type checking if you don't, you know, actually *check* the types. With type inference, the only reason to declare a variable's type is if the type checker can't infer it from the code, or if it infers the wrong type. (More on this later.) To do otherwise is as pointless and annoying as those comments which merely repeat what the code does: import math # import the math module mylist.append(v) # append v to mylist counter += 1 # add 1 to counter s = s.upper() # convert s to uppercase x: int = 3# assign the int 3 to x Don't be That Guy who writes comments stating the bleeding obvious. There's not always enough information for the type checker to infer the right type. Sometimes the information simply isn't there: x = [] # a list of what? and sometimes you actually did intend what looks like a type-error to the checker: x = 3 # okay, x is intended to be an int x = "spam" # wait, this can't be right In the later case, you can annotate the variable with the most general "any type at all" type: from typing import Any x: Any = 3 # x can be anything, but happens to be an int now x = "spam" # oh that's fine then or you can simply not check that module. (Type checking is optional, not mandatory.) >> A better example would be: >> >> x: int = None >> >> which ought to be read as "x is an int, or None, and it's currently >> None". > > In that case the type hint is lying. "Practicality beats purity." "This type, or None" is such a common pattern that any half-way decent type checker ought to be able to recognise it. You can, of course, explicitly annotate it: x: Optional[int] = None but the type checker should infer that if you assign None to a variable which is declared int, you
RE: Checking whether type is None
While I appreciate that use of "is" in thing is None, I claim this relies on knowledge of how Python works internally, to know that every None actually is the same ID (the same object) - it is singular. That probably works for 0 and 1 also but you probably wouldn't consider testing thing is 1, at least I hope you wouldn't. thing is None looks just as odd to me. Why not thing == None ? That works. --- Joseph S. -Original Message- From: Tobiah Sent: Tuesday, July 24, 2018 3:33 PM To: python-list@python.org Subject: Checking whether type is None Consider: >>> type({}) is dict True >>> type(3) is int True >>> type(None) is None False Obvious I guess, since the type object is not None. So what would I compare type(None) to? >>> type(None) >>> type(None) is NoneType Traceback (most recent call last): File "", line 1, in NameError: name 'NoneType' is not defined I know I ask whether: >>> thing is None but I wanted a generic test. I'm trying to get away from things like: >>> type(thing) is type(None) because of something I read somewhere preferring my original test method. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Guilty as charged
Re: "...while thing == None would work perfectly in almost all cases in practice, it's unidiomatic and suggests the writer isn't quite comfortable with the workings of the language" I admit, I've been a C++ programmer for many years and a Python programmer for only about 5 years. But, I did learn something here. I've read books on Python and somehow still did not know that None is guaranteed to be a singleton in all implementations, and that not only does "thing is None" therefore work (guaranteed), but that that is the Pythonic thing to do. ... Maybe I missed it, but I'll remember it now. --- Joseph S. -- https://mail.python.org/mailman/listinfo/python-list
RE: Why emumerated list is empty on 2nd round of print?
The question "If I do this "aList = enumerate(numList)", isn't it stored permanently in aList now? I see your point to use it directly, but just in case I do need to hang onto it from one loop to another, then how is that done?" Reflects that you are thinking in a C++ kind of way I think. When you declare a variable name and assign to it, in Python what you have done is assigned to the name a reference to the content. It is never true that the content is "in" the variable. The variable does not have storage for what you assign to it. That content is stored somewhere, but the variable just has a reference to it. So, aList = enumerate(numList) creates an iterator, and aList is a reference to that iterator. It is not "in" aLIst. Despite the name, aList does not contain a list. (See above). Now, on to the second part: the problem you showed - that you can only loop through aList:print(i,j) once - is BECAUSE you hung onto it from one loop to another. Once the iterator is exhausted, it's exhausted. Think of another more common iterator you've probably used: file = open("filename.txt") for line in file;print line On EOF the iterator throws an exception (that is expected), the for loop catches the exception and exits. Files can be "rewound" by file.seek(0). But other than that, once you have reached EOF, you have reached EOF. It doesn't automagically rewind. If you do another for line in file; print line it will not print anything. Exactly the same behavior as you are surprised about for the enumerate iterator. I don’t even know if there is a method to reset the enumerate iterator. If there isn't one, then you should not hold the iterator from one loop to the next, you have to make another one. --- Joe S. -Original Message- From: Viet Nguyen Sent: Thursday, September 6, 2018 2:50 PM To: python-list@python.org Subject: Re: Why emumerated list is empty on 2nd round of print? On Thursday, September 6, 2018 at 10:34:19 AM UTC-7, Chris Angelico wrote: > On Fri, Sep 7, 2018 at 3:26 AM, Viet Nguyen via Python-list > wrote: > numList > > [2, 7, 22, 30, 1, 8] > > > aList = enumerate(numList) > > > for i,j in aList:print(i,j) > > > > 0 2 > > 1 7 > > 2 22 > > 3 30 > > 4 1 > > 5 8 > > > for i,j in aList:print(i,j) > > > > > Because it's not an enumerated list, it's an enumerated iterator. > Generally, you'll just use that directly in the loop: > > for i, value in enumerate(numbers): > > There's generally no need to hang onto it from one loop to another. > > ChrisA Thanks ChrisA. If I do this "aList = enumerate(numList)", isn't it stored permanently in aList now? I see your point to use it directly, but just in case I do need to hang onto it from one loop to another, then how is that done? Anyway I think I'm ok and I got what I need for now. -- https://mail.python.org/mailman/listinfo/python-list
RE: [OT] master/slave debate in Python
This really is an amazing discussion. I actually do understand why "master" and "slave" might make people uncomfortable, although the meaning is quite clear. Perhaps we need a currently used alternative: 1) Captain and Private 2) Manager and employee 3) CEO and Peon 4) Controller and Controlled 5) Commander and executer You might not like any of these. That's OK, my goal was just to show that the relationship can be expressed without using outdated terms that some find objectionable. These all have pretty much the same relationship (first one says what to do, second one does it) but I think any one of them feels more "comfortable" now-a-days than Master and Slave. --- Joe S. -Original Message- From: Paul Moore Sent: Wednesday, September 26, 2018 11:41 AM To: Ian Kelly Cc: Python Subject: Re: [OT] master/slave debate in Python On Wed, 26 Sep 2018 at 16:30, Ian Kelly wrote: > Also: a human slave is not "a person being treated like a computer" > and I find it highly disrespectful that you would move to trivialize > slavery like that. I have no idea what it must feel like to be a slave (other than the trite and obvious idea that "it must be awful"). Unfortunately, debates like this do nothing to help me understand or empathise with the people suffering in that way, or people dealing with the aftermath of historical cases. I'm more than happy to ensure that we are not causing pain or being disrespectful of the suffering of others, but rather than simply making the whole issue feel like a censorship debate, I'd rather we were helping people to understand and empathise, so that they would *of their own accord* act in an appropriate way. Self-censorship based on understanding and empathy is far more reasonable than any sort of externally-imposed rules. But discussing what it means to be a slave, or the implications of slavery on our culture(s) is way off-topic for this list, so I'd prefer not to debate it further here. I'm sure anyone interested in understanding more can easily find more appropriate forums to participate in. Paul -- https://mail.python.org/mailman/listinfo/python-list
RE: Python Enhancement Proposal for List methods
I agree with others that I don't see a compelling need to add these to Python, since they are all easy to implement in a few lines. But what I really want to say is that Python tries hard to be easily readable and easily understood, by any reader. List.removeall( ) that does not remove all elements, but all occurrences of a value passed to it, does not seem to me to meet that goal. Even if you implement this as a function I encourage to think of a better name than removeall. --- Joseph S. -Original Message- From: Siva Sukumar Reddy Sent: Sunday, October 21, 2018 8:37 AM To: python-list@python.org; python-id...@python.org Subject: Python Enhancement Proposal for List methods Hey everyone, I am really new to Python contribution community want to propose below methods for List object. Forgive me if this is not the format to send an email. 1. *list.replace( item_to_be_replaced, new_item )*: which replaces all the occurrences of an element in the list instead of writing a new list comprehension in place. 2. *list.replace( item_to_be_replaced, new_item, number_of_occurrences )*: which replaces the occurrences of an element in the list till specific number of occurrences of that element. The number_of_occurrences can defaulted to 0 which will replace all the occurrences in place. 3. *list.removeall( item_to_be_removed )*: which removes all the occurrences of an element in a list in place. What do you think about these features? Are they PEP-able? Did anyone tried to implement these features before? Please let me know. Thank you, Sukumar -- https://mail.python.org/mailman/listinfo/python-list
Re: past exam paper help!
On Saturday, April 9, 2016 at 2:48:16 PM UTC+1, Joseph Caulfield wrote: > how would I model a mug a cylindrical vessel with an open top in python? > thansk :) *as a cylindrical vessel. -- https://mail.python.org/mailman/listinfo/python-list
past exam paper help!
how would I model a mug a cylindrical vessel with an open top in python? thansk :) -- https://mail.python.org/mailman/listinfo/python-list
RE: Recommendation for Object-Oriented systems to study
Hi, Replies inline. -Original Message- From: Python-list [mailto:python-list-bounces+joseph.lee22590=gmail@python.org] On Behalf Of Ankush Thakur Sent: Sunday, May 29, 2016 7:42 AM To: python-list@python.org Subject: Recommendation for Object-Oriented systems to study Hello, I'm a self-taught programmer who has managed to claw his way out of Python basics and even covered the intermediate parts. But I feel I have a ton of theory in my head and would like to see some smallish applications in action. More specifically, I'm looking for Object Oriented designs that will help me cement my knowledge and expose me to best practices that books never cover. I have half a mind to start reading up the Django or Pandas source code, but I don't want to overwhelm myself. Can somebody recommend smaller and simpler projects I can learn from? And if I can pick the brains of the creator, bonus points! Thanks in advance! Ankush JL: One I contribute to that has object-oriented design is NonVisual Desktop access: http://github.com/nvaccess/nvda I'd be happy to let you talk to the led devs of this project if you'd like. Cheers, Joseph -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: Iteration, while loop, and for loop
Hi, Answers inline. -Original Message- From: Python-list [mailto:python-list-bounces+joseph.lee22590=gmail@python.org] On Behalf Of Michael Selik Sent: Tuesday, June 28, 2016 6:16 AM To: Elizabeth Weiss ; python-list@python.org Subject: Re: Iteration, while loop, and for loop On Tue, Jun 28, 2016 at 8:41 AM Elizabeth Weiss wrote: > I do not understand the second code. What is counter? > It looks like someone wanted to make a loop induction variable. https://en.wikipedia.org/wiki/Induction_variable JL: Or access the array item via indexing. > Why do we use this code if we can use the simpler for loop? > You should not. Use the first version, it's much better. Python for-loops are preferable to while-loops. JL: Indexing is useful if one wishes to assign something different to the position represented by container[index]. But if you want a more elegant way to access the actual object in question, then using the first fragment is better (and more readable). For the most part, for loops are better, but there are times when while loops are preferable such as when you don't know the size of the input beforehand. Cheers, Joseph - https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: New to programming and asking about accessibility with jaws screen reader.
Hi, How are you running Python - via Command Prompt, perhaps? It might be better to ask a list like program-l (a dedicated programming list for blind devs). Cheers, Joseph -Original Message- From: Python-list [mailto:python-list-bounces+joseph.lee22590=gmail@python.org] On Behalf Of josphine said Sent: Sunday, July 24, 2016 1:04 PM To: python-list@python.org Subject: New to programming and asking about accessibility with jaws screen reader. Hello, I have downloaded python3.6 and found it is not accessible with jaws 17. So, is there any skripts for jaws for that? Or any suggestions? Every guidance will highly appreciated. Thanks. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Question regarding stdlib distutils strtobool behavior
Hello. It recently came to my attention that the strtobool function in the standard library doesn't return Python native boolean values, but rather returns integer 0 or 1: https://hg.python.org/cpython/file/3.5/Lib/distutils/util.py#l304 I am curious why this is the defined behavior and whether anyone can fill me in regarding this approach. For clarity, I would expect the code to `return True` and `return False` rather than `return 1` and `return 0`. Thanks, Joe -- https://mail.python.org/mailman/listinfo/python-list
Re: Question regarding stdlib distutils strtobool behavior
On Tuesday, August 9, 2016 at 9:34:44 AM UTC-4, Michael Selik wrote: > On Tue, Aug 9, 2016 at 9:26 AM Joseph Bane wrote: > > > Hello. > > > > It recently came to my attention that the strtobool function in the > > standard library doesn't return Python native boolean values, but rather > > returns integer 0 or 1: > > > > https://hg.python.org/cpython/file/3.5/Lib/distutils/util.py#l304 > > > > I am curious why this is the defined behavior and whether anyone can fill > > me in regarding this approach. For clarity, I would expect the code to > > `return True` and `return False` rather than `return 1` and `return 0`. > > > > I'll take a guess: it's probably a(n) historical artifact. Before there > were bools, returning 1 or 0 was the obvious technique. Even after bools > were added to Python 2, returning the literal 1 or 0 was faster than > looking up the names True or False. Now that True and False are keywords, > using the keyword is the obvious solution. (I am sorry if this is a duplicate; the reply didn't seem to make it through earlier...) Thank you for your note. I was thinking it might be just a historical artifact. Do you think this is the type of thing we could propose be changed in the next version of Python? It seems it would be more consistent with the principle of least surprise from the perspective of outsider Python calling code. I would be happy to submit a small patch for this change. As a side note, we discovered this with some code that was checking `if var is True` instead of just `if var`. I know this particular style choice isn't really dictated by the community (as opposed to something like `if var is None` that is), but it seems the latter option is the (generally) preferred approach. Basically, it seemed surprising that the former approach failed in our specific scenario because of how the `is` operator works: >>> 1 == True True >>> 0 == False True >>> 1 is True False >>> 0 is False False I am definitely not arguing that this behavior be changed, but just putting the larger issue into context. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question regarding stdlib distutils strtobool behavior
Thank you for your note. I was thinking it might be just a historical artifact. Do you think this is the type of thing we could propose be changed in the next version of Python? It seems it would be more consistent with the principle of least surprise from the perspective of outsider Python calling code. I would be happy to submit a small patch for this change. As a side note, we discovered this with some code that was checking `if var is True` instead of just `if var`. I know this particular style choice isn't really dictated by the community (as opposed to something like `if var is None` that is), but it seems the latter option is the (generally) preferred approach. Basically, it seemed surprising that the former approach failed in our specific scenario because of how the `is` operator works: >>> 1 == True True >>> 0 == False True >>> 1 is True False >>> 0 is False False I am definitely not arguing that this behavior be changed, but just putting the larger issue into context. On Tue, Aug 9, 2016 at 9:34 AM, Michael Selik wrote: > On Tue, Aug 9, 2016 at 9:26 AM Joseph Bane wrote: > >> Hello. >> >> It recently came to my attention that the strtobool function in the >> standard library doesn't return Python native boolean values, but rather >> returns integer 0 or 1: >> >> https://hg.python.org/cpython/file/3.5/Lib/distutils/util.py#l304 >> >> I am curious why this is the defined behavior and whether anyone can fill >> me in regarding this approach. For clarity, I would expect the code to >> `return True` and `return False` rather than `return 1` and `return 0`. >> > > I'll take a guess: it's probably a(n) historical artifact. Before there > were bools, returning 1 or 0 was the obvious technique. Even after bools > were added to Python 2, returning the literal 1 or 0 was faster than > looking up the names True or False. Now that True and False are keywords, > using the keyword is the obvious solution. > -- https://mail.python.org/mailman/listinfo/python-list
RE: question on the 'calendar' function
It's possible I don't understand the question. The calendar functions are NOT limited to this year or any limited range. Example: import calendar print( calendar.monthcalendar(2022, 12) ) Prints lists of dates in each week of December 2022. It prints: [[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]] So, Dec 1 is a Wednesday; Dec 31 is a Saturday. That's 49 months ahead of this month. Change the year and month to any (valid) number, and it will do what it does. The only caveat is that if the moon's orbit slows down as it gets farther away from the earth and the earth's rotation speed changes, then the calculations done by calendar for leap years may not be correct about the distant future. --- Joseph S. -Original Message- From: o1bigtenor Sent: Tuesday, November 20, 2018 8:37 AM To: python-list@python.org Subject: question on the 'calendar' function Greetings I am in the process of learning my first computer programming language (unless g-code counts and then it is my second - - - grin). It definitely is a big world out there. The calendar function has a lot of versatility and shows care in its development. There is one area where I don't understand if I even could use this function or if I need to look to something(s) else to achieve what I need. For planning I need to be able to easily look backward 6 months and forward at least 12 and better 18 months and would prefer perhaps even a total of 36 (and even 60 might be useful) months of calendar available. It could be useful to see the longer time spans as weeks rather than as days but seeing the larger time frames only as months would enable the planning that I need to do. Do I need to (somehow and I have no idea how) extend the calendar function? Is there some other way of displaying dates/calendars that would allow me to achieve my needed span? TIA -- https://mail.python.org/mailman/listinfo/python-list
RE: the python name
Python was started in the late 1980s by Guido Van Rossum, who (until quite recently) was the Benevolent Dictator for Life of Python. His recent strong support of Type Annotation was what got it passed - and having to fight for it was what convinced him retire from the role of BDFL. Anyway, at the time, he picked the name because he liked Monty Python's Flying Circus. At least, so I have read. If you don't know what Monty Python's Flying Circus was, I recommend looking for YouTube video snippets of it. (You'll know you've found enough when you know the answer to "What's on the telly?" is "There's a penguin on the telly".) The name "Python" may not make sense, but what sense does the name Java make, or even C (unless you know that it was the successor to B), or Haskell or Pascal or even BASIC? Or Caml or Kotlin or Scratch? Or Oberon or R? Or Smalltalk, or SNOBOL? By the way, C was 50 years old in 2018. And C++ is still mostly backward compatible to C. int, float, double and char are (still) not objects. Strings and arrays are not classes (and so do not have iterators, unless you create them). Until C++ 2014, there was no threading library as part of C++ standard. Even though now there is, it's seems to be to be old school. Look at Go (language) to see how concurrency can be built into the language instead of made available for optional use. Joseph S. -Original Message- From: pritanshsahs...@gmail.com Sent: Tuesday, January 1, 2019 1:39 AM To: python-list@python.org Subject: the python name why did you kept this name? i want to know the history behind this and the name of this snake python. -- https://mail.python.org/mailman/listinfo/python-list
RE: Python read text file columnwise
About the original question: If I were you, I would put the 3 numbers into a list (or a tuple, if you don't need to modify them) and put this into a dictionary. The key would be the date & time string. Then, if you need to find a particular entry you can look it up by date and time. But I suspect, since you want column access, you won't need to do that. You can iterate through the entries in the dictionary easily and extract the data from a column, or from all the columns, if that’s what you want. for entry in mydict: value = entry.datalist[0] # I hope I have the syntax correct Now, what you do with value is up to you. I think personally rather than building a list I would make a generator function. A generator uses a "yield" statement to return a value, and it waits in that state. The next time you call it it continues and returns the next value. Kind of useful when the alternative is making and passing around huge lists. --- Joseph S. -Original Message- From: DL Neil Sent: Saturday, January 12, 2019 4:48 PM To: python-list@python.org Subject: Re: Python read text file columnwise On 12/01/19 1:03 PM, Piet van Oostrum wrote: > shibashib...@gmail.com writes: > >> Hello >>> >>> I'm very new in python. I have a file in the format: >>> >>> 2018-05-31 16:00:0028.90 81.77 4.3 >>> 2018-05-31 20:32:0028.17 84.89 4.1 >>> 2018-06-20 04:09:0027.36 88.01 4.8 >>> 2018-06-20 04:15:0027.31 87.09 4.7 >>> 2018-06-28 04.07:0027.87 84.91 5.0 >>> 2018-06-29 00.42:0032.20 104.61 4.8 >> >> I would like to read this file in python column-wise. >> >> I tried this way but not working >>event_list = open('seismicity_R023E.txt',"r") >> info_event = read(event_list,'%s %s %f %f %f %f\n'); To the OP: Python's standard I/O is based around data "streams". Whilst there is a concept of "lines" and thus an end-of-line character, there is not the idea of a record, in the sense of fixed-length fields and thus a defining and distinction between data items based upon position. Accordingly, whilst the formatting specification of strings and floats might work for output, there is no equivalent for accepting input data. Please re-read refs on file, read, readline, etc. > Why would you think that this would work? To the PO: Because in languages/libraries built around fixed-length files this is how one specifies the composition of fields making up a record - a data structure which dates back to FORTRAN and Assembler on mainframes and other magtape-era machines. Whilst fixed-length records/files are, by definition, less flexible than the more free-form data input Python accepts, they are more efficient and faster in situations where the data (format) is entirely consistent - such as the OP is describing! -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
RE: get the terminal's size
Note sure why you couldn't capture $ echo $COLUMNS from a subprocess call. But, how about this (found on the web): from win32api import GetSystemMetrics print "Width =", GetSystemMetrics(0) print "Height =", GetSystemMetrics(1) -Original Message- From: Alex Ternaute Sent: Monday, January 14, 2019 6:58 AM To: python-list@python.org Subject: get the terminal's size Hi there, I want to know the number of columns of the terminal where python2 writes it's outputs. In a terminal, I type $ echo $COLUMNS 100 But in Python, os.getenv("COLUMNS") gets nothing. It gets nothing as well if I try to read the output of "echo $COLUMNS" from a subprocess. I feel that I'm missing something but what ? Looking on the internet for a hint, I see that python3 has an os.get_terminal_size(). Please, is there something similar for python2 ? Cheers -- Alex -- https://mail.python.org/mailman/listinfo/python-list
RE: get the terminal's size
I just tested the fix I proposed, in Python 2.7.13 Code: from win32api import GetSystemMetrics def main(): print "Width =", GetSystemMetrics(0) print "Height =", GetSystemMetrics(1) if __name__ == '__main__': main() Result: Width = 1536 Height = 864 -Original Message- From: Alex Ternaute Sent: Monday, January 14, 2019 6:58 AM To: python-list@python.org Subject: get the terminal's size Hi there, I want to know the number of columns of the terminal where python2 writes it's outputs. In a terminal, I type $ echo $COLUMNS 100 But in Python, os.getenv("COLUMNS") gets nothing. It gets nothing as well if I try to read the output of "echo $COLUMNS" from a subprocess. I feel that I'm missing something but what ? Looking on the internet for a hint, I see that python3 has an os.get_terminal_size(). Please, is there something similar for python2 ? Cheers -- Alex -- https://mail.python.org/mailman/listinfo/python-list
RE: Pythonic Y2K
I'd like to add one more thing to your list of what companies will have to consider: 6) The ability to hire and retain employees who will be happy to program in an obsolete version of Python. A version about which new books will probably not be written. A version which new packages will not support. A version which most other companies will no longer be using, so programming only in Python 2 will place the employee at a disadvantage compared to others who have gained experience with Python 3 if they ever have to change employers. --- Joseph S. -Original Message- From: Chris Angelico Sent: Wednesday, January 16, 2019 2:15 PM To: Python Subject: Re: Pythonic Y2K On Thu, Jan 17, 2019 at 6:04 AM Avi Gross wrote: > > I see messages like the following where someone is still asking how to > do something in some version of python 2.X. > > I recall the days before the year 2000 with the Y2K scare when people > worried that legacy software might stop working or do horrible things > once the clock turned. It may even have been scary enough for some > companies to rewrite key applications and even switch from languages like > COBOL. > > What is happening in the python community, and especially in places > where broken software may be a serious problem? > > I assume versions of python 2.X will continue to be available for some > time but without any further support and without features being back-ported. Commercial support for Python 2 will probably continue for a while, in the same way that support for versions older than 2.7 is still available to Red Hat customers today (if I'm not mistaken). Otherwise, well, the software will continue without updates or security patches until it breaks. Companies will have to weigh up five costs against each other: 1) The cost of the status quo: the risk of critical failures or external attacks against unsupported and unpatched software 2) The cost of migrating to Python 3 3) The cost of migrating to a completely different language 4) The cost of maintaining their own local fork of Python 2 5) The cost of using a supported commercial platform such as RHEL. For most small to medium projects, it's probably going to come down to #1 or #2, where #1 has the laziness bonus. For many larger companies, #1 is an unpayable cost. Everyone has to make that choice, and remember that "cost" doesn't just mean money (for instance, the cost of moving to Linux might be quite considerable for a Windows shop, and even within a Linux ecosystem, switching to Red Hat may have consequences to other programs you might need). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
basic question on how "import" works
[*u23885@c009 3_NeuralNetworks]$ cat foo.py* from __future__ import print_function # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) [u23885@c009 3_NeuralNetworks]$ when the above code is executed, equivalent of *$ python foo.py* the output is as follows: ... Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes. Extracting /tmp/data/train-images-idx3-ubyte.gz Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes. Extracting /tmp/data/train-labels-idx1-ubyte.gz Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes. Extracting /tmp/data/t10k-images-idx3-ubyte.gz Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes. Extracting /tmp/data/t10k-labels-idx1-ubyte.gz ... My questions are: 1. where are the write / print statements that display *Successfully downloaded, extracting ...* 2. I don't see any such files in /tmp/data on my system, why? 3. (this is part of a code for training a neuronal network which works as expected, it's just for my own understanding of how this works -- Thank you) -- Regards, Joseph Pareti - Artificial Intelligence consultant cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
What is your experience porting Python 2.7.x scripts to Python 3.x?
In the company I work for we have a program (free) that runs scripts (that we sell) to test according to particular standards. The program embeds a Python interpreter, and the scripts are Python (which uses functions revealed to Python from within the program). Well, this year must be time ... I've told my manager that we need to change from Python 2.7.13 (the last version to which I updated it) to Python 3.x, whatever the latest is, sometime this year and to get that on our roadmap. I should mention that updating from earlier 2.x versions through 2.7.13 has not caused any errors or problems in our scripts. I guess that is as expected. I've read about the 2to3 utility, and I think our Python code is pretty simple ... I don't expect much beyond changing print to print( ) wherever it occurs (we capture stdout and stderr and emit what we get to a file, that can be very helpful). There are Python function calls to C functions that are callable from Python in our program but that should not be a problem, they are known to be functions. Still, I am concerned; I have never tried using 2to3 so I can't give a justifiable estimate of how long this migration might take. For anyone who has moved a substantial bunch of Python 2 to Python 3, can you please reply with your experience? Did you run into any issues? Did 2to3 do its job well, or did you have to review its output to eliminate some working but silly thing? Thank you, anyone who replies, for replying. --- Joseph S. -- https://mail.python.org/mailman/listinfo/python-list
generate matplotlib images without having access to an X server
The following piece of code is supposed to generate images for plotting: (in *bold*, my added / corrected statements) ... *# JP handle non X server* *import matplotlib* *matplotlib.use('Agg')* # JP import matplotlib.pyplot as plt import numpy as np import tensorflow as tf ... # Generate images from noise, using the generator network. f, a = plt.subplots(4, 10, figsize=(10, 4)) for i in range(10): # Noise input. z = np.random.uniform(-1., 1., size=[4, noise_dim]) g = sess.run([gen_sample], feed_dict={gen_input: z}) g = np.reshape(g, newshape=(4, 28, 28, 1)) # Reverse colours for better display g = -1 * (g - 1) for j in range(4): # Generate image from noise. Extend to 3 channels for matplot figure. img = np.reshape(np.repeat(g[j][:, :, np.newaxis], 3, axis=2), newshape=(28, 28, 3)) a[j][i].imshow(img) *# JP HAck* *# see https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server <https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server>* *# "tuple packing" -> https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences <https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences>* *#f.show()* *#plt.draw()* *#plt.waitforbuttonpress()* *#a.savefig('a.png')* *f.savefig('f.png')* To make it run, I commented out all plt.* statements. Indeed it runs and it produces the 'f.png' picture. However, when the statement: a.savefig('a.png') is also activated (i.e. not commented out), the program ends with the following exception: * a.savefig('a.png')* *AttributeError: 'numpy.ndarray' object has no attribute 'savefig'* Anything I am missing? I am not familiar with the code, just trying to understand it. Thank you -- Regards, Joseph Pareti - Artificial Intelligence consultant cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
RE: Exercize to understand from three numbers which is more high
Explanation: 5 > 4 so it goes into the first if. 5 is not greater than 6, so it does not assign N1 to MaxNum. The elif (because of the lack of indent) applies to the first if, so nothing further is executed. Nothing has been assigned to MaxNum, so that variable does not exist. You're right, it does not work. How about this: Mylist = [ N1, N2, N3] Maxnum = N1 for value in Mylist: if value > Maxnum: Maxnum = value print(Maxnum) Or were lists and for loops excluded from this exercise? --- Joe S. On 1/29/19 9:27 AM, Jack Dangler wrote: > wow. Seems like a lot going on. You have 3 ints and need to determine > the max? Doesn't this work? > > N1, N2, N3 > > if N1>N2 > if N1>N3 > MaxNum = N1 > elif N2>N3 > MaxNum = N2 > elif N1 MaxNum = N3 No. Assuing that you meant to include colons where I think you did, what if (N1, N2, N3) == (5, 4, 6)? -- https://mail.python.org/mailman/listinfo/python-list
RE: Exercize to understand from three numbers which is more high
Yes, that works. Assuming it was correctly formatted when you ran it. The formatting could not possibly be run in a Python interpreter, I think. --- Joseph S. From: Adrian Ordona Sent: Tuesday, January 29, 2019 2:52 PM To: Schachner, Joseph Cc: Dan Sommers <2qdxy4rzwzuui...@potatochowder.com>; python-list@python.org Subject: Re: Exercize to understand from three numbers which is more high i'm also a beginner reading all the replies helps. i was trying the problem myself and came up with the below code with a users input. num1 = int(input("Enter first number: "))num2 = int(input("Enter second number: "))num3 = int(input("Enter third number: "))if num1 > num2 and num1 > num3: print(num1, " is th max number")elif num2 > num1 and num2 > num3: print(num2, " is the max number")else: print(num3, "is the max number") On Tue, Jan 29, 2019 at 1:48 PM Schachner, Joseph mailto:joseph.schach...@teledyne.com>> wrote: Explanation: 5 > 4 so it goes into the first if. 5 is not greater than 6, so it does not assign N1 to MaxNum. The elif (because of the lack of indent) applies to the first if, so nothing further is executed. Nothing has been assigned to MaxNum, so that variable does not exist. You're right, it does not work. How about this: Mylist = [ N1, N2, N3] Maxnum = N1 for value in Mylist: if value > Maxnum: Maxnum = value print(Maxnum) Or were lists and for loops excluded from this exercise? --- Joe S. On 1/29/19 9:27 AM, Jack Dangler wrote: > wow. Seems like a lot going on. You have 3 ints and need to determine > the max? Doesn't this work? > > N1, N2, N3 > > if N1>N2 >if N1>N3 > MaxNum = N1 > elif N2>N3 >MaxNum = N2 > elif N1MaxNum = N3 No. Assuing that you meant to include colons where I think you did, what if (N1, N2, N3) == (5, 4, 6)? -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: The sum of ten numbers inserted from the user
Well of course that doesn't work. For starters, x is an int or a float value. After the loop It holds the 10th value. It might hold 432.7 ... It is not a list. The default start for range is 0. The stop value, as you already know, is not part of the range. So I will use range(10). In the second loop, I think you thought x would be a list and you I'm sure you wanted to do for y in x: but instead you did for y in range(x) and remember x might be a very large number.So the second loop would loop that many times, and each pass it would assign y (which has first value of 0 and last value of whatever x-1 is) to sum. Even though its name is "sum" it is not a sum. After the loop it would hold x-1. You wanted to do sum += y. Or sum = sum + y. I prefer the former, but that could reflect my history as a C and C++ programmer. And then you printed y, but you really want to print sum (assuming that sum was actually the sum). Putting all of the above together, you want to do this: vallist =[] # an empty list, so we can append to it for n in range(10): x = input("Insert a number: ")# get 1 number into x vallist.append(x) # append it to our list # Now vallist holds 10 values sum = 0 # No need to start sum as a float, in Python if we add a float to an integer the result will be float. It doesn't matter in the program if sum is int or float. for y in vallist: sum += y print( "The sum is: ", sum) -Original Message- From: ^Bart Sent: Thursday, February 7, 2019 6:30 AM To: python-list@python.org Subject: The sum of ten numbers inserted from the user I thought something like it but doesn't work... for n in range(1, 11): x = input("Insert a number: ") for y in range(x): sum = y print ("The sum is: ",y) -- https://mail.python.org/mailman/listinfo/python-list
RE: The sum of ten numbers inserted from the user
I just realized that input has changed in Python 3 and I was using Python 2.7.13 with from __future__ import print_function and some others, but not that. In Python 3 the int( ) or float( ) cast is necessary because input( ) does what raw_input( ) did in Python 2; raw_input( ) name is therefore removed. --- Joe S. From: Ian Clark Sent: Thursday, February 7, 2019 1:27 PM To: Schachner, Joseph Cc: python-list@python.org Subject: Re: The sum of ten numbers inserted from the user This is my whack at it, I can't wait to hear about it being the wrong big o notation! numbers=[] while len(numbers) < 10: try: chip = int(input('please enter an integer: ')) except ValueError: print('that is not a number, try again') else: numbers.append(chip) print(sum(numbers)) On Thu, Feb 7, 2019 at 10:23 AM Schachner, Joseph mailto:joseph.schach...@teledyne.com>> wrote: Well of course that doesn't work. For starters, x is an int or a float value. After the loop It holds the 10th value. It might hold 432.7 ... It is not a list. The default start for range is 0. The stop value, as you already know, is not part of the range. So I will use range(10). In the second loop, I think you thought x would be a list and you I'm sure you wanted to do for y in x: but instead you did for y in range(x) and remember x might be a very large number.So the second loop would loop that many times, and each pass it would assign y (which has first value of 0 and last value of whatever x-1 is) to sum. Even though its name is "sum" it is not a sum. After the loop it would hold x-1. You wanted to do sum += y. Or sum = sum + y. I prefer the former, but that could reflect my history as a C and C++ programmer. And then you printed y, but you really want to print sum (assuming that sum was actually the sum). Putting all of the above together, you want to do this: vallist =[] # an empty list, so we can append to it for n in range(10): x = input("Insert a number: ")# get 1 number into x vallist.append(x) # append it to our list # Now vallist holds 10 values sum = 0 # No need to start sum as a float, in Python if we add a float to an integer the result will be float. It doesn't matter in the program if sum is int or float. for y in vallist: sum += y print( "The sum is: ", sum) -Original Message- From: ^Bart mailto:gabriele1nos...@hotmail.com>> Sent: Thursday, February 7, 2019 6:30 AM To: python-list@python.org<mailto:python-list@python.org> Subject: The sum of ten numbers inserted from the user I thought something like it but doesn't work... for n in range(1, 11): x = input("Insert a number: ") for y in range(x): sum = y print ("The sum is: ",y) -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: Why float('Nan') == float('Nan') is False
Because all comparisons with NAN return false, that's the spec. is NAN > 0? False. Is NAN< 0? False. Is NAN == 0? False. Is NAN == ? False. So: Is NAN == NAN? False. And one more: Is NAN < 1.0e18? False This makes some sense because NAN is Not A Number, so any comparison to a number fails. --- Joseph S. -Original Message- From: ast Sent: Wednesday, February 13, 2019 8:21 AM To: python-list@python.org Subject: Why float('Nan') == float('Nan') is False Hello >>> float('Nan') == float('Nan') False Why ? Regards -- https://mail.python.org/mailman/listinfo/python-list
RE: Multiprocessing vs subprocess
Re: " My understanding (so far) is that the tradeoff of using multiprocessing is that my manager script can not exit until all the work processes it starts finish. If one of the worker scripts locks up, this could be problematic. Is there a way to use multiprocessing where processes are launched independent of the parent (manager) process?" I just want to point out that subprocess (which uses the operating system to start another processes, to run whatever you say - doesn't have to be Python running another script, can be an .exe) does not have that restriction. The subprocess call can be blocking (the caller waits), or not. If not the caller can do whatever it wants including decide not to wait forever, and it can even exit. Of course, if one of the processes you launched is locked up that is a problem all by itself, even thought the manager can exit. --- Joseph S. -- https://mail.python.org/mailman/listinfo/python-list
RE: Syntax for one-line "nonymous" functions in "declaration style"
Re: ">> Neither i like how a function magically turns into a generator if the >> keyword `yield` appears somewhere within its definition. > I agree, there should have been a required syntactic element on the "def" > line as well to signal it immediately to the reader. It won't stop me from > using them, though." One way to save people looking at the code from having to look through a function for a yield statement to see if it is a generator would be to add a """doc string""" immediately after the function def, saying that it is a generator and describing what it does. I realize I'm calling on the programmer to address this issue by adding doc strings. Nonetheless adding doc strings is a good habit to get in to. --- Joseph S. -Original Message- From: Ian Kelly Sent: Sunday, March 31, 2019 3:45 PM To: Python Subject: Re: Syntax for one-line "nonymous" functions in "declaration style" On Sun, Mar 31, 2019 at 1:09 PM Alexey Muranov wrote: > > On dim., Mar 31, 2019 at 6:00 PM, python-list-requ...@python.org wrote: > > On Sat, Mar 30, 2019, 5:32 AM Alexey Muranov > > > > wrote: > > > >> > >> On ven., Mar 29, 2019 at 4:51 PM, python-list-requ...@python.org > >> wrote: > >> > > >> > There could perhaps be a special case for lambda expressions > >> such > that, > when they are directly assigned to a variable, > >> Python would use the > variable name as the function name. I > >> expect this could be > accomplished by > a straightforward > >> transformation of the AST, perhaps even by just > replacing > > >> the assignment with a def statement. > >> > >> If this will happen, that is, if in Python assigning a > >> lambda-defined function to a variable will mutate the function's > >> attributes, or else, if is some "random" syntactically-determined > >> cases > >> > >> f = ... > >> > >> will stop being the same as evaluating the right-hand side and > >> assigning the result to "f" variable, it will be a fairly good > >> extra reason for me to go away from Python. > >> > > > > Is there a particular reason you don't like this? It's not too > > different from the syntactic magic Python already employs to support > > the 0-argument form of super(). > > I do not want any magic in a programming language i use, especially if > it breaks simple rules. > > I do not like 0-argument `super()` either, but at least I do not have > to use it. Well, you wouldn't have to use my suggestion either, since it only applies to assignments of the form "f = lambda x: blah". As has already been stated, the preferred way to do this is with a def statement. So just use a def statement for this, and it wouldn't affect you (unless you *really* want the function's name to be "" for some reason). That said, that's also the reason why this probably wouldn't happen. Why go to the trouble of fixing people's lambda assignments for them when the preferred fix would be for them to do it themselves by replacing them with def statements? > Neither i like how a function magically turns into a generator if the > keyword `yield` appears somewhere within its definition. I agree, there should have been a required syntactic element on the "def" line as well to signal it immediately to the reader. It won't stop me from using them, though. -- https://mail.python.org/mailman/listinfo/python-list
RE: scalable bottleneck
If you are using Python 3, range does not create at list, it is a generator. If you're using Python 2.x, use xrange instead of range. xrange is a generator. In Python 3 there is no xrange, they just made range the generator. --- Joseph S. -Original Message- From: Sayth Renshaw Sent: Wednesday, April 3, 2019 5:42 PM To: python-list@python.org Subject: scalable bottleneck In an email, I received this question as part of a newsletter. def fetch_squares ( max_root ): squares = [] for x in range ( max_root ): squares . append (x **2) return squares MAX = 5 for square in fetch_squares (MAX ): do_something_with ( square ) 1) Do you see a memory bottleneck here? If so, what is it? 2) Can you think of a way to fix the memory bottleneck? Want to know if I am trying to solve the correct bottleneck. I am thinking that the bottleneck is to create a list only to iterate the same list you created sort of doubling the time through. Is that the correct problem to solve? If it is then I thought the best way is just to supply the numbers on the fly, a generator. def supply_squares(max_root): for x in max_root: yield x MAX = 5 So then I set up a loop and do whatever is needed. At this time I am creating generator objects. But is this the correct way to go? More of a am I thinking correctly questino. item = 0 while item < MAX: print(supply_squares(item)) item += 1 Thanks Sayth -- https://mail.python.org/mailman/listinfo/python-list
RE: Design a function that finds all positive numbers
I'm willing to bet "sorted" is a sort of the list of strings. The result is certainly not what I'd expect if the list contained numeric values. So: make a new list that holds the values in your "Array" (which is probably a list) converted to numbers. Sort the new list. That should give you're a numerically sorted result. After that, you can look through the negative numbers on the new list (they will all be before any positive value), and try to find the positive value in the new list. Output the positive value. Warning: keep track of the values you have already checked, and don't output the same value twice. You the values you've already looked for into a set (sets do not ever store duplicate values, not important in this case) and check if a subsequent value is already in the set. I say this because there are three -2 values, and two 2 values, but I think you only want to print 2 once. --- Joseph S. -Original Message- From: Ben Bacarisse Sent: Tuesday, April 9, 2019 7:33 AM To: python-list@python.org Subject: Re: Design a function that finds all positive numbers Ranjith Bantu writes: > A numeric array of length 'N' is given. you need to design a function > that finds all positive numbers in the array that have their opposites > in it swell. give the approach for solving the optimal average or best > case performance. answer will be your obsolute. > Array: -7,4,-3, 2, 2, -8, -2, 3, 3, 7, -2, 3, -2 > sorted: -2, -2, -2 ,2 ,2, -3, 3, 3, 4, -7, 7, -8? > > can I solve any problems like this by learning python? You need to learn how to solve problems as well as learning Python -- they go hand in hand -- but Python is a good language to get started with. > if anybody > knows this answer or any mistakes in this question, please explain to > me in detail? That would require quite a long essay! As to the question, it's a bit odd to talk of opposites, but it's not ambiguous. More problematic is what to do with duplicates. The question should be worded so that it's either clear what is wanted, or so that it is clear that you should decide what to do. -- Ben. -- https://mail.python.org/mailman/listinfo/python-list
RE: Python-list Digest, Vol 189, Issue 17
Please see https://docs.python.org/2/library/colorsys.html And follow the links in there, read the FAQ. You'll find that python represents RGB values in three numeric values. Very simple. I believe scale is 0.0 to 1.0. --- Joseph S. -Original Message- From: Python-list On Behalf Of python-list-requ...@python.org Sent: Monday, June 17, 2019 10:28 AM To: python-list@python.org Subject: Python-list Digest, Vol 189, Issue 17 ---External Email--- Send Python-list mailing list submissions to python-list@python.org To subscribe or unsubscribe via the World Wide Web, visit https://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-requ...@python.org You can reach the person managing the list at python-list-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." -- https://mail.python.org/mailman/listinfo/python-list
issue with regular expressions
the following code ends in an exception: import re pattern = 'Sottoscrizione unica soluzione' mylines = []# Declare an empty list. with open ('tmp.txt', 'rt') as myfile: # Open tmp.txt for reading text. for myline in myfile: # For each line in the file, mylines.append(myline.rstrip('\n')) # strip newline and add to list. for element in mylines: # For each element in the list, #print(element) match = re.search(pattern, element) s = match.start() e = match.end() print(element[s:e]) F:\October20-2019-RECOVERY\Unicredit_recovery\tmp_re_search>c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\python.exe search_0.py Traceback (most recent call last): File "search_0.py", line 10, in s = match.start() AttributeError: 'NoneType' object has no attribute 'start' any help? Thanks -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
Re: issue with regular expressions
Ok, thanks. It works for me. regards, Am Di., 22. Okt. 2019 um 11:29 Uhr schrieb Matt Wheeler : > > > On Tue, 22 Oct 2019, 09:44 joseph pareti, wrote: > >> the following code ends in an exception: >> >> import re >> pattern = 'Sottoscrizione unica soluzione' >> mylines = []# Declare an empty list. > > with open ('tmp.txt', 'rt') as myfile: # Open tmp.txt for reading >> text. >> for myline in myfile: # For each line in the file, >> mylines.append(myline.rstrip('\n')) # strip newline and add to >> list. >> for element in mylines: # For each element in the >> list, >> #print(element) >>match = re.search(pattern, element) >>s = match.start() >>e = match.end() >>print(element[s:e]) >> >> >> >> F:\October20-2019-RECOVERY\Unicredit_recovery\tmp_re_search>c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\python.exe >> search_0.py >> Traceback (most recent call last): >> File "search_0.py", line 10, in >> s = match.start() >> AttributeError: 'NoneType' object has no attribute 'start' >> >> any help? Thanks >> > > Check over the docs for re.match again, you'll see it returns either a > Match object (which is always truthy), or None. > > So a simple solution is to wrap your attempts to use the Match object in > > ``` > if match: > ... > ``` > >> -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list
TypeError: unhashable type: 'list'
I am experimnenting with this (reproducer) code: pattern_eur= ['Total amount'] mylines = []# Declare an empty list. with open ('tmp0.txt', 'rt') as myfile: # Open tmp.txt for reading text. for myline in myfile: # For each line in the file, mylines.append(myline.rstrip('\n')) # strip newline and add to list. for element in mylines: # For each element in the list, match_C = re.search(pattern_eur, element) if match_C: element = element + 2 print(element) -- the input file being: $ cat tmp0.txt line 0 line 1 Total amount 5.00 linex line z line c Total amount 43598 line line m Total amount 32000 line end -1 line end 0 line end 1 line end 2 -- My intent is to locate the line containing "Total amount", skip the next line, then print the eur value. The program terminates as follows: Traceback (most recent call last): File "search_then_advance.py", line 8, in match_C = re.search(pattern_eur, element) File "c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\lib\re.py", line 183, in search return _compile(pattern, flags).search(string) File "c:\Users\joepareti\Miniconda3\pkgs\python-3.7.1-h8c8aaf0_6\lib\re.py", line 276, in _compile return _cache[type(pattern), pattern, flags] TypeError: unhashable type: 'list' Thanks for any insigths -- -- Regards, Joseph Pareti - Artificial Intelligence consultant Joseph Pareti's AI Consulting Services https://www.joepareti54-ai.com/ cell +49 1520 1600 209 cell +39 339 797 0644 -- https://mail.python.org/mailman/listinfo/python-list