Resources
As requested: www.guardyannet.com.br www.tra.web.pt http://www.cita.es/veracidad/expolingua/Brasil http://www.collegeboard.com/csearch/majors_careers/profiles/careers/105464.html http://www.guardyannet.com.br/ http://www.guiagratis.com.br/ http://www.clubedoprofessor.com.br/traduz/ http://poloclup.linguateca.pt/artur/ http://baixaki.ig.com.br/categorias/cat18_1.htm http://www.jucergs.rs.gov.br/sitejucergs/Site/juc-trd_1.htm http://www.abrates.com.br/ http://www.servicosgratis.com.br/categoria.php?id=30 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is python source code not available on github?
http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 On Sat, Jun 23, 2012 at 9:16 PM, gmspro wrote: > Why is python source code not available on github? > > Make it available on github so that we can git clone and work on source > code. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- George R. C. Silva Desenvolvimento em GIS http://geoprocessamento.net http://blog.geoprocessamento.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Geodetic functions library GeoDLL 32 Bit and 64 Bit
Hi Fred. Do you know about proj4? proj4 is opensource library that does the coordinate transformations side of geospatial for many many already tested projects. Does your libraries do anything that proj4 does not? On Wed, Aug 29, 2012 at 2:51 AM, Fred wrote: > Hi developers, > > who develops programs with geodetic functionality like world-wide > coordinate transformations or distance calculations, can use geodetic > functions of my GeoDLL. The Dynamic Link Library can easily be used with > most of the modern programming languages like C, C++, C#, Basic, Delphi, > Pascal, Java, Fortran, Visual-Objects and others to add geodetic > functionality to own applications. For many programming languages > appropriate Interfaces are available. > > GeoDLL supports 2D and 3D coordinate transformation, geodetic datum shift > and reference system convertion with Helmert, Molodenski and NTv2 (e.g. > BeTA2007, AT_GIS_GRID, CHENYX06), meridian strip changing, user defined > coordinate and reference systems, distance calculation, Digital Elevation > Model, INSPIRE support, Direct / Inverse Solutions and a lot of other > geodetic functions. > > The DLL is very fast, save and compact because of forceful development in > C++ with Microsoft Visual Studio 2010. The geodetic functions of the > current version 12.35 are available in 32bit and 64bit architecture. All > functions are prepared for multithreading and server operating. > > You find a free downloadable test version on > http://www.killetsoft.de/p_gdlb_e.htm > Notes about the NTv2 support can be found here: > http://www.killetsoft.de/p_gdln_e.htm > Report on the quality of the coordinate transformations: > http://www.killetsoft.de/t_1005_e.htm > > Fred > Email: info_at_killetsoft.de > -- > http://mail.python.org/mailman/listinfo/python-list > -- George R. C. Silva Desenvolvimento em GIS http://geoprocessamento.net http://blog.geoprocessamento.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A sad day for the scientific Python community. John Hunter, creator of matplotlib: 1968-2012.
career a few years ago for a job in industry, he remained > engaged enough that as of today, he is still the top committer to > matplotlib; this is the git shortlog of those with more than 1000 > commits to the project: > > 2145 John Hunter > 2130 Michael Droettboom > 1060 Eric Firing > > All of this was done by a man who had three children to raise and who > still always found the time to help those on the mailing lists, solve > difficult technical problems in matplotlib, teach courses and seminars > about scientific Python, and more recently help create the NumFOCUS > foundation project. Despite the challenges that raising three > children in an expensive city like Chicago presented, he never once > wavered from his commitment to open source. But unfortunately now he > is not here anymore to continue providing for their well-being, and I > hope that all those who have so far benefited from his generosity, > will thank this wonderful man who always gave far more than he > received. Thanks to the rapid action of Travis Oliphant, the NumFOCUS > foundation is now acting as an escrow agent to accept donations that > will go into a fund to support the education and care of his wonderful > girls Rahel, Ava and Clara. > > If you have benefited from John's many contributions, please say > thanks in the way that would matter most to him, by helping Miriam > continue the task of caring for and educating Rahel, Ava and Clara. > You will find all the information necessary to make a donation here: > > http://numfocus.org/johnhunter > > Remember that even a small donation helps! If all those who ever use > matplotlib give just a little bit, in the long run I am sure that we > can make a difference. > > If you are a company that benefits in a serious way from matplotlib, > remember that John was a staunch advocate of keeping all scientific > Python projects under the BSD license so that commercial users could > benefit from them without worry. Please say thanks to John in a way > commensurate with your resources (and check how much a yearly matlab > license would cost you in case you have any doubts about the value you > are getting...). > > John's family is planning a private burial in Tennessee, but (most > likely in September) there will also be a memorial service in Chicago > that friends and members of the community can attend. We don't have > the final scheduling details at this point, but I will post them once > we know. > > I would like to again express my gratitude to Travis Oliphant for > moving quickly with the setup of the donation support, and to Eric > Jones (the founder of Enthought and another one of the central figures > in our community) who immediately upon learning of John's plight > contributed resources to support the family with everyday logistics > while John was facing treatment as well as my travel to Chicago to > assist. This kind of immediate urge to come to the help of others > that Eric and Travis displayed is a hallmark of our community. > > Before closing, I want to take a moment to publicly thank the > incredible staff of the University of Chicago medical center. The > last two weeks were an intense and brutal ordeal for John and his > loved ones, but the hospital staff offered a sometimes hard to > believe, unending supply of generosity, care and humanity in addition > to their technical competence. The latter is something we expect from > a first-rate hospital at a top university, where the attending > physicians can be world-renowned specialists in their field. But the > former is often forgotten in a world often ruled by a combination of > science and concerns about regulations and liability. Instead, we > found generous and tireless staff who did everything in their power to > ease the pain, always putting our well being ahead of any mindless > adherence to protocol, patiently tending to every need we had and > working far beyond their stated responsibilities to support us. To > name only one person (and many others are equally deserving), I want > to thank Dr. Carla Moreira, chief surgical resident, who spent the > last few hours of John's life with us despite having just completed a > solid night shift of surgical work. Instead of resting she came to > the ICU and worked to ensure that those last hours were as comfortable > as possible for John; her generous actions helped us through a very > difficult moment. > > It is now time to close this already too long message... > > John, thanks for everything you gave all of us, and for the privilege > of knowing you. > > Fernando. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- George R. C. Silva Desenvolvimento em GIS http://geoprocessamento.net http://blog.geoprocessamento.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with Python/ArcPy
even better gis.stackexchange.com On Wed, Dec 12, 2012 at 9:42 PM, Xavier Ho wrote: > You can always try http://stackoverflow.com/search?q=ArcPY, or post your > question there. > > Cheers, > Xav > > > > On 13 December 2012 08:07, Michelle Couden wrote: > >> Does anyone know of a website or forum where there is help for ArcPY >> (Python) programmers? ESRI’s (GIS) resource center Forums are very busy and >> my questions go days without an answer. Any suggestions would be great. >> Thanks!! >> >> ** ** >> >> ** ** >> >> ** ** >> >> *Michelle Couden* >> >> TPP-T GIS Cartographer >> >> Certified GIS Analyst >> >> (512) 486-5136 >> >> Fax (512)486-5153 >> >> michelle.cou...@txdot.gov >> >> ** ** >> >> Mind the road, not your business. >> >> [image: Logo] >> >> ** ** >> >> ** ** >> >> ** ** >> >> ** ** >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- George R. C. Silva Desenvolvimento em GIS http://geoprocessamento.net http://blog.geoprocessamento.net <>-- http://mail.python.org/mailman/listinfo/python-list
Problem in Dictionaries
I´m with problem in Dictionaries ! I would like to know if the dictionary can sort with a function that i give to then! Because i need to have a dictionary sort by key ! For exemple : dict = {} dict[50] = "fifty" dict[129] = "a hundred twenty nine" print dict {129: "a hundred twenty nine", 50: "fifty"} But i need dict sort : { 50: "fifty", 129: "a hundred twenty nine"} How can i do this ? Thanks, Glauco Buzini da Costa Silva -- http://mail.python.org/mailman/listinfo/python-list
Lambda: the Ultimate Design Flaw
Shriram Krishnamurthi has just announced the following elsewhere; it might be of interest to c.l.s, c.l.f, and c.l.p: http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html The Fate Of LAMBDA in PLT Scheme v300 or Lambda the Ultimate Design Flaw About 30 years ago, Scheme had FILTER and MAP courtesy of Lisp hackers who missed them from their past experience. To this collection, Scheme added a lexically-scoped, properly-functioning LAMBDA. But, despite of the PR value of anything with Guy Steele's name associated with it, we think these features should be cut from PLT Scheme v300. We think dropping FILTER and MAP is pretty uncontroversial; (filter P S) is almost always written clearer as a DO loop (plus the LAMBDA is slower than the loop). Even more so for (map F S). In all cases, writing the equivalent imperative program is clearly beneficial. Why drop LAMBDA? Most Scheme users are unfamiliar with Alonzo Church (indeed, they don't even know that he was related to Guy Steele), so the name is confusing; also, there is a widespread misunderstanding that LAMBDA can do things that a nested function can't -- we still recall Dan Friedman's Aha! after we showed him that there was no difference! (However, he appears to have since lapsed in his ways.) Even with a better name, we think having the two choices side-by-side just requires programmers to think about their program; not having the choice streamlines the thought process, and Scheme is designed from the ground up to, as much as possible, keep programmers from thinking at all. So now FOLD. This is actually the one we've always hated most, because, apart from a few examples involving + or *, almost every time we see a FOLD call with a non-trivial function argument, we have to grab pen and paper and imagine the *result* of a function flowing back in as the *argument* to a function. Plus, there are *more* arguments coming in on the side! This is all absurdly complicated. Because almost all the examples of FOLD we found in practice could be written as a simple loop with an accumulator, this style should be preferred, perhaps with us providing a simple helper function to abstract away the boilerplate code. At any rate, FOLD must fold. --The PLT Scheme Team -- http://mail.python.org/mailman/listinfo/python-list
problem with py2exe !
Hi, I´m with problem to create a executable program in python. I´m using py2exe but i don´t know if it´s right. My setup.py: from distutils.core import setupimport py2exefrom glob import glob setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "2.0", description = "programa InVesalius", name = "InVesalius", # targets to build console = ["C:\\promed2.0\\python\\MyMainModule.py"], data_files=[("icons", glob("C:\\promed2.0\\icons\\*.*")), ("docs",glob("C:\\promed2.0\\docs\\*.*")), ("config", ["C:\\promed2.0\\setup.cfg"]) ],packages = ['vtk-windows', 'vtk-windows.vtk', 'vtk-windows.vtk.gtk', 'vtk-windows.vtk.qt', 'vtk-windows.vtk.tk', 'vtk-windows.vtk.util', 'vtk-windows.vtk.wx', 'vtk-windows.vtk.test'], ) When i run in prompt "python setup.py py2exe", appear in the end this: ### The following modules appear to be missing[ '_imaging_gif','libVTKCommonPython', 'libVTKContribPython', 'libVTKGraphicsPython', 'libVTKImagingPython', 'libVTKPatentedPython', libvtkCommonPython', 'libvtkFilteringPython', 'libvtkGraphicsPython', 'libvtkHybridPython', 'libvtkIOPython', 'libvtkImagingPython', 'libvtkParallelPython', 'libvtkPatentedPython', 'libvtkRenderingPython', 'numarray.array', 'numarray.dot', 'numarray.fromfile', 'numarray.size', 'numarray.zeros', 'vtk.vtkActor2D', 'vtk.vtkDCMParser', 'vtk.vtkImageClip', 'vtk.vtkImageFlip', 'vtk.vtkImageImport', 'vtk.vtkImageMagnify', 'vtk.vtkImageMapper', 'vtk.vtkImagePermute', 'vtk.vtkImageReader', 'vtk.vtkImageResample', 'vtk.vtkImageReslice', 'vtk.vtkImageShiftScale', 'vtk.vtkImageThreshold', 'vtk.vtkImageViewer', 'vtk.vtkImageWriter', 'vtk.vtkRenderWindow', 'vtk.vtkRenderer', 'vtk.vtkTextMapper', 'vtk.vtkTextProperty', 'vtk.vtkTransform'] ### My PYTHONPATH = C:\Python23;C:\promed2.0\vtk-windows;C:\promed2.0\python My dir: ## promed2.0/ setup.cfg setup.py icons/ docs/ python/ MyMainModule.py vtk-window/ vtkpython.py vtkpythontk.py vtk.pth vtkCommon.dll vtkCommonPython.dll vtkCommonTCL.dll ... vtk/ ### OS: win 2K Python ver: 2.3.5py2exe ver: 0.5.4 How can i solve this problem? Thanks Glauco No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.9.11 - Release Date: 14/4/2005 -- http://mail.python.org/mailman/listinfo/python-list
Problem using py2exe
Hi, I´m with problem to create a executable program in python. I´m using py2exe but i don´t know if it´s right. My setup.py: from distutils.core import setupimport py2exefrom glob import glob setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "2.0", description = "programa InVesalius", name = "InVesalius", # targets to build console = ["C:\\promed2.0\\python\\MyMainModule.py"], data_files=[("icons", glob("C:\\promed2.0\\icons\\*.*")), ("docs",glob("C:\\promed2.0\\docs\\*.*")), ("config", ["C:\\promed2.0\\setup.cfg"]) ],packages = ['vtk-windows', 'vtk-windows.vtk', 'vtk-windows.vtk.gtk', 'vtk-windows.vtk.qt', 'vtk-windows.vtk.tk', 'vtk-windows.vtk.util', 'vtk-windows.vtk.wx', 'vtk-windows.vtk.test'], ) When i run in prompt "python setup.py py2exe", appear in the end this: ### The following modules appear to be missing[ '_imaging_gif','libVTKCommonPython', 'libVTKContribPython', 'libVTKGraphicsPython', 'libVTKImagingPython', 'libVTKPatentedPython', libvtkCommonPython', 'libvtkFilteringPython', 'libvtkGraphicsPython', 'libvtkHybridPython', 'libvtkIOPython', 'libvtkImagingPython', 'libvtkParallelPython', 'libvtkPatentedPython', 'libvtkRenderingPython', 'numarray.array', 'numarray.dot', 'numarray.fromfile', 'numarray.size', 'numarray.zeros', 'vtk.vtkActor2D', 'vtk.vtkDCMParser', 'vtk.vtkImageClip', 'vtk.vtkImageFlip', 'vtk.vtkImageImport', 'vtk.vtkImageMagnify', 'vtk.vtkImageMapper', 'vtk.vtkImagePermute', 'vtk.vtkImageReader', 'vtk.vtkImageResample', 'vtk.vtkImageReslice', 'vtk.vtkImageShiftScale', 'vtk.vtkImageThreshold', 'vtk.vtkImageViewer', 'vtk.vtkImageWriter', 'vtk.vtkRenderWindow', 'vtk.vtkRenderer', 'vtk.vtkTextMapper', 'vtk.vtkTextProperty', 'vtk.vtkTransform'] ### My PYTHONPATH = C:\Python23;C:\promed2.0\vtk-windows;C:\promed2.0\python My dir: ## promed2.0/ setup.cfg setup.py icons/ docs/ python/ MyMainModule.py vtk-window/ vtkpython.py vtkpythontk.py vtk.pth vtkCommon.dll vtkCommonPython.dll vtkCommonTCL.dll ... vtk/ ### OS: win 2K Python ver: 2.3.5py2exe ver: 0.5.4 How can i solve this problem? Thanks Glauco No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.9.16 - Release Date: 18/4/2005 -- http://mail.python.org/mailman/listinfo/python-list
How can i solve this problem with py2exe ?
Hi, I´m with problem to create a executable program in python. I´m using py2exe but i don´t know if it´s right. When i run in prompt "python setup.py py2exe", appear in the end this: ### The following modules appear to be missing[ '_imaging_gif','libVTKCommonPython', 'libVTKContribPython', 'libVTKGraphicsPython', 'libVTKImagingPython', 'libVTKPatentedPython', libvtkCommonPython', 'libvtkFilteringPython', 'libvtkGraphicsPython', 'libvtkHybridPython', 'libvtkIOPython', 'libvtkImagingPython', 'libvtkParallelPython', 'libvtkPatentedPython', 'libvtkRenderingPython', 'numarray.array', 'numarray.dot', 'numarray.fromfile', 'numarray.size', 'numarray.zeros', 'vtk.vtkActor2D', 'vtk.vtkDCMParser', 'vtk.vtkImageClip', 'vtk.vtkImageFlip', 'vtk.vtkImageImport', 'vtk.vtkImageMagnify', 'vtk.vtkImageMapper', 'vtk.vtkImagePermute', 'vtk.vtkImageReader', 'vtk.vtkImageResample', 'vtk.vtkImageReslice', 'vtk.vtkImageShiftScale', 'vtk.vtkImageThreshold', 'vtk.vtkImageViewer', 'vtk.vtkImageWriter', 'vtk.vtkRenderWindow', 'vtk.vtkRenderer', 'vtk.vtkTextMapper', 'vtk.vtkTextProperty', 'vtk.vtkTransform'] ### How can i solve this problem? My setup.py: from distutils.core import setupimport py2exefrom glob import glob setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "2.0", description = "programa InVesalius", name = "InVesalius", # targets to build console = ["C:\\promed2.0\\python\\MyMainModule.py"], data_files=[("icons", glob("C:\\promed2.0\\icons\\*.*")), ("docs",glob("C:\\promed2.0\\docs\\*.*")), ("config", ["C:\\promed2.0\\setup.cfg"]) ],packages = ['vtk-windows', 'vtk-windows.vtk', 'vtk-windows.vtk.gtk', 'vtk-windows.vtk.qt', 'vtk-windows.vtk.tk', 'vtk-windows.vtk.util', 'vtk-windows.vtk.wx', 'vtk-windows.vtk.test'], ) My PYTHONPATH = C:\Python23;C:\promed2.0\vtk-windows;C:\promed2.0\python My dir: ## promed2.0/ setup.cfg setup.py icons/ docs/ python/ MyMainModule.py vtk-window/ vtkpython.py vtkpythontk.py vtk.pth vtkCommon.dll vtkCommonPython.dll vtkCommonTCL.dll ... vtk/ ### OS: win 2K Python ver: 2.3.5py2exe ver: 0.5.4 Thanks Glauco No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.10.3 - Release Date: 25/4/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: If you were starting a project with XML datasource using python
As people already said, don't use XML for persistence. Read it, parse it, and persist it in another format. databases are quite good for that. even sqlite3 will outperfom any few MB xml files. On Mon, Jan 5, 2015 at 11:55 PM, Chris Angelico wrote: > On Tue, Jan 6, 2015 at 11:49 AM, Dennis Lee Bieber > wrote: > >>So you would convert it to json so it can then be stored? > >> > > NO! > > > > JSON and XML, in my mind, are equivalents -- (human-readable) > notations > > for transferring data between applications. JSON may just have fewer > > "options" for how to notate basic data. > > JSON corresponds much more closely to Python data types, but > converting from one to the other can't improve matters any. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -- George R. C. Silva SIGMA Consultoria http://www.consultoriasigma.com.br/ -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP8 and 4 spaces
Isn't this an old discussion? Just configure your editor properly. In my team we all use spaces, but I'll be damned if I need to type 12 spaces in a row. I'll just configured Sublime to insert spaces instead of tabs. Problem solved. On Fri, Jul 4, 2014 at 12:12 PM, Mark Lawrence wrote: > On 04/07/2014 14:59, Mihamina Rakotomandimby wrote: > >> On 07/04/2014 04:47 PM, Roy Smith wrote: >> >>> As long as*all* your tools follow that convention, everything >>>> >is fine. The problems arise when you mix in tools that use >>>> >different conventions. >>>> >>> The problem is, tools always get mixed. I use emacs. The next guy uses >>> vi. Somebody else uses Sublime. The list goes on and on. You will >>> never control what tools other people use. >>> >> >> This may be the subject of a PEP: "What tool will you use" :-) >> > > I'll nominate our resident unicode expert to write the PEP as he's also an > expert on tools. Consider his superb use of the greatly loved google > groups for example. Sadly I understand that he has yet to master the > intricacies of pip, but I'm sure that'll come with practice, or has he > given up? > > > -- > My fellow Pythonistas, ask not what our language can do for you, ask what > you can do for our language. > > Mark Lawrence > > --- > This email is free from viruses and malware because avast! Antivirus > protection is active. > http://www.avast.com > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- George R. C. Silva SIGMA Consultoria http://www.consultoriasigma.com.br/ -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP8 and 4 spaces
> I assume any sane editor has similar functionality. I see my coworkers > using vim, sublime, eclipse, and X-code. They all appear to do these > things, and I would thus classify any of them as sane editors. I'm sure > there are others. If the tool you're (in the generic sense of "you") > using doesn't have this type of basic language support, you should > reconsider your choice of tool Could not agree more :D -- https://mail.python.org/mailman/listinfo/python-list
Re: Topological Overlap
Homework? You need to give us a start, sample of the data and an actual question. I don't think many people will help you do your homework for you. On Sat, Aug 16, 2014 at 7:32 AM, lavanya addepalli wrote: > Hello > > I have a file with network node pairs and weights as time difference > I am trying to find the topological overlap of that data > > I have been searching for any sample in python but i dont seem to find > any. > > Any suggestion in start with are appreciated > > > Thanks > Lav > > -- > https://mail.python.org/mailman/listinfo/python-list > > -- George R. C. Silva SIGMA Consultoria http://www.consultoriasigma.com.br/ -- https://mail.python.org/mailman/listinfo/python-list
Re: PyCharm refactoring tool?
It's pretty useful. I use it for some time now and I very much like it. There are some things that might not be available on Python because of it's duck typing behavior (Pycharm perhaps can't confirm that the type is boolean to suggest it's inversion, for instance). The most powerful for me are the rename refactor and extract. Works like charm (no pun intended). On Mon, Sep 15, 2014 at 4:44 PM, Skip Montanaro wrote: > I started up an instance of PyCharm last Friday. It's mostly just been > sitting there like a bump on a log. I set things up to use Emacs as my > editor. It seems most of its functionality won't be all that useful. Most > of my work is on libraries/platforms - stuff which is not runnable in > isolation, so the Run menu doesn't look all that useful. I have git, etc > integrated into my Emacs environment, so don't need the VCS menu. Most > everything else looks fairly genertic. > > Except the Refactor menu. Before I try to do much/anything with it, I > thought I would solicit feedback on its capability. Does it work as > intended? I read through the PyCharm help sections on refactoring. It seems > to describe a number of code refactorings which aren't available for Python > code. For example, I don't see an "invert boolean" refactoring. > > How useful is PyCharm's refactoring subsystem? > > Thx, > > Skip > > > -- > https://mail.python.org/mailman/listinfo/python-list > > -- George R. C. Silva SIGMA Consultoria http://www.consultoriasigma.com.br/ -- https://mail.python.org/mailman/listinfo/python-list
transfer rate limiting in socket.py
Hi folks, I have a need in a network data distribution application to send out data to folks who want it using the protocol of their choice. I´d like it to support a variety of protocols and I don´t want to implement any of them :-) http, ftp (via ftplib) , https (dunno how yet), ssl, ssh, sftp (via paramiko) The thing is... I want rate-limiting so that in the case of a failure of a single client I don´t penalize the other clients, or if my server (which is acting as a client pushing to remote servers.) goes down, it doesn´t saturate the link when it comes back. So I want to have all the protocols limit the number of bytes they send per second. It looks like the easiest way to do this is to dive into socket.py... and look! it says: # Wrapper module for _socket, providing some additional facilities # implemented in Python. note the ´additional facilities implemented in python´ ... so we just add logic to: -- add a ´maxrate´ argument to the constructor and/or an attribute to modify the setting... -- tally bytes, and time, and know when we are going ´too fast´ -- when too fast.. in the ´flush´ routine, in the synchronous case, sleep for the correct time to come back under budget. in the async, return without writing. -- do something similar for reading. Anybody think this would be fun? -- http://mail.python.org/mailman/listinfo/python-list
Re: transfer rate limiting in socket.py
I looked at twisted briefly. It looks like it is server oriented. Does it work in for clients initiating connections? Jean-Paul Calderone wrote: > On 16 Jun 2006 13:53:48 -0700, Peter Silva <[EMAIL PROTECTED]> wrote: > >Hi folks, > > > >I have a need in a network data distribution application to send out > >data to folks who want it using the protocol of their choice. I´d > >like it to support a variety of protocols and I don´t want to > >implement any of them :-) > >http, ftp (via ftplib) , https (dunno how yet), ssl, ssh, sftp (via > >paramiko) > > > >The thing is... I want rate-limiting so that in the case of a failure > >of a single client > >I don´t penalize the other clients, or if my server (which is acting > >as a client pushing to remote servers.) goes down, it doesn´t saturate > >the link when it comes back. > > > >So I want to have all the protocols limit the number of bytes they send > >per second. > >It looks like the easiest way to do this is to dive into socket.py... > >and look! it says: > > > ># Wrapper module for _socket, providing some additional facilities > ># implemented in Python. > > > >note the ´additional facilities implemented in python´ ... > > > >so we just add logic to: > >-- add a ´maxrate´ argument to the constructor and/or an attribute to > >modify the setting... > >-- tally bytes, and time, and know when we are going ´too fast´ > >-- when too fast.. in the ´flush´ routine, in the synchronous case, > >sleep for the correct time to come back under budget. in the async, > >return without writing. > > -- do something similar for reading. > > > > Anybody think this would be fun? > > Use Twisted instead. It supports every protocol you mentioned, and > rate limiting too. > > Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: transfer rate limiting in socket.py
Cool! Will check it out... Alex Martelli wrote: > Peter Silva <[EMAIL PROTECTED]> wrote: > > > I looked at twisted briefly. It looks like it is server oriented. > > Does it work in for clients initiating connections? > > Twisted supports clients, servers, and "middleware" (proxies etc) in > equally wonderful and powerful ways. > > > Alex -- http://mail.python.org/mailman/listinfo/python-list
problem in the compiler ?
when i creat a RadioButton and put a command = self.Function , this function is called in the creation of RadioButton. It´s right this or it´s wrong ? Thank you Glauco No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.1 - Release Date: 2/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in the compiler ?
I´m sorry if i don´t write correct. My code is like this: MyClass() class MyClass: def __init__(self): btn = RadioButton(command=self.Function) def Function(self): print "Enter in the function" python : 2.3.5 os: win 2K When a do this, the function 'Function' is call. And i don´t want this. What´s wrong ? Thank you Glauco - Original Message - From: "Delaney, Timothy C (Timothy)" <[EMAIL PROTECTED]> To: "Glauco Silva" <[EMAIL PROTECTED]>; Sent: Monday, May 02, 2005 8:50 PM Subject: RE: problem in the compiler ? Glauco Silva wrote: > when i creat a RadioButton and put a command = self.Function , this > function is called in the creation of RadioButton. It´s right this or > it´s wrong ? http://www.catb.org/~esr/faqs/smart-questions.html I'm pretty sure I can guess exactly what the problem is. I suspect your code looks somewhat like: btn = RadioButton(command=self.Function()) Follow the instructions in the above link and you should be able to work out why this is wrong. If I've failed to read your mind correctly, the above link should also teach you how to make it easier for me to do so. Tim Delaney -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.1 - Release Date: 2/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in the compiler ?
The call of MyClass isn´t in this order... i only want to explain that i´m calling the class 'MyClass' and when i do this the function "Function" is call when the compiler pass for the RadioButton. The same happened when i used Pmw.RadioSelect. I solve this problem now using this: radio = Pmw.RadioSelect() radio.bind('', self.Function) if i use : Pmw.RadioSelect(command = self.Function) the 'Function' is call. And i think that this is wrong and i only want to tell to help solve this bug. so, my code is this: file : MyClass.py import Pmw class MyClass: def __init__(self): radio = Pmw.RadioSelect() radio.bind('', self.Function) #Pmw.RadioSelect(command = self.Function) def Funciton(self): print "Enter in the Function" if __name__ == '__main__' : MyClass() when i call in the console like this: C:\python MyClass.py if i using in the __init__ this : Pmw.RadioSelect(command = self.Function) so the string "Enter in the Function" is print Thank you Glauco - Original Message - From: "Scott David Daniels" <[EMAIL PROTECTED]> To: Sent: Tuesday, May 03, 2005 11:21 AM Subject: Re: problem in the compiler ? Glauco Silva wrote: > python : 2.3.5 > os: win 2K This part is good enough (though sometimes it helps to mention the service pack number on windows systems). > My code is like this: > > MyClass() > > class MyClass: > def __init__(self): > btn = RadioButton(command=self.Function) > def Function(self): > print "Enter in the function" This is not good enough. Show us a small actual example that exhibits the problem behavior on your machine. Often in the course of doing this distillation, the original problem will become clear to you. The code above fails with: Traceback (most recent call last): File "", line 1, in -toplevel- MyClass() NameError: name 'MyClass' is not defined on the initial call to MyClass(). I suspect this is not what you care about. Don't make people trying to help you do any work you cannot do yourself. Imagine yourself browsing the newsgroup and trying to decide whether to spend some time trying to help someone with a problem. Would _you_ want to spend time trying to guess what the code was with the problem as well as what the problem was, or would you decide to help someone else out? --Scott David Daniels [EMAIL PROTECTED] -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.2 - Release Date: 2/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in the compiler ?
So , I will try to explain ! I´m trying to modify a code that doesn´t belong to me. I thought that there was a bug in the compilation of Pmw.RadioSelect, but there wans't. I hadn't noticed that the code invoked the button of radioselect in another part of it. Now I simply took off the part of the code which invoked the button and the program is working as I expected. Thanks for your help. Anyway, the code was this : - self.myButton = Pmw.RadioSelect(frame, selectmode = MULTIPLE, command = self.Function) self.myButton.add('C1') self.myButton.pack() ... self.myButton.invoke('C1') - - Original Message - From: "Delaney, Timothy C (Timothy)" <[EMAIL PROTECTED]> To: "Glauco Silva" <[EMAIL PROTECTED]>; Sent: Wednesday, May 04, 2005 8:20 PM Subject: RE: problem in the compiler ? Glauco Silva wrote: > I´m sorry, I feel I didn't comunicate very well . > The program I am writing is a part of a big project, so it would be > no use to post it here as it involves many other things and concepts. We wouldn't want the whole thing - that would be useless. What you need to do is trim it down to the smallest piece of code that causes the problem. Normally doing this reveals the actual problem, and you don't need to go to the newsgroup. > But i solve my problem and don´t have bug. My code was wrong. Excellent. You should now post your solution to the newsgroup. Tim Delaney -- No virus found in this incoming message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.3 - Release Date: 3/5/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.5 - Release Date: 4/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple "cmp"s chained one after another
You can try this : >>> l = [(2001, 5, 2),(2111,3,3),(1984, 3, 1), (2001, 1, 1)] >>> l.sort(lambda x = l[0],y = l[1] : cmp((x[1],x[2]),(y[1],y[2]))) - Original Message - From: "Volker Grabsch" <[EMAIL PROTECTED]> To: Sent: Saturday, May 14, 2005 7:09 AM Subject: Multiple "cmp"s chained one after another Hello! Ich just found a very nice 'pythonic' solution for an often appearing problem. I didn't find it documented anywhere, so I'm posting it here. If this isn't new in any way, I'd really like to get to know it. Example problem: I have some "datetime" objects and want to sort them, as here: birthdays = [d1,d2,d3,d4] birthdays.sort() However, I don't want to sort them the default way. These are birthdays, so only the month and day do matter, not the year. E.g.: 2003-01-01 should be smaller than 1984-05-01 So I have to write the comparison on my own, e.g. def cmp_birthdays(d1,d2): if d1.month > d2.month: return 1 if d1.month < d2.month: return -1 if d1.day > d2.day: return 1 if d1.day < d2.day: return -1 return 0 ... birthdays.sort(cmp_birthdays) This implementation of cmp_birthdays is very ugly. Image you want to chain more than 2 values in that "cmp_birthdays". I also want to use the builtin "cmp" function, not ">" and "<". After thinking some minutes about it, I found a very nice solution: I have some "cmp"s one aftter another. If one if them return 1 oder -1, it sould be returned. If it returns 0, the next "cmp" is used. In other words: I have a sequence of numbers, and want to get the first one that is not 0. (or return 0, if all numbers were 0) But this is exactly what the "or" operator does, due to short-circuit evaluation. In this example, that means: def cmp_bithdays(d1,d2): return cmp(d1.month,d2.month) or cmp(d1.day,d2.day) The generic pattern is: return cmp(...) or cmp (...) or cmp(...) or ... I'm not sure whether this pattern is already a "common recipe", but I found it to be a very nice idea. :-) Any opinions? Greets, Volker -- Volker Grabsch ---<<(())>>--- \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.11.10 - Release Date: 13/5/2005 -- http://mail.python.org/mailman/listinfo/python-list
Creat a DLL File from python code, and use that DLL file in other Platform (Labview, Java .NET etc)
Hi, I would like to request your attention for this very specific issue: I have several classes in Python, and now I want simply re-use it, in other language. The closest to solution I think I came was with this site: http://www.py2exe.org/index.cgi/Py2exeAndCtypesComExeServer?highlight=%28%28Py2exeAndCtypesComDllServer%29%29 but I not able to solve questions related with TLB files and __init__.py files. So, could anyone give a tip about HOW TO CREAT a dll file from Python? thank in advance AMMS -- http://mail.python.org/mailman/listinfo/python-list
Creating a DLL file from Python Code
Hi, I would like to request your attention for this very specific issue: I have several classes in Python, and now I want simply re-use it, in other language. The closest to solution I think I came was with this site: http://www.py2exe.org/index.cgi/Py2exeAndCtypesComDllServer but I not able to solve questions related with TLB files and __init__.py files. So, could anyone give a tip about how to creat a dll file from Python? It is possible under any conditions? thank in advance macedo -- http://mail.python.org/mailman/listinfo/python-list
Re: Converging Multiple Classes
Take a look at the strategy pattern. But with python being a dinamic language, you probably won't need to implement it like that. http://en.wikipedia.org/wiki/Strategy_pattern Example: # import all you need CAMERAS = ['A','B','C'] def capture_A: pass def capture_B: pass def capture_C: pass def capture(camera): if camera in CAMERAS: if camera = 'A': function = capture_A if camera = 'B': function = capture_B if camera = 'C': function = capture_C # call function function() else return On Fri, Feb 4, 2011 at 2:39 PM, Wanderer wrote: > I have a bunch of cameras I want to run tests on. They each have > different drivers and interfaces. What I want to do is create python > wrappers so that they all have a common interface and can be called by > the same python test bench program. I'm not sure what to call it. I > don't think it's inheritance. Maybe there is no official thing here > and I just need to brute force my way through it. Is there some > programming methodology I should be using? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- George R. C. Silva Desenvolvimento em GIS http://blog.geoprocessamento.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterate from 2nd element of a huge list
Em 01-02-2012 01:39, Paulo da Silva escreveu: > Hi! > > What is the best way to iterate thru a huge list having the 1st element > a different process? I.e.: > > process1(mylist[0]) > for el in mylist[1:]: > process2(el) > > This way mylist is almost duplicated, isn't it? > > Thanks. I think iter is nice for what I need. Thank you very much to all who responded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterate from 2nd element of a huge list
Em 01-02-2012 03:16, Paulo da Silva escreveu: > Em 01-02-2012 01:39, Paulo da Silva escreveu: >> Hi! >> >> What is the best way to iterate thru a huge list having the 1st element >> a different process? I.e.: >> >> process1(mylist[0]) >> for el in mylist[1:]: >> process2(el) >> >> This way mylist is almost duplicated, isn't it? >> >> Thanks. > > > I think iter is nice for what I need. > Thank you very much to all who responded. BTW, iter seems faster than iterating thru mylist[1:]! -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterate from 2nd element of a huge list
Em 01-02-2012 04:55, Cameron Simpson escreveu: > On 01Feb2012 03:34, Paulo da Silva wrote: > | BTW, iter seems faster than iterating thru mylist[1:]! > > I would hope the difference can be attributed to the cost of copying > mylist[1:]. I don't think so. I tried several times and the differences were almost always consistent. I put mylist1=mylist[1:] outside the time control. iter still seems a little bit faster. Running both programs several times (1000 elements list) I only got iter being slower once! But, of course, most of the difference comes from the copy. -- http://mail.python.org/mailman/listinfo/python-list
setup.py for an extension
Hi all. I have a python extension (bindings for a C lib - no swig) and I would like to write a setup.py to build a source distribution pack. The extension consists of 3 files: foo.h foo.c foo.py that are placed in a eclipse directory /home//ECLIPSE/workspace/ext/src foo.h+foo.c are to be compiled into _foo.so shared lib. _foo.so is itself a module only called from foo.py. The dir I wrote the setup.py is any arbitrary dir. I don't want to put packaging stuff into the eclipse source. I read the docs but have no idea on how to do this. Some tentatives I did completely failed. Any help? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: random number
If you want it as an int: random.randint(10, 99) Or as a string: s = '%06d' % random.randint(0, 99) On Mon, Mar 26, 2012 at 2:08 AM, Nikhil Verma wrote: > Hi All > > How can we generate a 6 digit random number from a given number ? > > eg:- > > def number_generator(id): > random.randint(id,99) > > When i am using this it is sometimes giving me five digit and sometimes 6 > . I want to avoid encryption . Can i have alphanumeric 6 digit random > number from this . > > Thanks in advance > > -- > Regards > Nikhil Verma > +91-958-273-3156 > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
pyplot: change the number of x labels (from 6)
Hi all. I want to have dates as major ticks labels of X axis. This fragment of code works fine except that I need more dates to appear instead the 6 I am getting. The number of dates in dtsd is for ex. 262. Thanks for any help. BTW, I got most of this code from some site on the internet. ... fig=plt.figure(figsize=(12,9)) gs=gridspec.GridSpec(2,1,height_ratios=[4,1]) ... ax0=plt.subplot(gs[0]) ... plt.xlim(-0.1,dts[-1]+0.1) dtsd=pd.to_datetime(ds.getIndexes()) def format_date(x,__pos=None): thisind=np.clip(int(x+0.5),0,dtslen-1) return dtsd[thisind].strftime('%Y-%m-%d') ax0.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate() ... -- https://mail.python.org/mailman/listinfo/python-list
Re: pyplot: change the number of x labels (from 6)
Às 09:17 de 10-01-2018, Thomas Jollans escreveu: On 2018-01-10 05:22, Paulo da Silva wrote: Hi all. ... It's a bit hard to tell without a working example, but I think you'll want to set a tick locator, e.g. something like ax0.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1)) Basically I have a list of hundred of dates (one per point) and I want few of them, to fill the X axis. This should be simple! The code I have (too complex for the task, btw), from the internet, does exactly that, including presenting them 45º oriented, but only presents 5 or 6 dates. I want more, perhaps 12. Read this: https://matplotlib.org/api/ticker_api.html The old-fashioned way would be to set to tick locations manually with https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticks.html Yes, I need to look at this ... Thank you. -- https://mail.python.org/mailman/listinfo/python-list
pandas (in jupyter?) problem
Hi all! I'm having the following problem. Consider the code (the commented or the not commented which I think do the same things): #for col in missing_cols: #df[col] = np.nan df=df.copy() df[missing_cols]=np.nan df has about 2 cols and len(missing_cols) is about 18000. I'm getting lots (1 by missing_col?) of the following message from ipykernel: "PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()` df[missing_cols]=np.nan" At first I didn't have df=df.copy(). I added it later, but the same problem. This slows down the code a lot, perhaps because jupyter is taking too much time issuing these messages! Thanks for any comments. -- https://mail.python.org/mailman/listinfo/python-list
Re: What's up with modern Python programmers rewriting everything in Rust?
Às 16:40 de 20/06/22, Dennis Lee Bieber escreveu: On Mon, 20 Jun 2022 15:54:29 +0100, Paulo da Silva declaimed the following: Às 15:07 de 19/06/22, jan Anja escreveu: Dude, it's called CPython for a reason. IMHO CPython means Core Python, not C Python. It is, as I recall, a term for the reference implementation of Python, which was written in C... In contrast to things like Jython -- Python implemented using Java. Yes, it is a reference. That's why it is called "Core Python". The "C" has nothing to do with the C programming language. It may well be written in any language. So far it is "C" language. -- https://mail.python.org/mailman/listinfo/python-list
Re: What's up with modern Python programmers rewriting everything in Rust?
Às 15:07 de 19/06/22, jan Anja escreveu: Dude, it's called CPython for a reason. IMHO CPython means Core Python, not C Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: "CPython"
Às 18:19 de 20/06/22, Stefan Ram escreveu: The same personality traits that make people react to troll postings might make them spread unconfirmed ideas about the meaning of "C" in "CPython". The /core/ of CPython is written in C. CPython is the /canonical/ implementation of Python. The "C" in "CPython" stands for C. Not so "unconfirmed"! Look at this article, I recently read: https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ There is a sentence in ther that begins with "CPython, short for Core Python, a reference implementation that other Python distributions are derived from, ...". Anyway, I wrote "IMHO". Do you have any credible reference to your assertion "The "C" in "CPython" stands for C."? Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: "CPython"
Às 20:01 de 20/06/22, Paulo da Silva escreveu: Às 18:19 de 20/06/22, Stefan Ram escreveu: The same personality traits that make people react to troll postings might make them spread unconfirmed ideas about the meaning of "C" in "CPython". The /core/ of CPython is written in C. CPython is the /canonical/ implementation of Python. The "C" in "CPython" stands for C. Not so "unconfirmed"! Look at this article, I recently read: https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ There is a sentence in ther that begins with "CPython, short for Core Python, a reference implementation that other Python distributions are derived from, ...". Anyway, I wrote "IMHO". Do you have any credible reference to your assertion "The "C" in "CPython" stands for C."? Thank you. Well ... I read the responses and they are not touching the point! I just answered, with my opinion based on articles I have read in the past. Certainly I could not be sure. That's why I responded as an opinion (IMHO) and not as an assertion. Stefan Ram responded with a, at least, not very polite post. That's why I needed to somehow "defend" why I posted that response, and, BTW, trying to learn why he said that the C in CPython means "written in C". I still find very strange, to not say weird, that a compiler or interpreter has a name based in the language it was written. But, again, is just my opinion and nothing more. I rest my case. Thank you all. -- https://mail.python.org/mailman/listinfo/python-list
Re: "CPython"
Às 03:20 de 21/06/22, MRAB escreveu: On 2022-06-21 02:33, Chris Angelico wrote: On Tue, 21 Jun 2022 at 11:13, Paulo da Silva wrote: Às 20:01 de 20/06/22, Paulo da Silva escreveu: > Às 18:19 de 20/06/22, Stefan Ram escreveu: >> The same personality traits that make people react >> to troll postings might make them spread unconfirmed >> ideas about the meaning of "C" in "CPython". >> >> The /core/ of CPython is written in C. >> >> CPython is the /canonical/ implementation of Python. >> >> The "C" in "CPython" stands for C. >> >> > > Not so "unconfirmed"! > Look at this article, I recently read: > https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ > > > There is a sentence in ther that begins with "CPython, short for Core > Python, a reference implementation that other Python distributions are > derived from, ...". > > Anyway, I wrote "IMHO". > > Do you have any credible reference to your assertion "The "C" in > "CPython" stands for C."? > > Thank you. Well ... I read the responses and they are not touching the point! I just answered, with my opinion based on articles I have read in the past. Certainly I could not be sure. That's why I responded as an opinion (IMHO) and not as an assertion. Stefan Ram responded with a, at least, not very polite post. That's why I needed to somehow "defend" why I posted that response, and, BTW, trying to learn why he said that the C in CPython means "written in C". I still find very strange, to not say weird, that a compiler or interpreter has a name based in the language it was written. But, again, is just my opinion and nothing more. Not sure why it's strange. The point is to distinguish "CPython" from "Jython" or "Brython" or "PyPy" or any of the other implementations. Yes, CPython has a special place because it's the reference implementation and the most popular, but the one thing that makes it distinct from all the others is that it's implemented in C. And just to make it clear, the interpreter/compiler _itself_ is still called "python". "CPython" is a name/term that was applied retroactively to that particular implementation when another implementation appeared. Yes, but that does not necessarily means that the C has to refer to the language of implementation. It may well be a "core" reference to distinguish that implementation from others with different behaviors. Let's say they reimplement "reference python" CPython in Rust. What is better? Change the "reference python" CPython name to RPython, for example, or let it as CPython? It's my opinion that it should stay as CPython. After all who cares in which language it is implemented? Regards. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: "CPython"
Às 02:33 de 21/06/22, Chris Angelico escreveu: On Tue, 21 Jun 2022 at 11:13, Paulo da Silva wrote: Às 20:01 de 20/06/22, Paulo da Silva escreveu: Às 18:19 de 20/06/22, Stefan Ram escreveu: The same personality traits that make people react to troll postings might make them spread unconfirmed ideas about the meaning of "C" in "CPython". The /core/ of CPython is written in C. CPython is the /canonical/ implementation of Python. The "C" in "CPython" stands for C. Not so "unconfirmed"! Look at this article, I recently read: https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ There is a sentence in ther that begins with "CPython, short for Core Python, a reference implementation that other Python distributions are derived from, ...". Anyway, I wrote "IMHO". Do you have any credible reference to your assertion "The "C" in "CPython" stands for C."? Thank you. Well ... I read the responses and they are not touching the point! I just answered, with my opinion based on articles I have read in the past. Certainly I could not be sure. That's why I responded as an opinion (IMHO) and not as an assertion. Stefan Ram responded with a, at least, not very polite post. That's why I needed to somehow "defend" why I posted that response, and, BTW, trying to learn why he said that the C in CPython means "written in C". I still find very strange, to not say weird, that a compiler or interpreter has a name based in the language it was written. But, again, is just my opinion and nothing more. Not sure why it's strange. The point is to distinguish "CPython" from "Jython" or "Brython" or "PyPy" or any of the other implementations. Notice that they are, for example, Jython and not JPython. There is also Cython that is a different thing. And YES. You have the right to not feel that as strange. Regards Paulo -- https://mail.python.org/mailman/listinfo/python-list
Subtract n months from datetime
Hi! I implemented a part of a script to subtract n months from datetime. Basically I subtracted n%12 from year and n//12 from the month adding 12 months when it goes<=0. Then used try when converting to datetime again. So, if the day is for example 31 for a 30 days month it raises a ValuError exception. Then I subtract 1 to day and repeat. The code seems too naive and very very complicated! What is the best way to achieve this? Any existent module? At the very end, what I want is to subtract nx where x can be y, m, w, d for respectively years, months, weeks or days. I feel I am missing something here ... Thanks. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Subtract n months from datetime
Às 05:44 de 21/06/22, Paul Bryan escreveu: Here's how my code does it: import calendar def add_months(value: date, n: int): """Return a date value with n months added (or subtracted if negative).""" year = value.year + (value.month - 1 + n) // 12 month = (value.month - 1 + n) % 12 + 1 day = min(value.day, calendar.monthrange(year, month)[1]) return date(year, month, day) Paul I have a datetime, not a date. Anyway, the use of calendar.monthrange simplifies the task a lot. Assuming dtnow has the current datetime and dtn the number of months to be subtracted, here is my solution (the code was not cleaned yet - just a test): dtnow_t=list(dtnow.timetuple()[:6]+(dtnow.microsecond,)) y=dtnow_t[0] # y,m,d,*_=dtnow_t seems slower m=dtnow_t[1] d=dtnow_t[2] dy,dm=divmod(dtn,12) y-=dy m-=dm if m<1: m+=12 y-=1 daysinmonth=calendar.monthrange(y,m)[1] d=min(d,daysinmonth) dtnow_t[0]=y dtnow_t[1]=m dtnow_t[2]=d bt=datetime.datetime(*dtnow_t) Any comments are welcome. Thank you. Paulo On Tue, 2022-06-21 at 05:29 +0100, Paulo da Silva wrote: Hi! I implemented a part of a script to subtract n months from datetime. Basically I subtracted n%12 from year and n//12 from the month adding 12 months when it goes<=0. Then used try when converting to datetime again. So, if the day is for example 31 for a 30 days month it raises a ValuError exception. Then I subtract 1 to day and repeat. The code seems too naive and very very complicated! What is the best way to achieve this? Any existent module? At the very end, what I want is to subtract nx where x can be y, m, w, d for respectively years, months, weeks or days. I feel I am missing something here ... Thanks. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Subtract n months from datetime [Why?]
Às 05:29 de 21/06/22, Paulo da Silva escreveu: As a general response to some comments ... Suppose we need to delete records from a database older than ... Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. The same happens for the years. 5 years before February, 29 is February, 28. Again, this is my opinion and that's the way I like it :-) Regards Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Subtract n months from datetime [Why?]
Às 20:25 de 22/06/22, Barry Scott escreveu: On 22 Jun 2022, at 17:59, Paulo da Silva wrote: Às 05:29 de 21/06/22, Paulo da Silva escreveu: As a general response to some comments ... Suppose we need to delete records from a database older than ... Today, it's usual to specify days. For example you have to keep some gov papers for 90 days. This seems to come from computers era. In our minds, however, we immediately think 90 days=3 months. For example, one may want to delete some files older than 9 months. It's far more intuitive than 270 days. When we talk about years it is still going. For example I need to keep my receipts for 5 years because IRS audits. Accepting this, it's intuitive, for example, that 3 months before July, 31 is April, 30. The same happens for the years. 5 years before February, 29 is February, 28. The advantage of 30 days, 90 days etc is that a contract or law does not need to tell you how to deal with the problems of calendar months. As you say in peoples thoughts that 1 month or 3 months etc. But an accounts department will know how to to the number of days till they have to pay up. Yes. But my point is to justify why I want months. And it depends on the application. Let's suppose a program for Joe User to clean something - files, for example. There are no rules except for the comfort of the user. He would prefer to be able to say 9 months back instead of 270 days. And by 9 months, he expects to count down 9 months. Not 270 days. That's what happens with the script I am writing. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Subtract n months from datetime
Às 19:47 de 22/06/22, Marco Sulla escreveu: The package arrow has a simple shift method for months, weeks etc https://arrow.readthedocs.io/en/latest/#replace-shift At first look it seems pretty good! I didn't know it. Thank you Marco. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Find the path of a shell command
Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? Thanks for any comments/responses. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 05:00 de 12/10/22, Paulo da Silva escreveu: Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? Thank you all who have responded so far. I think that the the suggestion of searching the PATH env seems the best. Another thing that I thought of is that of the 'which', but, to avoid the mentioned recurrent problem of not knowing where 'which' is I would use 'type' instead. 'type' is a bash (sh?) command. Thanks Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 17:22 de 12/10/22, Tilmann Hentze escreveu: Paulo da Silva schrieb: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Probably you could use os.unlink[1] with no problem. No, because I need to launch several rm's that keep running after the script ends. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 20:16 de 12/10/22, 2qdxy4rzwzuui...@potatochowder.com escreveu: On 2022-10-12 at 17:43:18 +0100, Paulo da Silva wrote: Às 17:22 de 12/10/22, Tilmann Hentze escreveu: Paulo da Silva schrieb: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Probably you could use os.unlink[1] with no problem. No, because I need to launch several rm's that keep running after the script ends. rm doesn't take that long. Why are you detaching them? Because the use of "rm -rf" here is to remove full dirs, mostly in external drives, each reaching more than hundreds thousand files. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 19:14 de 12/10/22, Jon Ribbens escreveu: On 2022-10-12, Paulo da Silva wrote: Às 05:00 de 12/10/22, Paulo da Silva escreveu: Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? Thank you all who have responded so far. I think that the the suggestion of searching the PATH env seems the best. Another thing that I thought of is that of the 'which', but, to avoid the mentioned recurrent problem of not knowing where 'which' is I would use 'type' instead. 'type' is a bash (sh?) command. If you're using subprocess.run / subprocess.Popen then the computer is *already* searching PATH for you. Yes, and it works out of cron. Your problem must be that your cron job is being run without PATH being set, perhaps you just need to edit your crontab to set PATH to something sensible. I could do that, but I am using /etc/cron.* for convenience. Or just hard-code your program to run '/bin/rm' explicitly, which should always work (unless you're on Windows, of course!) It can also be in /bin, at least. A short idea is to just check /bin/rm and /usr/bin/rm, but I prefer searching thru PATH env. It only needs to do that once. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 20:09 de 12/10/22, Antoon Pardon escreveu: Op 12/10/2022 om 18:49 schreef Paulo da Silva: Às 05:00 de 12/10/22, Paulo da Silva escreveu: Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? Thank you all who have responded so far. I think that the the suggestion of searching the PATH env seems the best. I fear that won't work. If it doesn't work in cron, that probably means, PATH is not set properly in your cron environment. And if PATH is not set properly, searching it explicitely won't work either. It seems you are right :-( I didn't think of that! Does 'type' bash command work? I don't know how bash 'type' works. I need to do some tests. Thanks Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command
Às 22:38 de 12/10/22, Jon Ribbens escreveu: On 2022-10-12, Jon Ribbens wrote: On 2022-10-12, Paulo da Silva wrote: Às 19:14 de 12/10/22, Jon Ribbens escreveu: On 2022-10-12, Paulo da Silva wrote: Às 05:00 de 12/10/22, Paulo da Silva escreveu: Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? Thank you all who have responded so far. I think that the the suggestion of searching the PATH env seems the best. Another thing that I thought of is that of the 'which', but, to avoid the mentioned recurrent problem of not knowing where 'which' is I would use 'type' instead. 'type' is a bash (sh?) command. If you're using subprocess.run / subprocess.Popen then the computer is *already* searching PATH for you. Yes, and it works out of cron. Your problem must be that your cron job is being run without PATH being set, perhaps you just need to edit your crontab to set PATH to something sensible. I could do that, but I am using /etc/cron.* for convenience. Or just hard-code your program to run '/bin/rm' explicitly, which should always work (unless you're on Windows, of course!) It can also be in /bin, at least. I assume you mean /usr/bin. But it doesn't matter. As already discussed, even if 'rm' is in /usr/bin, it will be in /bin as well (or /usr/bin and /bin will be symlinks to the same place). A short idea is to just check /bin/rm and /usr/bin/rm, but I prefer searching thru PATH env. It only needs to do that once. I cannot think of any situation in which that will help you. But if for some reason you really want to do that, you can use the shutil.which() function from the standard library: >>> import shutil >>> shutil.which('rm') '/usr/bin/rm' Actually if I'm mentioning shutil I should probably mention shutil.rmtree() as well, which does the same as 'rm -r', without needing to find or run any other executables. Except that you can't have parallel tasks, at least in an easy way. Using Popen I just launch rm's and end the script. -- https://mail.python.org/mailman/listinfo/python-list
Re: Find the path of a shell command [POSTPONED]
Às 05:00 de 12/10/22, Paulo da Silva escreveu: Hi! The simple question: How do I find the full path of a shell command (linux), i.e. how do I obtain the corresponding of, for example, "type rm" in command line? The reason: I have python program that launches a detached rm. It works pretty well until it is invoked by cron! I suspect that for cron we need to specify the full path. Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? What about other commands? For now I will postpone this problem. I just wrote a small script to delete a dir using rm and it works even under cron! There is another problem involved. The script, works fine except when launched by cron! Why? I'll have to look into this later when I have more time. For now I solved the problem using a complementary shell script. Thank you very much to those who responded. Paulo -- https://mail.python.org/mailman/listinfo/python-list
A trivial question that I don't know - document a function/method
Hi all! What is the correct way, if any, of documenting a function/method? 1. def foo(a,b): """ A description. a: Whatever 1 b: Whatever 2 """ ... 2. def foo(a,b): """ A description. a -- Whatever 1 b -- Whatever 2 """ ... 3. def foo(a,b): """ A description. @param a: Whatever 1 @param b: Whatever 2 """ ... 4. def foo(a,b): """ A description. :param a: Whatever 1 :param b: Whatever 2 """ ... 5. Any other ... Any comments/suggestions are welcome. Thanks. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Typing: Is there a "cast operator"?
Hello! I am in the process of "typing" of some of my scripts. Using it should help a lot to avoid some errors. But this is new for me and I'm facing some problems. Let's I have the following code (please don't look at the program content): f=None # mypy naturally assumes Optional(int) because later, at open, it is assigned an int. .. if f is None: f=os.open(... .. if f is not None: os.write(f, ...) .. if f is not None: os.close(f) When I use mypy, it claims Argument 1 to "write" has incompatible type "Optional[int]"; expected "int" Argument 1 to "close" has incompatible type "Optional[int]"; expected "int" How to solve this? Is there a way to specify that when calling os.open f is an int only? I use None a lot for specify uninitialized vars. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: A trivial question that I don't know - document a function/method
Às 21:58 de 22/10/22, Paulo da Silva escreveu: Hi all! What is the correct way, if any, of documenting a function/method? Thank you all for the, valuable as usual, suggestions. I am now able to make my choices. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Typing: Is there a "cast operator"? [RESOLVED]
Às 21:36 de 23/10/22, Paulo da Silva escreveu: Hello! I am in the process of "typing" of some of my scripts. Using it should help a lot to avoid some errors. But this is new for me and I'm facing some problems. Let's I have the following code (please don't look at the program content): f=None # mypy naturally assumes Optional(int) because later, at open, it is assigned an int. .. if f is None: f=os.open(... .. if f is not None: os.write(f, ...) .. if f is not None: os.close(f) When I use mypy, it claims Argument 1 to "write" has incompatible type "Optional[int]"; expected "int" Argument 1 to "close" has incompatible type "Optional[int]"; expected "int" How to solve this? Is there a way to specify that when calling os.open f is an int only? And yes there is! Exactly the "cast" operator. A mistype led me to wrong search results. I'm sorry. So, in the above code, we have to do: os.write(cast(int,f), ...) and os.close(cast(int,f), ...) Regards. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Typing: Is there a "cast operator"?
Às 23:56 de 23/10/22, Cameron Simpson escreveu: On 23Oct2022 21:36, Paulo da Silva wrote: I am in the process of "typing" of some of my scripts. Using it should help a lot to avoid some errors. But this is new for me and I'm facing some problems. Let's I have the following code (please don't look at the program content): f=None # mypy naturally assumes Optional(int) because later, at open, it is assigned an int. .. if f is None: f=os.open(... .. if f is not None: os.write(f, ...) .. if f is not None: os.close(f) When I use mypy, it claims Argument 1 to "write" has incompatible type "Optional[int]"; expected "int" Argument 1 to "close" has incompatible type "Optional[int]"; expected "int" How to solve this? Is there a way to specify that when calling os.open f is an int only? I use None a lot for specify uninitialized vars. Maybe you shouldn't. The other way is to just not initialise the var at all. You could then just specify a type. Example: Python 3.8.13 (default, Aug 11 2022, 15:46:53) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> f:int >>> f Traceback (most recent call last): File "", line 1, in NameError: name 'f' is not defined >>> So now `f` has `int` type definitely (for `mypy`'s purposes), and if used before assignment raises a distinctive error (versus having the value `None`, which you might then pass around, and perhaps successfully use in some contexts). It is probably better on the whole to specify types up front rather than relying on `mypy` or similar to infer them. That way (a) you're stating your intent and (b) not relying on an inferred type, which if you've got bugs may be inferred _wrong_. If `mypy` infers a type incorrectly all the subsequent checks will also be flawed, perhaps subtly. Yes. I also use to make f unavailable (f=None) when something goes wrong and I don't want to stop the script but of course I could use "del f". I also need to care about using "try", which might be better than "if" tests. A thing to think of ... Thanks. Paulo -- https://mail.python.org/mailman/listinfo/python-list
A typing question
Hi! Consider this simple script ... ___ from typing import List, Optional class GLOBALS: foos=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE in a real script def __init__(self): pass GLOBALS.foos: Optional[Foos]=Foos() ___ Running mypy on it: pt9.py:18: error: Type cannot be declared in assignment to non-self attribute pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") Line 18 is last line and pt9.py is the scrip. Replacing last line by GLOBALS.foos=Foos() and running mypy still gives the second error. pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") What is the common practice in these cases? Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 22:34 de 29/10/22, dn escreveu: Out of interest, tested snippet in PyCharm, cf native-mypy. It flags the original: GLOBALS.foos: Optional[Foos]=Foos() but not the fall-back: GLOBALS.foos=Foos() Must admit, the first query coming to mind was: why is the typing taking place at initialisation-time, rather than within the (class) definition? At definition time "foos" has already been typed as None by implication! Solution (below) will not work if the mention of Foos in GLOBALS is a forward-reference. Either move GLOBALS to suit, or surround "Foos" with quotes. This is the problem for me. So far, without typing, I used to have some config and globals classes, mostly to just group definitions an make the program more readable. A matter of taste and style. Now, "typing" is breaking this, mostly because of this forward reference issue. The funny thing is that if I replace foos by Foos it works because it gets known by the initial initialization :-) ! from typing import List, Optional class GLOBALS: Foos: Optional[Foos]=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE def __init__(self): pass GLOBALS.Foos=Foos() Also, these days (Python version allowing) importing "List" is unnecessary. Instead could use "list". On 30/10/2022 10.23, Sam Ezeh wrote: Do you want the following? ``` from typing import List, Optional class GLOBALS: foos: Optional[Foos] = None class Foo: def __init__(self): pass class Foos: Foos: List[Foo] = [] def __init__(self): pass GLOBALS.foos = Foos() ``` Kind regards, Sam Ezeh On Sat, 29 Oct 2022 at 22:13, Paulo da Silva < p_d_a_s_i_l_v_a...@nonetnoaddress.pt> wrote: Hi! Consider this simple script ... ___ from typing import List, Optional class GLOBALS: foos=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE in a real script def __init__(self): pass GLOBALS.foos: Optional[Foos]=Foos() ___ Running mypy on it: pt9.py:18: error: Type cannot be declared in assignment to non-self attribute pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") Line 18 is last line and pt9.py is the scrip. Replacing last line by GLOBALS.foos=Foos() and running mypy still gives the second error. pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") What is the common practice in these cases? Thank you. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 02:32 de 30/10/22, dn escreveu: On 30/10/2022 11.59, Paulo da Silva wrote: Solution (below) will not work if the mention of Foos in GLOBALS is a forward-reference. Either move GLOBALS to suit, or surround "Foos" with quotes. This is the problem for me. So far, without typing, I used to have some config and globals classes, mostly to just group definitions an make the program more readable. A matter of taste and style. Agreed, a good practice. Thank you. Now, "typing" is breaking this, mostly because of this forward reference issue. As a first step, use the quotation-marks to indicate that such will be defined later in the code:- class GLOBALS: Foos: Optional[Foos]=None class GLOBALS: Foos: Optional["Foos"]=None Later, as gather (typing) expertise, can become more sophisticated, as-and-when... The funny thing is that if I replace foos by Foos it works because it gets known by the initial initialization :-) ! Is the objective to write (good) code, or merely to satisfy the type-checker? Something that is misleading is not going to be appreciated by others (including the +6-months you), eg a = a + 1 # decrement total Typing is not compulsory, and has been designed so that we can implement it a bit at a time, eg only one function amongst many contained by a module - if that's the only code that requires maintenance/update. Best not to create "technical debt" though! The main idea is to eventually catch some, otherwise "hidden", errors and produce better and cleaner code. Documentation is also a must. Regards -- https://mail.python.org/mailman/listinfo/python-list
Re: A typing question
Às 01:14 de 30/10/22, Thomas Passin escreveu: On 10/29/2022 1:45 PM, Paulo da Silva wrote: Hi! Consider this simple script ... ___ from typing import List, Optional class GLOBALS: foos=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE in a real script def __init__(self): pass GLOBALS.foos: Optional[Foos]=Foos() ___ Running mypy on it: pt9.py:18: error: Type cannot be declared in assignment to non-self attribute pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") Line 18 is last line and pt9.py is the scrip. Replacing last line by GLOBALS.foos=Foos() and running mypy still gives the second error. pt9.py:18: error: Incompatible types in assignment (expression has type "Foos", variable has type "None") What is the common practice in these cases? Thank you. I don't understand class Foos: Foos: List[Foo]=[] If "Foos" is supposed to be a class attribute, then it cannot have the same name as the class. Yes it can. You can refer it anywhere by Foos.Foos as a list of Foo elements. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 10:26 de 30/10/22, Peter J. Holzer escreveu: On 2022-10-29 23:59:44 +0100, Paulo da Silva wrote: Às 22:34 de 29/10/22, dn escreveu: Solution (below) will not work if the mention of Foos in GLOBALS is a forward-reference. Either move GLOBALS to suit, or surround "Foos" with quotes. ^^ This is the problem for me. Quotes are a bit ugly, but why are they a problem? [...] The funny thing is that if I replace foos by Foos it works because it gets known by the initial initialization :-) ! from typing import List, Optional class GLOBALS: Foos: Optional[Foos]=None [...] class Foos: That seems like a bug to me. What is the «Foos» in «Optional[Foos]» referring to? If it's the class attribute «Foos» then that's not a type and even if its type is inferred that's not the same as «Optional[it's type]», or is it? If it's referring to the global symbol «Foos» (i.e. the class defined later) that hasn't been defined yet, so it shouldn't work (or alternatively, if forward references are allowed it should always work). The problem is exactly this. Is there anything to do without loosing my script structure and usual practice? The forward reference only is needed to the "typing thing". Even if I declare class "Foos: pass" before, then another error arises - something like "already declared" below. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 22:34 de 29/10/22, dn escreveu: Out of interest, tested snippet in PyCharm, cf native-mypy. It flags the original: GLOBALS.foos: Optional[Foos]=Foos() but not the fall-back: GLOBALS.foos=Foos() Must admit, the first query coming to mind was: why is the typing taking place at initialisation-time, rather than within the (class) definition? At definition time "foos" has already been typed as None by implication! Solution (below) will not work if the mention of Foos in GLOBALS is a forward-reference. Either move GLOBALS to suit, or surround "Foos" with quotes. Somehow I missed this sentence the 1st. time I read this post :-( This is good enough to me! Thank you. I didn't know about this "quoting" thing. Regards Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 17:06 de 30/10/22, Stefan Ram escreveu: Paulo da Silva writes: Is there anything to do without loosing my script structure and usual practice? to lose (losing): to stop having something to loose (loosing): to let or make loose (see next line) loose (adj.): not firmly attached/tied/fastened/controlled to loosen: similar to "to loose" It was a keyboard bounce ;-) How about answering the question? Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Fwd: A typing question
Às 21:08 de 31/10/22, Peter J. Holzer escreveu: On 2022-10-30 11:26:56 +0100, Peter J. Holzer wrote: On 2022-10-29 23:59:44 +0100, Paulo da Silva wrote: The funny thing is that if I replace foos by Foos it works because it gets known by the initial initialization :-) ! from typing import List, Optional class GLOBALS: Foos: Optional[Foos]=None [...] class Foos: That seems like a bug to me. But is it even true? I just tried to reproduce it (should have done that before answering) with mypy 0.942 (included in Ubuntu 22.04 LTS): [p1]--- from typing import List, Optional class GLOBALS: foos: Optional[Foos]=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE def __init__(self): pass GLOBALS.foos=Foos() --- [p2]--- from typing import List, Optional class GLOBALS: Foos: Optional[Foos]=None class Foo: def __init__(self): pass class Foos: Foos: List[Foo]=[] # SOME GLOBALS ARE USED HERE def __init__(self): pass GLOBALS.Foos=Foos() --- --- p1 2022-10-31 21:59:49.639869922 +0100 +++ p2 2022-10-31 21:58:19.815830677 +0100 @@ -1,7 +1,7 @@ from typing import List, Optional class GLOBALS: -foos: Optional[Foos]=None +Foos: Optional[Foos]=None class Foo: @@ -15,4 +15,4 @@ def __init__(self): pass -GLOBALS.foos=Foos() +GLOBALS.Foos=Foos() So the only difference is the capitalization of foos. And mypy accepts both (as it probably should): % mypy p1 Success: no issues found in 1 source file % mypy p2 Success: no issues found in 1 source file If you did something different, please explain what you did. Yes for mypy. Try to run them (python3 ). Paulo -- https://mail.python.org/mailman/listinfo/python-list
typing: property/setter and lists?
Hi! And a typing problem again!!! ___ class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) ___ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") How do I turn around this? Thanks. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: typing: property/setter and lists? [RESOLVED]
Às 03:24 de 03/11/22, Paulo da Silva escreveu: Hi! And a typing problem again!!! ___ class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) ___ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") How do I turn around this? Changing def foos(self) -> list[int]: to def foos(self) -> Union[list[int]]: fixes the problem. Not so elegant, however! Regards. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: typing: property/setter and lists? [RESOLVED ERRATA]
Às 05:32 de 03/11/22, Paulo da Silva escreveu: Às 03:24 de 03/11/22, Paulo da Silva escreveu: Hi! And a typing problem again!!! ___ class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) ___ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") How do I turn around this? Changing def foos(self) -> list[int]: to def foos(self) -> Union[list[int]]: I meant, of course, def foos(self) -> Union[list[int],int]: Sorry. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: typing: property/setter and lists? [RESOLVED]
Às 18:16 de 03/11/22, Chris Angelico escreveu: On Fri, 4 Nov 2022 at 05:03, Paulo da Silva wrote: Changing def foos(self) -> list[int]: to def foos(self) -> Union[list[int]]: fixes the problem. Not so elegant, however! Wait, what?! Union[X, Y] means "X or Y" Union[X] means "X, but don't complain if it's a @property". Is that how it goes? I'm sorry. A bad transposition of the text. I meant def foos(self) -> Union[list[int],int]: Regards. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: typing: property/setter and lists?
Às 07:55 de 03/11/22, dn escreveu: On 03/11/2022 16.24, Paulo da Silva wrote: class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) ___ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") To help us to help you please copy-paste the *exact* message - especially which line is in-question. The above code passes without complaint in PyCharm, and executes. However, the general rule?convention would be to establish type at the first mention of the identifier, eg def __init__(self): self.__foos:list[int] = 5 * [ 0 ] # or [ 0, 0, 0, 0, 0, ] Why the "__i", and not "i", or "_"? Just because of my personal taste. I know that __ means (for me) a "not used anymore" var and i is an indexer/counter/... Regards. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: typing: property/setter and lists? [RESOLVED ERRATA]
Às 07:52 de 04/11/22, dn escreveu: On 04/11/2022 07.50, Chris Angelico wrote: On Fri, 4 Nov 2022 at 05:48, Paulo da Silva wrote: Às 05:32 de 03/11/22, Paulo da Silva escreveu: Às 03:24 de 03/11/22, Paulo da Silva escreveu: Hi! And a typing problem again!!! ___ class C: def __init__(self): self.__foos=5*[0] @property def foos(self) -> list[int]: return self.__foos @foos.setter def foos(self,v: int): self.__foos=[v for __i in self.__foos] c=C() c.foos=5 print(c.foos) ___ mypy gives the following error: error: Incompatible types in assignment (expression has type "int", variable has type "List[int]") How do I turn around this? Changing def foos(self) -> list[int]: to def foos(self) -> Union[list[int]]: I meant, of course, def foos(self) -> Union[list[int],int]: Ohhh! I thought this was triggering a strange quirk of the checker in some way... Yes, these personal styles (?quirks) are off-putting to others. Plus "_" means (more or less) "not used anymore" and for most of us, a weak-identifier name such as "i" is indeed "an indexer/counter/... " Thank you for the suggestions. BTW, I am not a python pro programmer. I use it as a tool as many other tools and some other (few) languages. .. ...and whilst I'm griping, "To help us to help you please copy-paste the *exact* message" has been followed by: "I'm sorry. A bad transposition of the text." copy-paste for the win! (and to keep others happy to spend their voluntary time helping you - more working-with-the-team thinking to consider - please) The full original message was there. Seemed to me that that was obvious considering the simplicity of the subject and the illustrative toy example. Anyway, I'm sorry. Thank you. Paulo -- https://mail.python.org/mailman/listinfo/python-list
spyder does not work under root! [linux]
Hi! I need to debug a python3 script under root. I tried spyder but it does not work. Running as root without --no-sandbox is not supported. See https://crbug.com/638180. Thanks for any comments including alternative solutions to debug as root. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: spyder does not work under root! [linux]
Às 22:56 de 08/10/21, Paulo da Silva escreveu: > Hi! > > I need to debug a python3 script under root. I tried spyder but it does > not work. > > Running as root without --no-sandbox is not supported. See > https://crbug.com/638180. > > Thanks for any comments including alternative solutions to debug as root. > I also tried with eric and curiously it gave the same message!! This seems crazy. -- https://mail.python.org/mailman/listinfo/python-list
Assign a value to a var content in an object
Hello! Is there a better way of doing this? Why didn't setattr (as commented) work? Thanks for an help/comments. class C: def f(self,v): #setattr(self,n,v) self.__dict__['n']=v c=C() c.f(3) print(c.n) -- https://mail.python.org/mailman/listinfo/python-list
Re: Assign a value to a var content in an object
Às 23:28 de 10/10/21, Stefan Ram escreveu: > Paulo da Silva writes: >> class C: >>def f(self,v): >>#setattr(self,n,v) >>self.__dict__['n']=v > >> Why didn't setattr (as commented) work? > > Because the name n has not been initialized to a suitable > value in the function f. You could write > > setattr( self, "n", v ) Ah, OK - I missed the "" around n! :-( > > , but if you want this, > > self.n = v > > would be better. Of course :-) But that's not the purpose. This is just a toy example. Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: spyder does not work under root! [linux]
Às 22:54 de 11/10/21, Chris Angelico escreveu: > On Tue, Oct 12, 2021 at 8:52 AM Paulo da Silva > wrote: >> >> Hi! >> >> I need to debug a python3 script under root. I tried spyder but it does >> not work. >> >> Running as root without --no-sandbox is not supported. See >> https://crbug.com/638180. >> >> Thanks for any comments including alternative solutions to debug as root. >> > > Did you try reading the linked bug report? Or running it with --no-sandbox? > Yes. It is about a web browser! Why are 2 python debuggers related with a web browser?! As per spyder, there is no such switch --no-sandbox! Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: spyder does not work under root! [linux]
Às 02:08 de 12/10/21, Michael Torrie escreveu: > On 10/8/21 4:32 PM, Paulo da Silva wrote: >> Às 22:56 de 08/10/21, Paulo da Silva escreveu: >>> Hi! >>> >>> I need to debug a python3 script under root. I tried spyder but it does >>> not work. >>> >>> Running as root without --no-sandbox is not supported. See >>> https://crbug.com/638180. >>> >>> Thanks for any comments including alternative solutions to debug as root. >>> >> I also tried with eric and curiously it gave the same message!! >> >> This seems crazy. > > Not so crazy. It's incredibly dangerous to run a web browser as root. > There's no reason I can think of for running a python script driving a > web browser as root. spyder and eric are both python editors/debuggers! Why are they related with web browsers?! Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: spyder does not work under root! [linux]
Às 16:16 de 14/10/21, Mats Wichmann escreveu: > On 10/13/21 16:55, Michael Torrie wrote: >> On 10/13/21 12:09 PM, Paulo da Silva wrote: >>> spyder and eric are both python editors/debuggers! Why are they related >>> with web browsers?! >> >> Good point. I was going off of the chromium bug report. My bad. I >> mistook Spyder for Selenium, which is a web scraping scripting engine >> that does use a real browser. Oops. >> >> However, for better or worse, browser engines power all kinds of apps >> these days, including IDEs. I do not know if Spyder is powered by >> Chromium or not. VS Code, for example, is powered by a web browser >> engine. >> >> As to Eric and Qt, I can't speak to that. > > (sorry sent this wrong place first time) > > > The configuration dialog in eric uses its WebBrowser module, which uses > qtwebengine, which uses Chromium, which gives you the error. It's not a > Python error, fwiw. > > It seems there's an environment variable you can try in the Qt world > (I've never had occasion to check this out): > > https://forum.qt.io/topic/94721/running-as-root-without-no-sandbox-is-not-supported > Ok, thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: spyder does not work under root! [linux]
Às 23:55 de 13/10/21, Michael Torrie escreveu: > On 10/13/21 12:09 PM, Paulo da Silva wrote: >> spyder and eric are both python editors/debuggers! Why are they related >> with web browsers?! > > Good point. I was going off of the chromium bug report. My bad. I > mistook Spyder for Selenium, which is a web scraping scripting engine > that does use a real browser. Oops. > > However, for better or worse, browser engines power all kinds of apps > these days, including IDEs. I do not know if Spyder is powered by > Chromium or not. VS Code, for example, is powered by a web browser engine. > > As to Eric and Qt, I can't speak to that. Software starts to get sickly complicated these days :-( Thanks Michael and Peter. -- https://mail.python.org/mailman/listinfo/python-list
New assignmens ...
Hi! Why doesn't this work if (self.ctr:=self.ctr-1)<=0: while this works if (ctr:=ctr-1)<=0: Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: New assignmens ...
Às 20:34 de 22/10/21, Chris Angelico escreveu: > On Sat, Oct 23, 2021 at 6:24 AM Jon Ribbens via Python-list > wrote: >> >> On 2021-10-22, Stefan Ram wrote: >>> Paulo da Silva writes: >>>> Why doesn't this work >>>> if (self.ctr:=self.ctr-1)<=0: >>>> while this works >>>> if (ctr:=ctr-1)<=0: >>> >>> assignment_expression ::= [identifier ":="] expression, >>> but the attribute references "self.ctr" is no identifier! >> >> This seems a surprising omission. You'd expect at least 'attributeref' >> and 'subscription' to be allowed, if not the whole of 'target'. > > That's not the primary use-case for assignment expressions, and they > were highly controversial. It is much easier to expand it afterwards > than to restrict it, or to have the feature rejected because people > are scared of some small aspect of it. > > If you want to propose relaxing the restrictions, make your use-case > and attempt to convince people of the value. > Well, I didn't follow the discussion of this new feature, but the reason I can see behind allowing it seems so valid for for ctr:=ctr-1 as for self.ctr:=self.ctr-1. The kind of use is exactly the same. One is for a normal function, the other for a method. IMHO this makes no sense at all. Arguable may be for example LHS ctrs[i], or something like that. But self.ctr ...! Too weird. Thanks Paulo -- https://mail.python.org/mailman/listinfo/python-list
Avoid nested SIGINT handling
Hi! How do I handle a SIGINT (or any other signal) avoid nesting? Does this work? class STATUS: InInt=False def SIGINT_handler(sn,f): if STATUS.InInt: return STATUS.InInt=True process_int() STATUS.InInt=False Thanks for any suggestions. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Avoid nested SIGINT handling
Às 21:55 de 10/11/21, Jon Ribbens escreveu: > On 2021-11-10, Paulo da Silva wrote: >> Hi! >> >> How do I handle a SIGINT (or any other signal) avoid nesting? > > I don't think you need to. Python will only call signal handlers in > the main thread, so a handler can't be executed while another handler > is running anyway. > Do you mean that if I issue a ctrl+c while the previous one is "processing" it is held until, at least, the "processing" returns? -- https://mail.python.org/mailman/listinfo/python-list
Re: Avoid nested SIGINT handling
Às 06:22 de 11/11/21, Chris Angelico escreveu: > On Thu, Nov 11, 2021 at 5:01 PM Jon Ribbens via Python-list > wrote: >> >> On 2021-11-10, Paulo da Silva wrote: >>> Hi! >>> >>> How do I handle a SIGINT (or any other signal) avoid nesting? >> >> I don't think you need to. Python will only call signal handlers in >> the main thread, so a handler can't be executed while another handler >> is running anyway. > > Threads aren't the point here - signals happen immediately. > > Would it be easier to catch KeyboardInterrupt and do your processing > there, rather than actually catching SIGINT? > > I'd recommend just trying what you have, and seeing if it's reentrant. > My suspicion is that it isn't, on a technical level (the Python > function will be queued for when it's safe to call it - probably after > the next bytecode instruction), but that your own code will still need > to worry about reentrancy. > OK, thank you -- https://mail.python.org/mailman/listinfo/python-list
Unexpected behaviour of math.floor, round and int functions (rounding)
Hello, I would like to report the following issue: Working with floats i noticed that: int(23.99/12) returns 1, and int(23.999/12) returns 2 This implies that int() function is rounding, which doesn't appear to be expected (documentation doesn't say anything about it). Looking further i noticed that 0.5+0.49994 returns 1. This seems to be related to double numbers' operations in C language, where 0.49994 is the greatest floating-point value less than 0.5. Counting on this several examples can be deduced, like: round(0+0.49994) returns 0, and round(1+0.49994) returns 2 This seems to be a known issue in Java (see reference) Reference: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675 I hope this information is helpful, thanks in advance for reading this, Kind regards, René -- https://mail.python.org/mailman/listinfo/python-list
Writing a package
Hello! Let's say I have a dir src containing another dir named foo and a script test.py. So, I have src/foo (dir) src/test.py (script) test.py has the folloing code: import foo as f c=f.C() I am inside src and want to run python test.py. How can I create the class C inside src/foo dir if it is possible at all? Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Writing a package
Às 02:01 de 05/02/22, Cameron Simpson escreveu: On 05Feb2022 00:37, Paulo da Silva wrote: Let's say I have a dir src containing another dir named foo and a script test.py. So, I have src/foo (dir) src/test.py (script) test.py has the folloing code: import foo as f c=f.C() I am inside src and want to run python test.py. How can I create the class C inside src/foo dir if it is possible at all? Define it in the file "src/foo/__init__.py". When you go: import blah Python reaches for the file "blah.py" or "blah/__init__.py" (this second path is for "packages"). Yes, thank you. -- https://mail.python.org/mailman/listinfo/python-list
Unpacking lists in a f string
Hi! Let's say I have two lists of equal length but with a variable number of elements. For ex.: l1=['a','b','c'] l2=['j','k','l'] I want to build a string like this "foo a j, b k, c l bar" Is it possible to achieve this with f strings or any other simple/efficient way? Thanks for any help/comments. -- https://mail.python.org/mailman/listinfo/python-list
Re: Unpacking lists in a f string
Às 02:17 de 09/02/22, Paulo da Silva escreveu: Hi! Let's say I have two lists of equal length but with a variable number of elements. For ex.: l1=['a','b','c'] l2=['j','k','l'] I want to build a string like this "foo a j, b k, c l bar" Is it possible to achieve this with f strings or any other simple/efficient way? Thanks for any help/comments. Thank you for your responses. -- https://mail.python.org/mailman/listinfo/python-list
Append/Replace a row in a pandas DataFrame
Hi all. I am learning pandas DataFrame and I want to add (eventually replace by index) some rows. For adding here is what I tried: >df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) >df A B C D 2013-01-01 -0.111621 1.126761 -2.420517 0.660948 2013-01-02 -0.243397 -0.975684 -0.679209 -0.656913 2013-01-03 0.405816 0.478353 0.621906 -0.262615 2013-01-04 -0.380249 0.416711 -0.906286 1.828339 2013-01-05 0.772747 0.993784 0.452746 1.665306 2013-01-06 0.535011 -0.662874 1.504281 0.543537 [6 rows x 4 columns] >dft=pd.DataFrame([[1,2,3,4]], index=[datetime.date(2016,1,12)],columns=df.columns) >dft A B C D 2016-01-12 1 2 3 4 [1 rows x 4 columns] >pd.concat([df,dft]) Out[71]: A B C D 2013-01-01 00:00:00 -0.111621 1.126761 -2.420517 0.660948 2013-01-02 00:00:00 -0.243397 -0.975684 -0.679209 -0.656913 2013-01-03 00:00:00 0.405816 0.478353 0.621906 -0.262615 2013-01-04 00:00:00 -0.380249 0.416711 -0.906286 1.828339 2013-01-05 00:00:00 0.772747 0.993784 0.452746 1.665306 2013-01-06 00:00:00 0.535011 -0.662874 1.504281 0.543537 2016-01-12 1.00 2.00 3.00 4.00 [7 rows x 4 columns] Why am I getting the second column?! How do I do to have a row replaced instead of added if its date (index) is an existent one? Thanks for any help or comments. Paulo -- https://mail.python.org/mailman/listinfo/python-list
Re: Append/Replace a row in a pandas DataFrame [SOLVED]
Às 21:10 de 13-04-2016, Paulo da Silva escreveu: > Hi all. ... > [6 rows x 4 columns] > >> dft=pd.DataFrame([[1,2,3,4]], > index=[datetime.date(2016,1,12)],columns=df.columns) > >> dft > A B C D > 2016-01-12 1 2 3 4 > > [1 rows x 4 columns] > >> pd.concat([df,dft]) > Out[71]: > A B C D > 2013-01-01 00:00:00 -0.111621 1.126761 -2.420517 0.660948 > 2013-01-02 00:00:00 -0.243397 -0.975684 -0.679209 -0.656913 > 2013-01-03 00:00:00 0.405816 0.478353 0.621906 -0.262615 > 2013-01-04 00:00:00 -0.380249 0.416711 -0.906286 1.828339 > 2013-01-05 00:00:00 0.772747 0.993784 0.452746 1.665306 > 2013-01-06 00:00:00 0.535011 -0.662874 1.504281 0.543537 > 2016-01-12 1.00 2.00 3.00 4.00 > > [7 rows x 4 columns] > > Why am I getting the second column?! I need to use for example pd.datetime instead of datetime.date. In fact there is no extra col but the inclusion of hour in the index. Still don't understand why! > > How do I do to have a row replaced instead of added if its date (index) > is an existent one? df.loc[]= Paulo -- https://mail.python.org/mailman/listinfo/python-list
Creating a hot vector (numpy)
Hi all. I have seen this "trick" to create a hot vector. In [45]: x Out[45]: array([0, 1]) In [46]: y Out[46]: array([1, 1, 1, 0, 0, 1, 0, 0], dtype=uint8) In [47]: y[:,None] Out[47]: array([[1], [1], [1], [0], [0], [1], [0], [0]], dtype=uint8) In [48]: x==y[:,None] Out[48]: array([[False, True], [False, True], [False, True], [ True, False], [ True, False], [False, True], [ True, False], [ True, False]], dtype=bool) In [49]: (x==y[:,None]).astype(np.float32) Out[49]: array([[ 0., 1.], [ 0., 1.], [ 0., 1.], [ 1., 0.], [ 1., 0.], [ 0., 1.], [ 1., 0.], [ 1., 0.]], dtype=float32) How does this (step 48) work? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Creating a hot vector (numpy)
Às 05:05 de 18-04-2016, Reto Brunner escreveu: > Hi, > It is called broadcasting an array, have a look here: > http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html > So, there are two broadcasts here. OK. Thanks. -- https://mail.python.org/mailman/listinfo/python-list
A pickle problem!
Hi. Why in this code fragment self.__name is not kept between pickle dumps/loads? How to fix it? Thanks. import pickle import pandas as pd import numpy as np class C(pd.DataFrame): def __init__(self,name,*a,**b): super(C,self).__init__(*a,**b) self.__name=name def GetName(self): return self.__name dates = pd.date_range('20130101', periods=6) c = C("FOO",np.random.randn(6,4), index=dates, columns=list('ABCD')) cd=pickle.dumps(c,pickle.HIGHEST_PROTOCOL) d=pickle.loads(cd) d.GetName() # AttributeError: 'C' object has no attribute '_C__name' -- https://mail.python.org/mailman/listinfo/python-list
Re: A pickle problem!
Às 22:43 de 21-04-2016, Paulo da Silva escreveu: > Hi. > > Why in this code fragment self.__name is not kept between pickle > dumps/loads? How to fix it? > > Thanks. > > import pickle > import pandas as pd > import numpy as np > > class C(pd.DataFrame): > def __init__(self,name,*a,**b): > super(C,self).__init__(*a,**b) > self.__name=name > > def GetName(self): > return self.__name > # Adding this works but looks tricky! def __getstate__(self): dfstate=super(C,self).__getstate__() cstate=(dfstate,self.__name) return cstate def __setstate__(self,cstate): super(C,self).__setstate__(cstate[0]) self.__name=cstate[1] > > dates = pd.date_range('20130101', periods=6) > c = C("FOO",np.random.randn(6,4), index=dates, columns=list('ABCD')) > > cd=pickle.dumps(c,pickle.HIGHEST_PROTOCOL) > > d=pickle.loads(cd) > > d.GetName() > > # AttributeError: 'C' object has no attribute '_C__name' > -- https://mail.python.org/mailman/listinfo/python-list
Re: A pickle problem!
Às 17:27 de 22-04-2016, Ian Kelly escreveu: > On Thu, Apr 21, 2016 at 7:52 PM, Paulo da Silva > wrote: >> Às 22:43 de 21-04-2016, Paulo da Silva escreveu: ... > > Probably this is necessary because the DataFrame class is already > customizing its pickle behavior without taking into account the > possibility of added attributes by subclasses. I think that your > solution of wrapping the state of the superclass looks fine. > Thank you. For any other vars ... Is there a way to get the vars of only the derived class? -- https://mail.python.org/mailman/listinfo/python-list
Re: A pickle problem!
Às 21:33 de 22-04-2016, Ian Kelly escreveu: > On Fri, Apr 22, 2016 at 2:21 PM, Paulo da Silva > wrote: ... > > If they start with two underscores then you could use the name > mangling to find them. If the class name is MyClass then look for any > keys in the instance dict that start with '_MyClass__'. Otherwise no, > you'd have to list them explicitly. > OK, thanks. -- https://mail.python.org/mailman/listinfo/python-list
A problem with classes - derived type
Hi! Suppose I have a class A whose implementation I don't know about. That class A has a method f that returns a A object. class A: ... def f(self, <...>): ... Now I want to write B derived from A with method f1. I want f1 to return a B object: class B(A): ... def f1(self, <...>): ... res=f(<...>) How do I return res as a B object? Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: A problem with classes - derived type
Às 05:20 de 09-05-2016, Paulo da Silva escreveu: Thank you Yann and Peter. I really didn't know anything about those "things". So far I have worked a lot with classes but they are written by me. Now I needed to derive pandas.Series (for example) and it has some methods that return pandas.Series objects. And I needed to return the derived object, not the pandas.Series one. The problem is now fixed. I'll find some time to read a little more about this to improve my pyhon knowledge. Thank you very much. -- https://mail.python.org/mailman/listinfo/python-list