Re: Python & Sybase
Chris, There are few more, depending which sybase database. More info on this link: http://wiki.python.org/moin/Sybase Cheers, Ivan On Thu, Apr 14, 2011 at 6:36 AM, Dan Stromberg wrote: > http://www.freetds.org/ > > There's likely also one you could get from your database admin. > > On Wed, Apr 13, 2011 at 8:40 AM, Chris M. Bartos > wrote: > > Hi, > > > > Are there any database drivers that allows Python to connect to remote > > Sybase Databases. > > I tried python-sybase, but somehow couldn't get it to connect remotely, > only > > locally...? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: My Issues
Hi Carson, If you are having big troubles installing Python on Windows (it really should be a click install from the Python download page here https://www.python.org/downloads/) you can use Anaconda to install, which usually makes installing python on problematic windows machines much easier. Follow this tutorial https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444 Use this download page: https://www.anaconda.com/download/ Don't get discouraged. Sometimes getting up and running is a bit of a pain, but it will be smooth sailing after you get it in there the first time. Ivan -- https://mail.python.org/mailman/listinfo/python-list
How to support a non-standard encoding?
Dear All I'm developing a python application for which I need to support a non-standard character encoding (specifically ISO 6937/2-1983, Addendum 1-1989). Here are some of the properties of the encoding and its use in the application: - I need to read and write data to/from files. The file format includes two sections in different character encodings (so I shan't be able to use codecs.open()). - iso-6937 sections include non-printing control characters - iso-6937 is a variable width encoding, e.g. "A" = [41], "Ä" = [0xC8, 0x41]; all non-spacing diacritical marks are in the range 0xC0-0xCF. By any chance is there anyone out there working on iso-6937? Otherwise, I think I need to write a new codec to support reading and writing this data. Does anyone know of any tutorials or blog posts on implementing a codec for a non-standard characeter encoding? Would anyone be interested in reading one? With thanks and best wishes Ivan -- ==== Ivan A. Uemlianin Llaisdy Speech Technology Research and Development i...@llaisdy.com www.llaisdy.com llaisdy.wordpress.com github.com/llaisdy www.linkedin.com/in/ivanuemlianin "Froh, froh! Wie seine Sonnen, seine Sonnen fliegen" (Schiller, Beethoven) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to support a non-standard encoding?
Dear jmf, Tim Thanks for these pointers. They look v useful. I'll have a go and report back (with success I hope). Best wishes Ivan On 06/01/2012 20:42, Tim Wintle wrote: On Fri, 2012-01-06 at 12:00 -0800, jmfauth wrote: The distibution of such a codec may be a problem. There is a register_codec method (or similar) in the codecs module. Tim -- Ivan A. Uemlianin Llaisdy Speech Technology Research and Development i...@llaisdy.com www.llaisdy.com llaisdy.wordpress.com github.com/llaisdy www.linkedin.com/in/ivanuemlianin "Froh, froh! Wie seine Sonnen, seine Sonnen fliegen" (Schiller, Beethoven) -- http://mail.python.org/mailman/listinfo/python-list
Perl / python regex / performance comparison
Hello everyone, I know this is not a direct python question, forgive me for that, but maybe some of you will still be able to help me. I've been told that for my application it would be best to learn a scripting language, so I looked around and found perl and python to be the nice. Their syntax and "way" is not similar, though. So, I was wondering, could any of you please elaborate on the following, as to ease my dilemma: 1. Although it is all relatively similar, there are differences between regexes of these two. Which do you believe is the more powerful variant (maybe an example) ? 2. They are both interpreted languages, and I can't really be sure how they measure in speed. In your opinion, for handling large files, which is better ? (I'm processing files of numerical data of several hundred mb - let's say 200mb - how would python handle file of such size ? As compared to perl ?) 3. This last one is somewhat subjective, but what do you think, in the future, which will be more useful. Which, in your (humble) opinion "has a future" ? Thank you for all the info you can spare, and expecially grateful for the time in doing so. -- Ivan -- http://mail.python.org/mailman/listinfo/python-list
Perl-python regex-performance comparison
Hello everyone, I know this is not a direct python question, forgive me for that, but maybe some of you will still be able to help me. I've been told that for my application it would be best to learn a scripting language, so I looked around and found perl and python to be the nice. Their syntax and "way" is not similar, though. So, I was wondering, could any of you please elaborate on the following, as to ease my dilemma: 1. Although it is all relatively similar, there are differences between regexes of these two. Which do you believe is the more powerful variant (maybe an example) ? 2. They are both interpreted languages, and I can't really be sure how they measure in speed. In your opinion, for handling large files, which is better ? (I'm processing files of numerical data of several hundred mb - let's say 200mb - how would python handle file of such size ? As compared to perl ?) 3. This last one is somewhat subjective, but what do you think, in the future, which will be more useful. Which, in your (humble) opinion "has a future" ? Thank you for all the info you can spare, and expecially grateful for the time in doing so. -- Ivan -- http://mail.python.org/mailman/listinfo/python-list
Perl-python regex-performance comparison
Hello everyone, I know this is not a direct python question, forgive me for that, but maybe some of you will still be able to help me. I've been told that for my application it would be best to learn a scripting language, so I looked around and found perl and python to be the nice. Their syntax and "way" is not similar, though. So, I was wondering, could any of you please elaborate on the following, as to ease my dilemma: 1. Although it is all relatively similar, there are differences between regexes of these two. Which do you believe is the more powerful variant (maybe an example) ? 2. They are both interpreted languages, and I can't really be sure how they measure in speed. In your opinion, for handling large files, which is better ? (I'm processing files of numerical data of several hundred mb - let's say 200mb - how would python handle file of such size ? As compared to perl ?) 3. This last one is somewhat subjective, but what do you think, in the future, which will be more useful. Which, in your (humble) opinion "has a future" ? Thank you for all the info you can spare, and expecially grateful for the time in doing so. -- Ivan p.s. Having some trouble posting this. If you see it come out several times, please ignore the copies. -- http://mail.python.org/mailman/listinfo/python-list
Perl python - regex performance comparison
Hello everyone, I know this is not a direct python question, forgive me for that, but maybe some of you will still be able to help me. I've been told that for my application it would be best to learn a scripting language, so I looked around and found perl and python to be the nice. Their syntax and "way" is not similar, though. So, I was wondering, could any of you please elaborate on the following, as to ease my dilemma: 1. Although it is all relatively similar, there are differences between regexes of these two. Which do you believe is the more powerful variant (maybe an example) ? 2. They are both interpreted languages, and I can't really be sure how they measure in speed. In your opinion, for handling large files, which is better ? (I'm processing files of numerical data of several hundred mb - let's say 200mb - how would python handle file of such size ? As compared to perl ?) 3. This last one is somewhat subjective, but what do you think, in the future, which will be more useful. Which, in your (humble) opinion "has a future" ? Thank you for all the info you can spare, and expecially grateful for the time in doing so. -- Ivan p.s. Having some trouble posting this. If you see it come out several times, please ignore the copies. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: File-writing not working in Windows?
John Machin ?: On Jun 7, 1:18 am, [EMAIL PROTECTED] wrote: Assume nothing. Don't believe anyone who says "always". Insert some print statements and repr() calls to show what's actually there. I hope however that it's something obvious that a Python guru here will be able to spot and that this n00b is missing! *IF* the problem is in the code, it would be easier to spot if you had removed large chunks of indentation before posting. Less is more: change "if (foo == 2):" to "if foo == 2:", "foo == True" to "foo", and "foo == False" to "not foo". Browse http://www.python.org/dev/peps/pep-0008/ HTH, John Hello, I tried os.path.join() under Windows XP and everything works as expected. The problem is in your script. You may use logger or use additional checks (John Machin wrote about this practice). TBRDs, Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-by-example - new online guide to Python Standard Library
Very cool. Have you thought about making a printable version that doesn't wrap any lines that shouldn't be and has page breaks at good spots? -- ivan -- http://mail.python.org/mailman/listinfo/python-list
Tix.HList - Move Cursor
Hello, How do I move the keyboard cursor position in a Tix.HList? I am using an HList with the right mouse button bound to pop up a menu. If the right click is done on an unselected item, I change the selection to that item. This works, however the keyboard cursor position remains at the last item selected with arrow keys or left click. How can I move this as well as the selection? def onrightclick(event): rightselected=hlist1.nearest(event.y) if hlist1.selection_includes(rightselected) <> "0": callpopup(rightselected) else: hlist1.selection_clear() hlist1.selection_set(rightselected) callpopup(rightselected) hlist1.bind("", onrightclick) Thanks, Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 3:47 pm, "Jerry Hill" <[EMAIL PROTECTED]> wrote: > When you run your code in pythonwin, it's just like calling 'python -i > chap2.py' It runs the code in chap2.py, then gives you an interpreter > window to interact with your code. In this case, that means that > FooClass is visible with no import at all, because it was defined in > the scope of the currently running script, as opposed to being > imported. > > You haven't said exactly how you're doing this on your mac, but I'm > guessing that you're opening a command line, starting up the python > interpreter, then going from there? > > Can someone help me out? I'm running into a mental block on how to > explain the difference between doing this: > C:\Python25>python -i chap2.py>>> foo1=FooClass() jmDesktop, With what Jerry stated, You can see what is happening under PythonWin interactive window by doing: >>> dir() before and after running chap2.py and see that FooClass is defined without import, which gives a clue that PythonWin is not running the script independant of the interactive window. Or try adding the following to the end of your chap2.py: print "Hello World" somevar = 12345 And run in PythonWin and see what happens to your interactive window and if somevar is defined. If you close and open PythonWin and use the interactive window without having first run chap2.py, you will find it behaves the same as the mac. Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonwin
Not related (except that it is about python and ArcGIS): Remember you can set PYTHONINSPECT to enter interactive mode at the end of a script. With a script set as an ArcGIS tool, you can then enter interactive to play around or debug with all the ArcGIS stuff loaded. Is there a better way people do this? Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: another language with classes?
> R Kantas writes: [Cross-posting to news:comp.lang.python, news:comp.lang.scheme, looking for more first-hand experience with these. Sadly, there's no news:comp.lang.go as of yet.] > I came into first contact with objects and classes programming under > Visual Basic 5/6 (VB classic) and found theese capabilities were > useful for efficient programming. Now, as this VB is no longer > supported by Microsoft I'm going to switch to another language, and > my question is which other of the popular programming lnguages has > such a construct like VB's classes where code and data can be > completely separated from the rest of the program, so that very handy > reusable code components can be created. I've had only a passing experience with VB, and even then, it dates back to the mid-1990'es, so I may not understand what exactly you're asking for, but my understanding is that most of the contemporary high-level languages, both compiled and not, offer comparable facilities. In particular, Go [1] appears to offer a simple yet powerful OO system, and even though it's still a very new language (introduced in 2009), it already has an extensive library, and offers the compiled code's performance comparable to that of C. The other popular choice is Python [2], and the one I'd like to investigate myself is Racket [3] (which is a dialect of Scheme, which in turn is a dialect of Lisp.) [1] https://en.wikipedia.org/wiki/Go_(programming_language) [2] https://en.wikipedia.org/wiki/Python_(programming_language) [3] https://en.wikipedia.org/wiki/Racket_(programming_language) [...] -- FSF associate member #7257 np. hcss.mod -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Python script as SMTP server for outgoing e-mails?
> Gilles writes: > On Sun, 21 Jul 2013 11:46:52 -0600, Michael Torrie wrote: [Cross-posting to news:comp.mail.misc.] >> What you're looking for is not an SMTP server but a Mail Transfer >> Agent, called an MTA. [...] >> Dennis is correct, though, that most ISPs do block outbound port 25 >> connections for security and spam reasons, and require you to use >> their SMTP server, which precludes the use of the local MTA. > I'm not sure my ISP blocks outbound port 25 connections. I'll > experiment with a small Linux box. There's yet another issue: certain email "operators" may block /inbound/ port 25 connections from ISP "customer" networks. > I wist they would use a smarter SPAM filter that wouldn't flag > perfectly legit-looking outgoing e-mails. FWIW, it may also be possible to use an email service (such as Google Mail) provided by a third-party. -- FSF associate member #7257 -- http://mail.python.org/mailman/listinfo/python-list
Re: My first ever Python program, comments welcome
On 21.07.2012 21:08, Lipska the Kat wrote: Greetings Pythoners A short while back I posted a message that described a task I had set myself. I wanted to implement the following bash shell script in Python Here's the script sort -nr $1 | head -${2:-10} this script takes a filename and an optional number of lines to display and sorts the lines in numerical order, printing them to standard out. if no optional number of lines are input the script prints 10 lines Here's the file. 50Parrots 12Storage Jars 6Lemon Currys 2Pythons 14Spam Fritters 23Flying Circuses 1Meaning Of Life 123Holy Grails 76Secret Policemans Balls 8Something Completely Differents 12Lives of Brian 49Spatulas ... and here's my very first attempt at a Python program I'd be interested to know what you think, you can't hurt my feelings just be brutal (but fair). There is very little error checking as you can see and I'm sure you can crash the program easily. 'Better' implementations most welcome #! /usr/bin/env python3.2 import fileinput from sys import argv from operator import itemgetter l=[] You can do without this, see below. t = tuple This initialization does nothing. Assignment t=(line.split('\t')) makes `t` a list (not a tuple), discarding any previous value. And you don't really need t: with fileinput.input(files=(filename)) as f: for line in f: t=(line.split('\t')) t[0]=int(t[0]) l.append(t) List comprehension is your friend, and now you don't need to initialize l to an empty list. with open(filename) as f: l = [line.split('\t') for line in f] The first element of each row is now a string, but it's easy to fix: l=sorted(l, key=itemgetter(0)) Use in-place sorting and cast the sorting element to int l.sort(key=lambda t: int(t[0])) inCount = int(argv[2]) lineCount = inCount lineCount = int(argv[2]) works just fine for c in range(lineCount): t=l[c] print(t[0], t[1], sep='\t', end='') Whenever you write "for i in range(n)" you're (probably) doing it wrong. Here you can use list slicing, and as a bonus the program doesn't bomb when lineCount is greater than length(l) for t in l[:lineCount]: print(t[0], t[1], sep='\t', end='') -- http://mail.python.org/mailman/listinfo/python-list
Re: Functional way to compare things inside a list
On 21.09.2012 00:58, thorso...@lavabit.com wrote: Hi, list = [{'1': []}, {'2': []}, {'3': ['4', '5']}] I want to check for a value (e.g. '4'), and get the key of the dictionary that contains that value. (Yep, this is bizarre.) some_magic(list, '4') => '3' What's the functional way to do it? Is it possible to do it with a one-liner? Yes: [key for d in list for key in d if '4' in d[key]] -- http://mail.python.org/mailman/listinfo/python-list
Wgy isn't there a good RAD Gui tool fo python
Ok Guys. I know that most of us have been expiriencing the need for a nice Gui builder tool for RAD and most of us have been googling for it a lot of times. But seriously. Why is the not even one single RAD tool for Python. I mean what happened to boa constructor that it stopped developing. I simply do not see any reasons why there isn't anything. Please help me understand it. Any insights? -- http://mail.python.org/mailman/listinfo/python-list
Re: Wgy isn't there a good RAD Gui tool fo python
Ok. I asked about this questio because I am working with python for the last 5 years and I am always in touch about signifigact things in Python. I am pissed of that I make my living by developing applications at work in Java an C#. My comPany would switch to python but they complained that there is not even one single gui builder or framework that can allow it to make a living from it. If you are going to say that there are also other libraries with every single one there is a significant problem that make the development painfull. About the natural selection... I'll say it with the words of penn&teller:bullshit For how many years are this vui library wars going on. How many. Look. I am a open source supporter but Windows will always kick the ass of open source because the open source comunity can not make a decision. Just imagine what we would have today if the effort of development would have been used to develop one really good library. We would have kicked the ass of MS and steve balmer. The average user wants something simple and not something to program to do something. It looks that the firs linux os to realize that is successfull. I am talking about android. And the python development team is doing nothing to improve the situatio to solve this dispute that lasts for the last years by including the worthless Tk library and now upgrading it with Tix. To summarize it. It would be very helpfull for python to spread if there qould be one single good rad gui builder similar to vs or netbeAns but for python. So right now if i need to make a gui app i need to work with an applicatio that is dicontinued for the last 5 years is pretty buggy but is ok. If it would only be maintained and the libraby updated it would be great. When it comes to other application, sorry but they are just bad. Their userfriendlyness is simmilar to most of Ms products, they are "user friendly" but the problem is that they very wisely chose their friends. The ony worthly ones mentioning as an gui builder are boa constructor fo wx, qtDesigner with the famous licence problems why companies do not want to work with it, sharpdevelop for ironpython and netbeans for jython. Did you notice that 2 of these 4 are not for python? One is out of dTe and one has a fucked up licence. Sorry guys but there is not even one single rad gui tool for python as long as there is no serious guibuilder. -- http://mail.python.org/mailman/listinfo/python-list
Property for dataclass field with default value
Hello All, I have some trouble using @dataclass together with @property decorator or property() function. >From the documentation and PEP is seems that the intended behaviour of @dataclass is to be the same as normal __init__() that sets instance variables. But it seems that when using @property decorator some parts work differently when relying on default values. I'm using Pyhton 3.8.3 for this. Using the code: from dataclasses import dataclass @dataclass class Container: x: int = 30 @property def x(self) -> int: return self._x @x.setter def x(self, z: int): if z > 1: self._x = z else: raise ValueError c= Container(x=10) print(c) c= Container() print(c) output is: Container(x=10) Traceback (most recent call last): File "/Users/ivanivanyuk/Documents/Shared/repos/bitbucket/evbox/g5plus-automated-testing/dataclass_example.py", line 18, in c= Container() File "", line 3, in __init__ File "/Users/ivanivanyuk/Documents/Shared/repos/bitbucket/evbox/g5plus-automated-testing/dataclass_example.py", line 13, in x if z > 1: TypeError: '>' not supported between instances of 'property' and 'int' Code with __init__() being inserted that should be roughly the same as generated by the @dataclass decorator: @dataclass class Container: x: int = 30 def __init__(self, x:int = 30): self.x = x @property def x(self) -> int: return self._x @x.setter def x(self, z: int): if z > 1: self._x = z else: raise ValueError c= Container(x=10) print(c) c= Container() print(c) output is: Container(x=10) Container(x=30) As far as I can see, this happens because actual __init__() generated by the @dataclass decorator looks like: def __init__(self, x:int = ): self.x = x I came up with a really convoluted way to work around it (just for fun, as this clearly defies the idea of dataclasses as a way to decrease boilerplate code): from dataclasses import dataclass, field def set_property(): Container.x = property(Container.get_x, Container.set_x) return 30 @dataclass class Container: x: int = field(default_factory=set_property) def get_x(self) -> int: return self._x def set_x(self, z: int): if z > 1: self._x = z else: raise ValueError c= Container(x=10) print(c) c= Container() print(c) output is: Container(x=10) Container(x=30) So, what I'm missing here? Is there some way to use field() or decorators to make property just work the same as in non-decorated class? Best regards, Ivan Ivanyuk -- https://mail.python.org/mailman/listinfo/python-list
Re: Property for dataclass field with default value
On Thu, 18 Jun 2020 at 11:26, Peter Otten <__pete...@web.de> wrote: > > Ivan Ivanyuk wrote: > > > Hello All, > > > > I have some trouble using @dataclass together with @property decorator > > or property() function. > > > > From the documentation and PEP is seems that the intended behaviour of > > @dataclass is to be the same as normal __init__() that sets instance > > variables. > > > > But it seems that when using @property decorator some parts work > > differently when relying on default values. I'm using Pyhton 3.8.3 for > > this. > > > > Using the code: > > > > from dataclasses import dataclass > > > > @dataclass > > class Container: > > x: int = 30 > > > > @property > > def x(self) -> int: > > return self._x > > > > @x.setter > > def x(self, z: int): > > if z > 1: > > self._x = z > > else: > > raise ValueError > > c= Container(x=10) > > print(c) > > c= Container() > > print(c) > > > > output is: > > > > Container(x=10) > > Traceback (most recent call last): > > File > > "/Users/ivanivanyuk/Documents/Shared/repos/bitbucket/evbox/g5plus- > automated-testing/dataclass_example.py", > > line 18, in > > c= Container() > > File "", line 3, in __init__ > > File > > "/Users/ivanivanyuk/Documents/Shared/repos/bitbucket/evbox/g5plus- > automated-testing/dataclass_example.py", > > line 13, in x > > if z > 1: > > TypeError: '>' not supported between instances of 'property' and 'int' > > > > Code with __init__() being inserted that should be roughly the same as > > generated by the @dataclass decorator: > > > > @dataclass > > class Container: > > x: int = 30 > > > > def __init__(self, x:int = 30): > > self.x = x > > > > @property > > def x(self) -> int: > > return self._x > > > > @x.setter > > def x(self, z: int): > > if z > 1: > > self._x = z > > else: > > raise ValueError > > > > c= Container(x=10) > > print(c) > > c= Container() > > print(c) > > > > output is: > > Container(x=10) > > Container(x=30) > > > > As far as I can see, this happens because actual __init__() generated > > by the @dataclass decorator looks like: > > > > def __init__(self, x:int = ): > > self.x = x > > > > I came up with a really convoluted way to work around it (just for > > fun, as this clearly defies the idea of dataclasses as a way to > > decrease boilerplate code): > > > > from dataclasses import dataclass, field > > > > def set_property(): > > Container.x = property(Container.get_x, Container.set_x) > > return 30 > > > > @dataclass > > class Container: > > x: int = field(default_factory=set_property) > > > > def get_x(self) -> int: > > return self._x > > > > def set_x(self, z: int): > > if z > 1: > > self._x = z > > else: > > raise ValueError > > > > c= Container(x=10) > > print(c) > > c= Container() > > print(c) > > > > output is: > > Container(x=10) > > Container(x=30) > > > > So, what I'm missing here? Is there some way to use field() or > > decorators to make property just work the same as in non-decorated > > class? > > Your class definition is basically > > class Container: > x = default_value > x = property_x > > i. e. you use the same name twice. A possible workaround might be to define > the property in a subclass. That way you get distinct namespaces for the > default value and the property: > > @dataclass > class ContainerBase: > x: int = 42 > > class Container(ContainerBase): > @property > def x(self): > return self._x > > @x.setter > def x(self, value): > if value <= 1: > raise ValueError > self._x = value > > > -- > https://mail.python.org/mailman/listinfo/python-list Didn't think about it in such a way! But now that it was pointed, I see no obvious way to resolve this in dataclass decorator given the way it's implemented now. And while adding another class looks easy it somewhat detracts from the dataclasses' purpose of removing boilerplate. Does it seems like a good idea to ask for documenting that behaviour in dataclasses documentation or it's not popular enough use case? Regards, Ivan -- https://mail.python.org/mailman/listinfo/python-list
Re: How to decompile an exe file compiled by py2exe?
Thomas Jollans wrote: > interpreter. This is based on the assumption that py2exe really > generates a pure exe and not an exe that interprets bytecode python. > be that the case, it may yield decent results, but ugly nontheless. It is - py2exe embeds python bytecodes. It seems it does it in the "library.zip" file (if I'm reading http://starship.python.net/crew/theller/moin.cgi/Py2Exe correctly). Bytecode files extracted should be decompilable to something resembling original python code by a python decompiler (quick Googling finds "decompyle": http://www.crazy-compilers.com/). -- http://mail.python.org/mailman/listinfo/python-list
Re: Using '__mul__' within a class
Gerard Flanagan wrote: > def Square( self ): > self *= self You probably mean return self * self > A = FibonacciMatrix() > A.Square() Make this A = A.Square() -- http://mail.python.org/mailman/listinfo/python-list
Carrying variables over from function to function
Alright heres my problem. . .Say I want to carry over a variable from one function to another or even another run of the same function. Is that possible? Heres a quick example of what I'm talking about. def abc(): x = 1 y = x + 1 print y def abcd(): y = x + 1 print y abc() abcd() the output would be: abc() 2 abcd() Traceback (most recent call last): File "(stdin)", line 1, in ? File "(stdin)", line 2, in abcd NameError: global name 'x' is not defined See, I want y in the second function to equal 4, carrying the x from the first function over to the next. Is there any way to do this? -Ivan _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Carrying variables over from function to function
Thanks for your quick responce Roy, thats exactly what I needed. =) -Ivan _ On the road to retirement? Check out MSN Life Events for advice on how to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement -- http://mail.python.org/mailman/listinfo/python-list
Help with syntax warnings
Here's a noob question for everyone (I'm not sure if my first message got through, is had a "suspicious header" so sorry for double post is so), is there a way to turn off syntax warnings or just make them not visible? Thanks, -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Turning off syntax warnings?
Here's a noob question for everyone which i can't seem to find the answer to on google. . .Is there a way to turn off syntax warnings? -Ivan _ FREE pop-up blocking with the new MSN Toolbar get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with syntax warnings
Well I've been experimenting with the warning filter and it doesn't seem to be working. . .I think it has something to do with the fact that warnings are issued during the compiling and not during the excecution. . .So the filter would come in to late to block them? Any ideas? -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Class Help
To continue with my previous problems, now I'm trying out classes. But I have a problem (which I bet is easily solveable) that I really don't get. The numerous tutorials I've looked at just confsed me.For intance: >>>class Xyz: ... def y(self): ... q = 2 ... >>>Xyz.y() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method y() must be called with Xyz instance as first argument (got nothing instead) So. . .What do I have to do? I know this is an extremley noob question but I think maybe if a person explained it to me I would finally get it =/ thanks in advance, -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI Script
Efrat, I am afraid a CGI script is never *executed* by the browser. Instead, it sends the URL to a server, expects the server to execute the script, and display the server's response. If you just put a file name then (it seems, I never even tried that) Firefox uses the local file store as a 'server' in that respect. If you want to test a CGI script on your own machine, you should run a web server on your own machine. That server should also be set up in a way that it recognizes a '.py' file as a CGI script to be executed by Python (not all servers may recognize the #! trick...). This may look scary, but it is not that bad. Apache has a number of precompiled binary versions that you can install on your machine; you can also use servers like W3C's jigsaw (this relies on Java) or others. These are all free and easy to install and, well, manageable to configure. Actually, in case you run on a MacOS X by any chance, Apache is already installed afaik... I hope this helps Ivan Original Message From: Efrat Regev <[EMAIL PROTECTED]> To: Subject: Python CGI Script Date: 30/9/2005 12:50 > Hello, > > I'm a data-structures course TA trying to write a python CGI script > for automatically compiling and testing students' projects. > Unfortunately, I've run into some questions while writing this, which I > couldn't solve with the various (and helpful) python-CGI documentation. > (It's possible that I'm posting to the wrong group; if so, I'd > appreciate suggestions for the appropriate group.) > > > 1. In my HTML page, I have the following: > > enctype="multipart/form-data"> > ... > > > In the above, submission_processor.py is the python CGI script. I > didn't write a URL in the action field, since I'm first testing > everyting on a local machine (running FC4). The first line of > submission_processor.py is > > #!/usr/bin/python > > and I've done > > chmod +x submission_processor.py > > When I hit the "submit" button, my browser (Firefox on FC4) doesn't > run the script; it asks me whether it should open > submission_processor.py or save it to disk. I couldn't figure out why. > > 2. My HTML page has the option for an instructor to list the various > submissions and scores. Obviously, this should be inaccessible to > students. The instructor has a password for doing this, therefore. > Suppose I place the password inside a python script, and give this > script only +x permission for others. Is this adequate as far as security? > > > Thanks in advance for answering these questions. > > > Efrat -- http://mail.python.org/mailman/listinfo/python-list
Re: Class Help
Thanks everyone for helping me out and tolerating the noob question =D The last part was confusing to me and thanks for explaining it so I get it! -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
noob question Letters in words?
Alright heres another noob question for everyone. Alright, say I have a menu like this. print "1. . .Start" print "2. . .End" choice1 = raw_input("> ") and then I had this to determine what option. if choice1 in ('1', 'Start', 'start'): #do first option if choice1 in ('2', 'End', 'end'): #do second option Is there a way (I searched for a module but didnt find one) that I can do something like this? if choice1 in ('1', 'S', 's'): #do first option if choice1 in ('2', 'E', 'e'): #do second option For instance I could type in Stop and would get the first option since it had an "s" in it? Anyone heard of any way to do this? Thanks, -Ivan By the way, if anyone gets tired of my persistant noob questions please tell me I don't want to bother anyone =D _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question Letters in words?
>Perhaps a better idea is to present the user with a choice that cannot >be deviated from, along the lines of... > >def main(): > print "1.\tStart" > print "2.\tSomething Else" > print "3.\tStop" > > x = raw_input() > if x is '1': print 'Start' > elif x is '2': print 'Something else' > elif x is '3': print 'End' > else: main() Right but see what if the user wants to type Start? I've already used the number menu but too many people get confused by it. . .Any other ideas? Thanks, -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question Letters in words?
Yes, I realize that. . .Heres another question then. I was trying somehting before so that if the user just pressed enter by accident, it would not accept the input and ask them to put in another. But the thing is I couldnt get it to work. I tryed if choice1 == None it would loop and ask for a new input but that didnt seem to work. . .Any ideas for that? Thanks, Ivan _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question Letters in words?
>Is it *really* a good idea if the user types "STOP!!!" and it has the >same effect as if they typed "Start please"? > >I've heard of "Do what I mean, not what I said" systems, which are usually >a really bad idea, but this is the first time I've seen a "Do what I don't >mean, not what I said" system. =D Alright, I'm going to stop trying to defend my idea since it's obviously a bad one. What do you recommend? -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob question Letters in words?
Thanks everyone for helping once again, lots of good ideas there Thanks, -Ivan _ FREE pop-up blocking with the new MSN Toolbar get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie needs help. Setting PYTHONDOCS to read HTML.
You can still use it, but you can't use the help. I don't know but this has always been better than the help for me! =D-- -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Let My Terminal Go
Mike Meyer wrote: > The easy way to do all these things - from C, anyway - is with > daemon(3). That isn't wrapped as part of the Python library. The > easiest way to solve your problem may be write a wrapper for that > call. If daemon exists on enough systems, submitting your wrapper as a > patch to the os modulee would be appropriate. I think the deamon() library call only exists on the BSDs. Anyway, there it is implemented with a fork() call and some additional code to close std descriptors, so there's no practical difference between calling deamon() and fork() by yourself... -- http://mail.python.org/mailman/listinfo/python-list
Re: Yes, this is a python question, and a serious one at that (moving to Win XP)
On 10/14/05, Peter Hansen <[EMAIL PROTECTED]> wrote: Christian Stapfer wrote:> 0.0. ... and add an item to your SendTo folder that allows> you to have Windows Explorer open a terminal window with its> current directory set to the currently displayed folder > (= "Open terminal here").Or install the "Command Prompt Here" gadget that MS produces, which hasa massive installer and a click-through license thing and everything,just to open a freakin' prompt at a given directory -PeterThere's an excellent windows registry edit to open a command prompt at the given directory that I've been using. . .Here's a link. http://www.winguides.com/registry/display.php/260/Hope that helps,-Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: WTF?
On 11/1/05, James Stroud <[EMAIL PROTECTED]> wrote: Why do my posts get held for suspcious headers and troll Xha Lee gets to postall sorts of profanity and ranting without any problem?--James StroudUCLA-DOE Institute for Genomics and ProteomicsBox 951570 Los Angeles, CA 90095http://www.jamesstroud.com/--http://mail.python.org/mailman/listinfo/python-list Hey man I feel your pain. Happens to me all the time. -- http://mail.python.org/mailman/listinfo/python-list
Re: putting an Icon in "My Computer"
On 3 Nov 2005 18:28:49 -0800, Brett Hoerner <[EMAIL PROTECTED]> wrote: > I've been asked by my boss to put an Icon in WinXP's "My Computer" for> a utility we use around the shop. My tool of choice is of course > Python and therefore what I am using to attempt my given task. I have> no trouble putting Icons in the WinXP Toolbar using Python, but have> totally failed to get an Icon to appear in My Computer. Any Idea on > why and maybe how to get around this using Python?I'm pretty sure the My Computer menu is limited to devices and specialWindows folders like My Documents, etc. I've never seen a program addan icon there, and I don't think its allowed through the API. --http://mail.python.org/mailman/listinfo/python-list If this can be achieved at all, it would be through the windows registry. I know you can change all the icons for the recycle bin and special folders through it. . .I would figure adding folders might even be under the same key. Try google. -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: putting an Icon in "My Computer"
On 11/3/05, Ivan Shevanski <[EMAIL PROTECTED]> wrote: On 3 Nov 2005 18:28:49 -0800, Brett Hoerner < [EMAIL PROTECTED]> wrote: > I've been asked by my boss to put an Icon in WinXP's "My Computer" for> a utility we use around the shop. My tool of choice is of course > Python and therefore what I am using to attempt my given task. I have> no trouble putting Icons in the WinXP Toolbar using Python, but have> totally failed to get an Icon to appear in My Computer. Any Idea on > why and maybe how to get around this using Python?I'm pretty sure the My Computer menu is limited to devices and specialWindows folders like My Documents, etc. I've never seen a program addan icon there, and I don't think its allowed through the API. --http://mail.python.org/mailman/listinfo/python-list If this can be achieved at all, it would be through the windows registry. I know you can change all the icons for the recycle bin and special folders through it. . .I would figure adding folders might even be under the same key. Try google. -Ivan Actually, this link might just be what you need. http://www.winguides.com/registry/display.php/73/ Hope that helps,-Ivan -- http://mail.python.org/mailman/listinfo/python-list
Can somebody help compiling 'mssqldb.pyd' for Python24 [win]?
Did you ever find any information about this... I've been trying to compile it, but wanted to know if someone had done it first. -- http://mail.python.org/mailman/listinfo/python-list
Shareware in Python
I want to create some shareware program in Python. Can I distribute this program with python24.dll file from Python 2.4.2? I'm not sure if Python GPL compatible license allowing for doing it. Thanks, Ivan Sas -- http://mail.python.org/mailman/listinfo/python-list
Multiples of a number
I've searched on google for a bit but I can't seem to find a way to get multiples of a number. . .For instance what would I do if I wanted something to happen every time x reached a multiple of 100 in this sample code: x = 0 while x < 2000: x += 1 Thanks in advance, -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiples of a number
On 11/5/05, Steven D'Aprano <[EMAIL PROTECTED]> wrote: On Sun, 06 Nov 2005 02:39:40 +0100, Carl Friedrich Bolz wrote:> Hi!>> Ivan Shevanski wrote:>> I've searched on google for a bit but I can't seem to find a way to get>> multiples of a number. . .For instance what would I do if I wanted >> something to happen every time x reached a multiple of 100 in this>> sample code:>>>> x = 0>> while x < 2000:>> x += 1>>>> The idea is to use to modulo operator % which gives you the residue of a > number when divided by another number:> for x in range(2000):> if x % 100 == 0:> do_something()Another way is, if you aren't doing anything *except* counting for the other 99 values of x, just skip them completely:fox x in range(20):do_something(x*100)Ivan, what are you trying to do?--Steven.-- http://mail.python.org/mailman/listinfo/python-listSorry for the late response. What I'm doing is pretty simple, I just have a counter running and every time the counter gets to a multiple of 100 it runs a function. So Carl's solution will work fine. Thanks everyone! Thanks, -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Clearing output screen
I know there is a way to do this, but google doesn't seem to want to find it =) There is a command to clear the output screen right? Thanks in advance, -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing output screen
On 11/6/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: Ivan Shevanski wrote> I know there is a way to do this, but google doesn't seem to want to find it> =) There is a command to clear the output screen right?no, because "output screen" isn't a well-defined concept on modern operating systems. the following works in many cases:import osif os.name == "nt":os.system("cls")else:os.system("clear") --http://mail.python.org/mailman/listinfo/python-listThat seems to work just fine. Thanks Fredrik! -Ivan -- http://mail.python.org/mailman/listinfo/python-list
Favorite flavor of Linux? (for python or anything else)
Looking to replace my older flavor of linux with something new. . .What are some of your favorites for python programming and anything else? Thanks, -Ivan -- http://mail.python.org/mailman/listinfo/python-list
PIL question: keeping metadata
A question on using the PIL library. If I take a jpg file then, say, resize it and save it somewhere else, all metadata that is part of the jpg file is lost. This is a pity: digital cameras routinely add metainformation, so does, for example, Photoshop. Is there any way of keeping this info in PIL? Alternatively, is there a simple image processing package that does it? Ivan -- http://mail.python.org/mailman/listinfo/python-list
Open the command line within a script
Hey this is probally a noob question but here goes. . .How could I open the command line inside of a python script? Would I have to use COM? -Ivan _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
How to run commands in command line from a script
I know there is an easy way to do this, and I just can not remember. I have already searched where I thought the module would be. . . I just want to run some name specific commands. Is this easily possible? Thanks, -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run commands in command line from a script
Alright well I'm quite a noob and when I run a simple command to change the current directory, nothing happens. I made a little test script to show it: import os cwd = os.getcwd() print cwd os.system('cd = C:\Program Files') print cwd then the result: C:\Python24\Python Scripts C:\Python24\Python Scripts The cd never changed. . . Can somebody explain this? I think I need to add something simple, i didnt quite get the example 'os.system('./some --command')' -Ivan From: Robert Kern <[EMAIL PROTECTED]> To: python-list@python.org Subject: Re: How to run commands in command line from a script Date: Thu, 30 Jun 2005 20:01:29 -0700 Ivan Shevanski wrote: > I know there is an easy way to do this, and I just can not remember. I have > already searched where I thought the module would be. . . I just want to run > some name specific commands. Is this easily possible? Quick and dirty: import os os.system('./some --command') More robust: Use the subprocess module. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run commands in command line from a script
Well, the thing is that I was just using changing directories as an example for running a name specific command, is the the only way to run name specific commands? An example would be (what I am actually trying to do) run the simply command mame s1945 in the command line. MAME is, for those of you that care, the multaple arcade machine emulator and the command runs the classic game strikers 1945. I'm just trying to automate the tedious process of running it through the command line. By the way, thanks to everyone who responded I'm really getting along here. Thanks, -Ivan > > Generally, the only way to use an application (i.e. a program like the > Python interpreter, or your own .exe) to change the working folder is to > have your script executed from within a batch file, write out a new > batch file in your script, and then have the calling batch file execute > that script if it exists. And, after that long-winded reply, here's another option, if you're just trying to change the directory _within_ your app but don't care if the change persists: import os os.chdir(r'c:\Program Files') -Peter -- _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: PostgreSQL & Python vs PHP
Luis P. Mendes wrote: > I need to build it from the server and also client side. > > For the client side I'll be using Python. > > But for the server side, I would like to hear some opinions. Is it worth > learning Php? If you know Python and don't know PHP, there's little benefit from spending the time learning it. But, PHP is extremely simple to work with and you can produce results VERY quickly. Part of the reason is that it's already intended to be a web-embedded language and doesn't reqire additonal frameworks, libraries or configuration like Python does. One thing that botheres me when using Python in php-like way is that the "indentation is significant" property becomes a nuisance when you intertwine HTML and code (which you shouldn't be doing anyway ;) ). The benefit of Python is that is a much cleaner language with well defined interfaces and you'll probably maintain a large application easier if it's in Python. There are no significant performance differences, and no really significant differences in programming approach. -- http://mail.python.org/mailman/listinfo/python-list
hotmail filter question with list
Just a quick mailing question for anyone who uses hotmail and gets this. Im having problems with my filters =/ i have a filter for mails with python-list@python.org in to or cc, but i still get some in my inbox. anyone? -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: py to exe: suggestions?
Not sure if you already got the answer to this lol but since this is one thing about python i do know how to do, use CXFreeze. Its basicly a combination of all the programs you have already tryed. Works great for me =D sorry I dont have a link, just google it. -Ivan _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
RE: Survey Tool
Wait. . .Do you want it on a website? I don't really understand you -Ivan _ Dont just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Best dbm to use?
[EMAIL PROTECTED] wrote: > I'm creating an persistant index of a large 63GB file > containing millions of peices of data. For this I would > naturally use one of python's dbm modules. But which is the > best to use? BDB4, but consider using sqlite - it's really simple, holds all data in a single file and it's more supported (in the sense: there are bindings for sqlite for almost any language/environment out there, and the file format is stable). It's also very fast and you can later add more information you want to store (by adding more fields to table). -- http://mail.python.org/mailman/listinfo/python-list
Re: 64 bit Python
Mathias Waack wrote: amounts of data. I figured out that a 32 bit application on HP-UX cannot address more than 1 GB of memory. In fact (I think due to the overhead of memory management done by python) a python application cannot use much more than 500 MB of "real" data. For this reason I don't thik this is likely. Don't know about HP-UX but on some platforms, FreeBSD for example, there is a soft memory-cap for applications. By default, a single application on FreeBSD cannot use more than 512MB of memory, period. The limit can be modified by root (probably involves rebooting). -- http://mail.python.org/mailman/listinfo/python-list
Re: 64 bit Python
Mathias Waack wrote: As I stated I wrote a simple C-program before. The c-program was able to allocate a bit more than 900MB in 32 bit mode. Sorry, I should've paid more attention :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Cappy2112 wrote: Eric3 has been compiled for Windows, without Cygwin and Without a commercial license Can it be downloaded from somewhere? (where from?) Or is it forbidden by the license? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Dennis Lee Bieber wrote: You know of an assembly language that does Object Oriented? My... The world has been waiting with bated breath for that. Hey, IIRC, old Turbo Assembler (tasm, by Borland) had those. Much of it was still manual, by it supported semi-automatic vtables and such :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple XML-to-Python conversion
[EMAIL PROTECTED] wrote: I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. I came across gnosis XML tools, but need a built-in option for doing something similar. I too needed such thing, and made this simple parser: http://ivoras.sharanet.org/projects/xmldict.py.gz It's really quick and dirty. It doesn't even use standard parsers such as dom or sax, but improvises its own. It's also very likely to fail in mysterious ways when it encounters invalid XML, but for quick and dirty jobs, it's very nice and easy. See the bottom of the file for some quick examples. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python like VB?
Dennis Lee Bieber wrote: On Sat, 19 Mar 2005 14:36:02 +0100, Ivan Voras <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: Hey, IIRC, old Turbo Assembler (tasm, by Borland) had those. Much of it was still manual, by it supported semi-automatic vtables and such :) I'd suspect through a rather elaborate "macro" capability. Probably... don't remember any more, but it was prominent in the manuals :) The standard assembler used in my college classes didn't even understand the native instruction set of the machine -- until you LD std,1 AFA(1),'04'x, CF(2),AF(1) cool, these look like microinstructions :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to c++ conversion problem
"Akdes Serin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I have a code in python like > if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom > function takes Direction enum as a parameter > > When I am trying to write this code in c++ > if (player->moveRoom(s[1])) //s[1] is a string so it outputs an error > because of not taking enum as a parameter > > How can I change string to enum in c++? Obviously C++ has no eval equivalent, but it also has limited "introspection" at run-time. That is, the executing code has no way to know the compile-time name associated with the enum values. One way to do this mapping manually would be: #include #include enum ERoom { roomEntrance = 0 , roomLobby = 1 , roomCave = 2 }; typedef std::map RoomLookup; typedef RoomLookup::value_type RoomLookupEntry; RoomLookupEntry roomLookupData[3] = { RoomLookupEntry("Entrance", roomEntrance ) , RoomLookupEntry("Lobby",roomLobby ) , RoomLookupEntry("Entrance", roomCave ) }; RoomLookup sRoomLookup(roomLookupData,roomLookupData+3); Then in your code: if (player->moveRoom(sRoomLookup[ s[1] ])) An annoyance with this approach is that your are writing everything twice. There are tricks to avoid that, using the preprocessor, but it has its own drawbacks (see the thread associated with http://groups.google.ca/groups?selm=QJGdnT8LXIMFEGLcRVn-1A%40comcast.com ) But for a game, most typically, the code would load room descriptions from a data file at run-time, and dynamically generate the equivalent of sRoomLookup. I hope this helps, Ivan -- http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form Brainbench MVP for C++ <> http://www.brainbench.com -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing per record
Irmen de Jong wrote: XML is not known for its efficiency Surely you are blaspheming, sir! XML's the greatest thing since peanut butter! I'm just *waiting* for the day someone finds its use on the rolls of toilet paper... oh the glorious day... -- http://mail.python.org/mailman/listinfo/python-list
Unicode problems, yet again
I have a string fetched from database, in iso8859-2, with 8bit characters, and I'm trying to send it over the network, via a socket: File "E:\Python24\lib\socket.py", line 249, in write data = str(data) # XXX Should really reject non-string non-buffers UnicodeEncodeError: 'ascii' codec can't encode character u'\u0161' in position 123: ordinal not in range(128) The other end knows it should expect this encoding, so how to send it? (Does anyone else feel that python's unicode handling is, well... suboptimal at least?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problems, yet again
Jp Calderone wrote: You don't have a string fetched from a database, in iso-8859-2, alas. That is the root of the problem you're having. What you have is a unicode string. Yes, you're right :) I actually did have iso-8859-2 data, but, as I found out late last night, the data got converted to unicode along the way. Thanks to all who replied so quickly :) (Does anyone else feel that python's unicode handling is, well... suboptimal at least?) Hmm. Not really. The only problem I've found with it is misguided attempt to "do the right thing" by implicitly encoding unicode strings, and this isn't so much of a problem once you figure things out, because you can always do things explicitly and avoid invoking the implicit behavior. I'm learning that, the hard way :) One thing that I always wanted to do (but probably can't be done?) is to set the default/implicit encoding to the one I'm using... I often have to deal with 8-bit encodings and rarely with unicode. Can it be done per-program? -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problems, yet again
John Machin wrote: (Does anyone else feel that python's unicode handling is, well... suboptimal at least?) Your posting gives no evidence for such a conclusion. Sorry, that was just steam venting from my ears - I often get bitten by the "ordinal not in range(128)" error. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode problems, yet again
John Machin wrote: Just a thought: I noticed from the traceback that you are running this on a Windows box. Profound apologies in advance if this question is an insult to your intelligence, but you do know that Windows code page 1250 (Latin 2) -- which I guess is the code page that you would be using -- is *NOT* the same as iso-8859-2, don't you? Yes, I know. The reason I'm doing it on Windows is that the app's supposed to be multiplatform, so I'm doing part of development on Windows, part on FreeBSD... The agreed-upon codepage is iso8859-2 for both. (about the "latin2" term - it really sucks that it's used incosistently - for example, PostgreSQL (and I think MySQL) use "latin2" when they mean iso8859-2). need to deal with Unicode, then set up the encoding explicitly on a per-file or per-socket basis. The default ASCII encoding is then there I didn't know that! ... looks at the manual ... oh, it was introduced in 2.3. I wonder if it would work for sockets (though I don't plan to use it now - I've got explicit encodings/decodings set up). -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting into Python, comming from Perl.
Mage wrote: foo = dict() or: foo = {} -- http://mail.python.org/mailman/listinfo/python-list
HTML cleaner?
Is there a HTML clean/tidy library or module written in pure python? I found mxTidy, but it's a interface to command-line tool. What I'm searching is something that will accept a list of allowed tags and/or attributes and strip the rest from HTML string. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML cleaner?
M.-A. Lemburg wrote: Not true: mxTidy integrates tidy as C lib. It's not an interface to the command line tool. Thanks, I'll look at it again! -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK vs. wxPython
Grant Edwards wrote: Huh? wxPythonGTK requires GTK runtimes as well: He was probably talking about Windows, where wx toolkit uses native (more or less...) controls. But then, installing GTK runtime libraries on Windows is a one-click job, there are automated installers for it. -- http://mail.python.org/mailman/listinfo/python-list
Reusing object methods?
Can this be done: (this example doesn't work) class A: def a_lengthy_method(self, params): # do some work depending only on data in self and params class B: def __init__(self): self.a_lengthy_method = A.a_lengthy_method # I know that data in "self" of class B object is compatible # with that of class A object I want to 'reuse' the same method from class A in class B, and without introducing a common ancestor for both of them - is this possible in an elegant, straightforward way? -- http://mail.python.org/mailman/listinfo/python-list
Re: Reusing object methods?
Jp Calderone wrote: I want to 'reuse' the same method from class A in class B, and without introducing a common ancestor for both of them - is this possible in an elegant, straightforward way? This is what sub-classing is for. If it makes you feel better, call it "mixing in" instead. You can share this method between two classes without inheritance (by defining a free function and then ...), but using a common base class really is just the right way to do it. Ok. -- http://mail.python.org/mailman/listinfo/python-list
Re: creating multiple python Django projects in Windows environment
Hi Reto. I understand that i need to run Django on a server. I have deployed projects to AWS (ubuntu) in the past. My main question is around how to tie it into the windows environment. Ivan On Mar 18, 2016 7:40 PM, Reto Brunner wrote: Well you can just put it on a proper server. In the end that's what django is for yes? In case that isn't an option and you don't want to install python there's docker, but then you would need to install that... On Fri, Mar 18, 2016, 20:05 jogaserbia mailto:ivanjanko...@live.ca>> wrote: Hello, At work, I have a windows environment. I have created applications on my linux ubuntu machine at home that I would like to use for work purposes. For example, I have: - a Django project that takes inputs from users and creates pdfs - a Django project that tracks various company related information - a python project that parses word documents and returns clean excel documents (the documents to be parsed would be on the local machine) - a python project that uses scikit learn to make decisions which customers should get which marketing campaigns What I would like to know is how I should create an environment (vagrant, virtualbox running linux on an existing Windows machine in my network?) and connect it to my windows environment so that staff can assess these applications. I would prefer not to have to install python on everyone's computer who might need to use the programs so as not to have to maintain each workstation. Can someone please give me ideas on what I should read about (or pay someone to do) that would enable me to create a basis on which multiple Python (web and non-web) applications can be access by staff in a windows environment. Thank you, and sorry if the question is a bit convoluted, I am trying to get my head around how to create a basis from which to create company wide access to applications. Ivan -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Understanding "help" command description syntax - explanation needed
Hello everyone, I'm a Python beginner and just getting familiar with it. (I need it for my EE B.Sc. project) For the learning purposes I use IDLE and (Learning Python by written by Mark Lutz). Let's say that I have some earlier experience with C language, but still Python is a different one ))) Anyway, the question I would like to ask is about understanding "help" contents. It may look to obvious and even a dumb question, but still I need your help. Here is a brief background with example in order to introduce my problem in more clear way: Suppose I get some list created: >>>L=[i for i in range(1,15,2)] As it can be seen, this is the odd numbers list: [1, 3, 5, 7, 9, 11, 13] Supppose I need to check the occurrence of number 7, in this case I'll just write: >>>L.index(7) The result is :3 So here is the question itself: If I use the help command to check the "range" command I get this info: range(stop) -> range object range(start, stop[, step]) -> range object As you've seen in my example I used range(1,15,2). But this knowledge I got from googling a couple of sites. I still can't understand the "help" command description. For instance, how do I need to understand that (start,stop[,step]) it's just a three numbers? What do those brackets--> [,] mean? The same about "str.replace" command, where I get this: S.replace(old, new[, count]) - using this description I can't really understand how to write the "replace" function parameters. So I googled it up and found this example in order to get more clear understanding of command use. str = "this is string examplewow!!! this is really string" print str.replace("is", "was") print str.replace("is", "was", 3) The result: thwas was string examplewow!!! thwas was really string thwas was string examplewow!!! thwas is really string But still how do I know that those "old, new" are the strings and [,count] just a number? I mean, it was more naturally(as a baginner) to me to write str.replace(is,was[,3]) and that's all. Finally, as for my opinion, this is a lame way to learn "what a command do" by constantly googling it for examples. I need to get more familiar with "help", but the main problem, is that I couldn't find any suitable explanations/tutorials about "help" syntax and etc. (maybe didn't search well). Any explanations/links will be greatly appreciated. I need some help for "help" ^_^ Thanks in advance, Ivan. -- https://mail.python.org/mailman/listinfo/python-list
RE: Understanding "help" command description syntax - explanation needed
Firtst of all thanks for reply. >>brackets [] means that the argument is optional. That's what I'm talking about (asking actually), where do you know it from? I mean, if there are some resources, which explain all these syntax abbreviations? The general concept. Like this one(just for example): class bytearray([source[, encoding[, errors]]]) --- What does it mean? Is that I can use it in optional way? Like: class bytearray(source) or class bytearray(encoding) ? or just write down all three of them? In which format do I do so? Sincerely, Ivan. -Original Message- From: Jean-Michel Pichavant [mailto:jeanmic...@sequans.com] Sent: Wednesday, November 5, 2014 13:55 To: Ivan Evstegneev Cc: python-list@python.org Subject: Re: Understanding "help" command description syntax - explanation needed Original Message - > From: "Ivan Evstegneev" > To: python-list@python.org > Sent: Wednesday, 5 November, 2014 12:00:16 PM > Subject: Understanding "help" command description syntax - explanation > needed So here is the question itself: > > If I use the help command to check the “range” command I get this > info: > > > > range(stop) -> range object > > range(start, stop[, step]) -> range object With python 2.7, when I type help(range), I get """ Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. """ range([start,] stop[, step]) tells you how to call the range function, there's a start, stop and step argument. The purpose of these arguments are given by the longer description. brackets [] means that the argument is optional. Though there's nothing wrong with googling the function for help, I'm doing it all the time. Actually, the python documentation is a better place to get help on a particular function, just make sure you hit the correct version, for either python 2 or 3: https://docs.python.org/2/library/functions.html#range I'm using python's help function only when working offline. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
RE: Understanding "help" command description syntax - explanation needed
Chris, You got my point exactly. ^_^ This is not about a "range" command itself, but those conventions. Thanks. Larry, >> That's what I'm talking about (asking actually), where do you know it from? >>I know it because I've been a programmer for 39 years. I didn't intend to offence anyone here. Just asked a questions ^_^ -Original Message- From: Python-list [mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of Chris Angelico Sent: Wednesday, November 5, 2014 14:16 Cc: python-list@python.org Subject: Re: Understanding "help" command description syntax - explanation needed On Wed, Nov 5, 2014 at 10:00 PM, Ivan Evstegneev wrote: > range(start, stop[, step]) -> range object > > For instance, how do I need to understand that (start,stop[,step]) > it’s just a three numbers? > > What do those brackets--> [,] mean? The docs for range() in Python 3 do need improvement, as Mark said, although there's a bit more info than you see there. The exact text varies from one version to another, but underneath that first line should be something like: "Return a virtual sequence of numbers from start to stop by step." That should tell you a bit more, at least. As to the brackets, they're a common convention meaning "optional". This is much bigger than Python, so it's not actually explained anywhere. (I've no idea where someone would go to try to find info on these sorts of conventions. It's a little hard to do a Google search for symbols and their usages. But that's what mailing lists like this are for.) You can create a range object with two arguments (start and stop) or three (start, stop, and step). When an argument is optional, it usually has a default, and in this case, the default step is 1 - every integer will be included. Don't be afraid to ask questions. There are plenty of people here who know both Python and C (I'm one of them), and we're happy to help out. And hey, you might find you can contribute a better piece of help text for something, and then we can make it better for every future wonderer :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Comprehension with two variables - explanation needed
Hello guys, I would like to ask you for some explanations on comprehensions. (Don't be scared, it just some particular example ^_^) I found this little "find prime number" example over the internet: >>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] >>> primes = [x for x in range(2, 50) if x not in noprimes] >>> print primes [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] It looked pretty clear to me, till the time I decided to make some changes to it %))) Ok this is the case: As you can see the first line's comprehension produces a list, that includes all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i). So I get this pattern: noprimes = = [4, 6, 8...48, 6, 9,12.. ]. The change that I tried to apply to this comprehension would lead to the following pattern: noprimes = = [[4, 6,8.48], [6, 9, 12..], ..,[some numbers]] But despite my struggling on it for the whole day, I haven't got to the desirable result(using comprehensions only) Please, don't get me wrong, I'm not a lazy one (just a beginner). In my case, I made some googling, and found some patterns for matrices, that look this one(for example): Matrix = [[0 for x in range(5)] for x in range(5)] But when I tried to use square brackets with my code, it yields an error about definition of "i", for instance: File "", line 1, in noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)] NameError: name 'i' is not defined. Then I tried to apply those brackets to "j", like this: >>> noprimes = [[j] for i in range(2, 8) for j in range(i*2, 50, i)] In this case I get, pretty predictable result, like this: [[num], [num], [num],...,[num]], and this is still not what I'm looking for.. So I moved further, and succeeded to solve my problem in a different manner: >>> noprimes=[] >>> for i in range(2,8): noprimes.append(list(range(i*2,50,i))) Which yields, in fact, the matrix I wanted from the beginning: noprimes == [[4, 6, 8, 10, 12,.., 48], [6, 9, 12, 15, 18, ., 42, 45, 48],..,[numbers]] Yep, this the "classical" way for me, on the other hand I have the feeling, that this is not, the ultimate solution. ^_^ So my questions is still persists: 1) Is it possible to realize such a thing by applying changes only to initial comprehension? If yes, it would be nice to see the solution. 2) How actually bad is my solution? I mean, after all, there are nested functions call in my code, so how much the speed is affected(if any)? Thanks a lot in advance, Ivan. -- https://mail.python.org/mailman/listinfo/python-list
RE: Comprehension with two variables - explanation needed
>Is this what you want? > >>>> [[j for j in range(i*2, 50, i)] for i in range(2,8)] >[[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48], [8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, >15, 20, 25, 30, 35, 40, 45], [12, 18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]] >[I am not sure what you are trying -- just making local changes to the ZF to make it work] >https://mail.python.org/mailman/listinfo/python-list Yes, awesome. Thanks. But it breaks all the picture that I've built in my head about comps till now... As I know from books and googling, the comps main idea looks approximately like this: [target <--main loop<--nested loop/s (and maybe some conditions)]Am I right? But your code looks somehow inverted to me o_0 Like: [[target with nested loop] <--- main loop with initial values for target] On the other hand, if I'm comparing to my tryouts: noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)] It looks same but the variables are not separated, so it definitely was not defined Sincerely, Ivan -Original Message- From: Python-list [mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of Rustom Mody Sent: Sunday, November 23, 2014 17:09 To: python-list@python.org Subject: Re: Comprehension with two variables - explanation needed On Sunday, November 23, 2014 8:28:16 PM UTC+5:30, Ivan Evstegneev wrote: > Hello guys, > > I would like to ask you for some explanations on comprehensions. > (Don't be scared, it just some particular example ^_^) > > I found this little "find prime number" example over the internet: > > >>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] > >>> primes = [x for x in range(2, 50) if x not in noprimes] print > >>> primes > [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] > > > It looked pretty clear to me, till the time I decided to make some > changes to it %))) > > Ok this is the case: > > As you can see the first line's comprehension produces a list, that includes all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i). > So I get this pattern: noprimes = = [4, 6, 8.48, 6, 9,12 ]. > The change that I tried to apply to this comprehension would lead to > the following pattern: noprimes = = [[4, 6,8...48], [6, 9, 12], > ,[some numbers]] > > But despite my struggling on it for the whole day, I haven't got to > the desirable result(using comprehensions only) > > Please, don't get me wrong, I'm not a lazy one (just a beginner). > > In my case, I made some googling, and found some patterns for matrices, that look this one(for example): > > Matrix = [[0 for x in range(5)] for x in range(5)] > > But when I tried to use square brackets with my code, it yields an error about definition of "i", for instance: > > File "", line 1, in noprimes = [[j for i in > range(2, 8)] for j in range(i*2, 50, i)] > NameError: name 'i' is not defined. Is this what you want? >>> [[j for j in range(i*2, 50, i)] for i in range(2,8)] [[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48], [8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, 15, 20, 25, 30, 35, 40, 45], [12, 18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]] [I am not sure what you are trying -- just making local changes to the ZF to make it work] -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: Comprehension with two variables - explanation needed
Got the main idea. Still need to "chew it up" in depth. (As I mentioned I'm a beginner EE student, so please excuse me for my "lameness" ^_^) -Original Message- From: Python-list [mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of Rustom Mody Sent: Sunday, November 23, 2014 18:46 To: python-list@python.org Subject: Re: Comprehension with two variables - explanation needed On Sunday, November 23, 2014 9:27:22 PM UTC+5:30, Roy Smith wrote: > Skip Montanaro wrote: > > > > But it breaks all the picture that I've built in my head about > > > comps till now... > > > > Note that list comprehensions are little more than syntactic sugar > > for for loops. If you're having terrible writing or understanding > > one, especially a compound one like your example, it can help to > > write it as a (nested) for loop, then covert it (perhaps incrementally) to the list comp form. > > Or not. If it was complicated enough that you needed to loopify it to > understand what it's doing, have pity on the next person who has to > maintain your code and leave it as a loop :-) > > My general rule for code hygiene is, "If I have to think about whether > something is too complicated, it is". [I guess I am in the minority here... anyways... here goes] 1. I find comprehensions are harder than for-loops -- corollary to functional code is easier than imperative -- corollary to time is a major headache. If the problem does not involve time the solution should try to avoid it 2. "List comprehensions are syntactic sugar for for loops" Cannot technically quarrel with that as that is the position of the official docs. However to me it puts the cart before the horse. Its like saying that def foo(x): return x+1 is just the same as 0 LOAD_FAST0 (x) 3 LOAD_CONST 1 (1) 6 BINARY_ADD 7 RETURN_VALUE (output of dis) That may be the case but it seems (to me at least) to defeat the purpose of using an hi-level language. 3. So how should one think of list comprehensions? As a python/executable version of 'set-builder notation' http://en.wikipedia.org/wiki/Set-builder_notation 4. Finally to the OP (assuming you wanted a prime-number generator) Heres a solution for your consideration. First a one-line solution in haskell sieve (p:xs) =p:sieve [x | x <- xs, x `mod` p /= 0] Call with sieve [2..] Now a pythonification of that def n2s(): # natural nos from 2; ie [2..] i=2 while True: yield i i+=1 def sieve(l): p = next(l) yield p yield from sieve (x for x in l if x % p != 0) Call as for p in sieve(n2s()): print(p) -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Python Iterables struggling using map() built-in
one: >>> print(list(map(iter, S))) [, , , ] -> At this moment "Wrecking Ball" song played in my head %))) >>> k = list(map(iter,S)) >>> next(k[0]) 's' >>> next(k[0]) Traceback (most recent call last): File "", line 1, in next(k[0]) StopIteration So I may admit that I found the problem, but can't explain it to myself. Finally I've checked the map() definition. According to python.org: "Return an iterator that applies function to every item of iterable, yielding the results." The questions: And as I've promised the question section: 1. What actually map() trying to do in Python 3.X? I mean, why is this works fine: >>>L = [1, 2, 3, 4] >>> k = iter(L) >>> next(k) 1 and so on. But not this: >>> list(map(iter, L)) Traceback (most recent call last): File "", line 1, in print(list(map(iter, L))) TypeError: 'int' object is not iterable 2. Why strings are allowed "to become" an iterators(self-iterators)? Maybe because of files(reading from file) ? I mean why, is this possible: >>> print(list(map(iter, S))) [, , , ] What I'm trying to say, is that if I wouldn't tried to run the book's example with integer arguments(or tuples or lists as arguments) it wouldn't alarm this issue. And I've lived happily assuming that I understand iterables. This is kind of a "dirty trick", because author do not talk about this anywhere. 3. The last question Author says: " But it falls into an infinite loop and fails in Python 3.X, because the 3.X map returns a one-shot iterable object instead of a list as in 2.X. In 3.X, as soon as we've run the list comprehension inside the loop once, iters will be exhausted but still True. To make this work in 3.X, we need to use the list built-in function to create an object that can support multiple iterations". (Like:"Wat?!" ^_^) Why the infinite loop would be there and why should list() to make it finite? o_0 Hope you have not get annoyed too much. Thanks in advance, Ivan -- https://mail.python.org/mailman/listinfo/python-list
Tuple of lists concatenation - function vs comprehension
Hello, When I have worked in Python shell (IDLE) I found this issue: >>>x = ([1, 2], [3, 4], [5, 6]) >>>L = [] >>>for I in x: L.extend(i) >>>L [1,2,3,4,5,6] But when I try to make comprehension using above expression, I get this: >>>x = ([1, 2], [3, 4], [5, 6]) >>>L = [] >>> [L.extend(i) for i in x] [None, None, None] But this works fine within function: >>> def myfunc(): x = ([1, 2], [3, 4], [5, 6]) L = [] [L.extend(i) for i in x] print(L) >>>myfunc() [1, 2, 3, 4, 5, 6] The question is why I'm getting empty list while working with comprehension in interactive console? Thanks for your help. Ivan. -- https://mail.python.org/mailman/listinfo/python-list
RE: Tuple of lists concatenation - function vs comprehension
Hi Shiyao, Now I see, that it was kind of dumb question... >>>>x = ([1, 2], [3, 4], [5, 6]) >>>>L = [] >>>[L.extend(i) for i in x] [None, None, None] BUT when I check L itself I'll see this one >>>L [1,2,3,5,6] Ok. Thanks. -Original Message- From: Shiyao Ma [mailto:i...@introo.me] Sent: Sunday, December 7, 2014 17:18 To: Ivan Evstegneev Cc: python-list@python.org Subject: Re: Tuple of lists concatenation - function vs comprehension On 12/07, Ivan Evstegneev wrote: > Hello, > > When I have worked in Python shell (IDLE) I found this issue: > > >>>x = ([1, 2], [3, 4], [5, 6]) > >>>L = [] > >>>for I in x: > L.extend(i) > > >>>L > [1,2,3,4,5,6] > > But when I try to make comprehension using above expression, I get this: > > >>>x = ([1, 2], [3, 4], [5, 6]) > >>>L = [] > >>> [L.extend(i) for i in x] > [None, None, None] Yes. per the doc, list.extend() returns None. > > But this works fine within function: > > >>> def myfunc(): > x = ([1, 2], [3, 4], [5, 6]) > L = [] > [L.extend(i) for i in x] > print(L) > > >>>myfunc() > [1, 2, 3, 4, 5, 6] This is also so true, as you are print the var 'L'. > > The question is why I'm getting empty list while working with > comprehension in interactive console? You are also getting [None]*3 in comprenhension inside a function. -- Shiyao Ma http://introo.me -- https://mail.python.org/mailman/listinfo/python-list
RE: Python Iterables struggling using map() built-in
Awesome Ned, Believe it or not, but I was browsing web for the answer about a half an hour ago. Guess what? I found your web page with the explanations you provided there. ))) Finally, I was ready to send this question to you directly, cause I didn't know that you subscribed to this mailing list too. ^_^ But, you was a bit faster. What a surprise. ))) ))) ))) Thanks a lot for your answer. Ivan. -Original Message- From: Python-list [mailto:python-list-bounces+webmailgroups=gmail@python.org] On Behalf Of Ned Batchelder Sent: Sunday, December 7, 2014 17:29 To: python-list@python.org Subject: Re: Python Iterables struggling using map() built-in On 12/6/14 11:44 AM, Ivan Evstegneev wrote: > And as I've promised the question section: > > 1.What actually map() trying to do in Python 3.X? > > I mean, why is this works fine: > >>>>L = [1, 2, 3, 4] > >>>> k = iter(L) > >>>> next(k) > > 1 > > and so on. > > But not this: > > >>> list(map(iter, L)) > > Traceback (most recent call last): > > File "", line 1, in > > print(list(map(iter, L))) > > TypeError: 'int' object is not iterable Let's unpack the code. You are running: map(iter, L) which is equivalent to: map(iter, [1, 2, 3, 4]) which executes: iter(1), iter(2), iter(3), iter(4) If you try iter(1), you get the error you are seeing. Integers are not iterable. What values would it produce? You ask what this is doing in Python 3, but it happens in any Python version, because integers are not iterable. > > 2.Why strings are allowed "to become" an iterators(self-iterators)? > Maybe because of files(reading from file) ? > > I mean why, is this possible: > >>>> print(list(map(iter, S))) > > [, > > , > > , > > ] > This is a confusing thing in Python: strings are iterable, they produce a sequence of 1-character strings: >>> list("hello") ['h', 'e', 'l', 'l', 'o'] This isn't because of reading from files. Open files are iterable, they produce a sequence of strings, one for each line in the file. This is why you can do: for line in file: process(line) Many times, it would be more convenient if strings were not iterable, but they are, and you need to keep it in mind when writing general-purpose iteration. > > 3.The last question > > Author says: > > " /But it falls into an infinite loop and fails in Python 3.X, because > the 3.X map returns a / > > /one-shot iterable object instead of a list as in 2.X. In 3.X, as soon > as we've run the list / > > /comprehension inside the loop once, iters will be exhausted but still > True/. /To make this / > > /work in 3.X, we need to use the list built-in function to create an > object that can support / > > /multiple iterations". /(Like:"Wat?!" ^_^)// > > Why the infinite loop would be there and why should list() to make it > finite? o_0 > OK, let's go slowly. There are a few foundational concepts to get under our belt. *** CONCEPTS 1. An iterable is an object that you can pass to iter() to get an iterator. 2. An iterator is an object that can provide you with values one after the other, by using next(). next() will either return the next value, or raise a StopIteration exception, indicating that there are no more values. 3. The only operation supported on iterators is next(). You cannot start them over, you cannot ask if there will be more values, you cannot find out how many values there will be, you can't ask what the last value was, etc. By supporting only one operation, they allow the broadest possible set of implementations. 4. You can ask an iterator for an iterator, and it will return itself. That is: iter(some_iterator) is some_iterator. 5. The "for NAME in EXPR" construct is equivalent to this: expr_iter = iter(EXPR) try: while True: NAME = next(expr_iter) ..DO_SOMETHING.. except StopIteration: pass 6. In Python 2, map() produces a list of values. Lists are iterable. In Python 3, map() produces a map object, which is an iterator. *** PYTHON 2 EXECUTION OK, now, here is the code in question: 1. def myzip(*args): 2. iters = map(iter, args) 3. while iters: 4. res = [next(i) for i in iters] 5. yield tuple(res) Let's cover the Python 2 execution first. At line 2, map produces a list of iterators. Line 3 will loop forever. Nothing ever changes the list. In fact, this is a very confusing part of this code. The code should have said "while True" here, because it would wor
Classes - converting external function to class's method.
Hello Everyone, I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: >>>class rec: pass Step 2 - adding some attributes: >>>rec.name = 'Bob' >>>rec.age = 40 Step 3 - Creating an instance: >>>x= rec() Step 4 - write down external function: >>>def uppername(obj): return obj.name.upper() Step 5 - applying this function on x: >>>uppername(x) 'BOB' Till this moment its Ok. But: Step 6 - Creating a class method: >>>rec.method = uppername Then using the "help" function I get (just checking what happened): >>>help(rec) class rec(builtins.object) | Methods defined here: | | method = uppername(obj) | | -- |omitted text.. | | Data and other attributes defined here: | | age = 40 | | name = 'Bob' Then the same about x: >>>help(x) class rec(builtins.object) | Methods defined here: | | method = uppername(obj) | --- omitted text . |- The last check I've made: >>> help(x.method) Help on method uppername in module __main__: uppername() method of __main__.rec instance >>> help(rec.method) Help on function uppername in module __main__: uppername(obj) and now to the Step 7 - using this new "method" on x: >>>x.method() 'BOB' >>>rec.method() . . TypeError: uppername() missing 1 required positional argument: 'obj' and then: >>>rec.method(rec) 'BOB' So my the question is: what is going on here? How this actually works? According to the book's downside note: ** In fact, this is one of the reasons the self argument must always be explicit in Python methods-because methods can be created as simple functions independent of a class, they need to make the implied instance argument explicit. They can be called as either functions or methods, and Python can neither guess nor assume that a simple function might eventually become a class's method. The main reason for the explicit self argument, though, is to make the meanings of names more obvious: names not referenced through self are simple variables mapped to scopes, while names referenced through self with attribute notation are obviously instance attributes. * Keeping it in mind, I wrote this code: >>> class myclass: def __init__(self, value): self.name = value def myupper(self): return self.name.upper() And then: >>> b = myclass('bob') >>>b.myupper() 'BOB' I made an assumption that this is what happens(roughly speaking) when I write this: >>>rec.method = uppername Am I right? (close enough maybe?) On the other hand, when I checked further: >>>dir(x.method) [, '__self__',...] but >>>dir(rec.method) [ list of method and '__self__' wasn't there.] I got a "bit" confused. Why actually in instance "x" >>>x.method() can auto-assign an "x" to uppername() function argument, but it doesn't work in a class "rec" itself? So I need to write down an "obj" argument manually. Why '__self__' exists only in instance "x"? (maybe because "rec", initially was created as an empty class?) How does a function "uppername()" looks like, when I apply it to "rec" class, so it becomes a class's method? So in such a case, when instance "x" receives an "update" it reads the new method as I described above(I mean the code of "myclass")? Thanks a lot in advance, Ivan. -- https://mail.python.org/mailman/listinfo/python-list
RE: Classes - converting external function to class's method.
Dear Steven, I very appreciate your answer. You just explained a lot of background things and you did it in more explicit and simple way than it've appeared in the book. I also agree with you about the fact that there are some advanced topics spread within a book's text. It is sometimes hard to a newbie to separate essential and from non essential(I mean more advanced) topics. So I may find myself digging down too much ^_^ In order to assemble the picture I would like to refer to couple of things you mentioned: >In this case, it works as you expect. Python looks up "method" on the instance, and doesn't find anything attached to the instance. It then looks at the class "rec", >which does have something called "method". Because this is a function, Python knows to provide the instance x as the first argument. So the call > x.method() >ends up turning into this: >rec.method(x) I saw something similar to this example, but initially didn't understand what the author meant, so I skipped it Here is a quote from a book(Please see Pic1.jpg too): *** Method Calls If this I2.w reference is a function call, what it really means is "call the C3.w function to process I2." That is, Python will automatically map the call I2.w() into the call C3.w(I2), passing in the instance as the first argument to the inherited function. *** This was much confusing, till the moment I've read your explanation on live example. ))) > Looking at this, I can guess you are using Python 3, because that won't work in > Python 2. Am I right? Yes. I downloaded, Python 3.4 from python.org. Currently working with IDLE. > The important part to see here is that when you call a method from an > instance: > > instance.method() > > Python *automatically* fills in the "self" argument using the instance. (In your > case, you called that argument "obj" instead of self, but Python doesn't care > what it is called.) > > How does Python know to use x as self? Because it's written right there: > x.method uses x as the first argument for method. But this is only done for > *instances*, not classes. So, just to summarize all this stuff: A class doesn't have method __self__ by itself. I checked this on some other class provided in the book: >>> class FirstClass: # Define a class object def setdata(self, value):# Define class's methods self.data = value # self is the instance def display(self): print(self.data) And then check it with: >>>dir(FirstClass) [Yep no __self__ here] On the other side, when an instance created, it does have __self__ method. > > How does a function "uppername()" looks like, when I apply it to "rec" > > class, so it becomes a class's method? > > I don't understand this question. Well this is an embarrassing moment, it's just shows how lame my English can be ) What I tried to ask here is if there any changes applied by Python to code of function "uppername()" when it becomes class method (after using this command: rec.method = uppername) Never mind, you already answered it here: > This is almost equivalent to the following: > > class rec: > name = 'Bob' > age = 40 > def method(obj): > return obj.name.upper() Moreover, regard to the "rec.method = uppername" As I can understand, in this case Python does make some changes to the function, but they are implicit. Am I right? Sincerely, Ivan > -Original Message- > From: Python-list [mailto:python-list- > bounces+webmailgroups=gmail@python.org] On Behalf Of Steven > D'Aprano > Sent: Sunday, December 14, 2014 19:28 > To: python-list@python.org > Subject: Re: Classes - converting external function to class's method. > > Ivan Evstegneev wrote: > > > Hello Everyone, > > > > I have stuck a bit with this example(took this one from the book). > > The example you are working on (adding external functions as methods) is > actually a bit more complicated than it seems, as you have discovered. You have > this: > > class rec: pass > rec.name = 'Bob' > rec.age = 40 > > x= rec() > > def uppername(obj): > return obj.name.upper() > > rec.method = uppername > > > This is almost equivalent to the following: > > class rec: > name = 'Bob' > age = 40 > def method(obj): > return obj.name.upper() > > > You then try to use this new method, by calling i
RE: Classes - converting external function to class's method.
Again Thanks for your help. I saw that there was a debate about "namespace" nature. That is what a book says about it(Learning Python 5 Ed. By Mark Lutz): * "Classes and Instances Although they are technically two separate object types in the Python model, the classes and instances we put in these trees are almost identical—each type’s main purpose is to serve as another kind of namespace—a package of variables, and a place where we can attach attributes. If classes and instances therefore sound like modules, they should; however, the objects in class trees also have automatically searched links to other namespace objects, and classes correspond to statements, not entire files." "Customization via inheritance More generally, classes can build up namespace hierarchies, which define names to be used by objects created from classes in the hierarchy. This supports multiple customizable behaviors more directly than other tools." "...classes live in modules and are namespaces as well, but they add an extra component to attribute lookup called inheritance search." "In fact, classes have just three primary distinctions. At a base level, they are mostly just namespaces, much like the modules we studied in Part V. Unlike modules, though, classes also have support for generating multiple objects, for namespace inheritance, and for operator overloading." I'm not pretending to be a "smartass" here, but as I can understand from the context: Classes are namespaces, but they also have an additional capabilities. BR, Ivan > -Original Message- > From: Python-list [mailto:python-list- > bounces+webmailgroups=gmail@python.org] On Behalf Of Steven > D'Aprano > Sent: Monday, December 15, 2014 04:01 > To: python-list@python.org > Subject: Re: Classes - converting external function to class's method. > > Thomas 'PointedEars' Lahn wrote: > > > Ivan Evstegneev wrote: > > > >> I have stuck a bit with this example(took this one from the book). > >> > >> Here are a description steps of what I've done till now: > >> > >> > >> Step 1 - creating an empty namespace: > >> > >>>>>class rec: pass > > > > IMHO that is not actually creating a namespace; it is just > > declaring/defining an empty class. > > And classes are namespaces. As are instances. > > One clue is the fact that we use exactly the same syntax for accessing names > in a > namespace regardless of whether the namespace is a package, a module, a class > or an instance: > > import collections.abc # a package namespace math.sin # a module namespace > OrderedDict.fromkeys # a class namespace mystring.upper # an instance > namespace > > I call it a "clue" rather than definitive proof because the syntax is not > quite the > same for all namespaces. Local and global variables also exist in namespaces, > but > you don't use dotted notation for them. > > Another clue is that most of these are implemented by using a __dict__ to > store > the name:value mapping. Again, that's not universal: instances can optionally > use __slots__ instead of __dict__ and packages use the file system. > > Apart from packages, one can use getattr(), setattr() and delattr() on all of > these > objects (modules, classes and instances) to manipulate their attributes. > > Wikipedia says: > > "In general, a namespace is a container for a set of identifiers (also known > as > symbols, names)." > > https://en.wikipedia.org/wiki/Namespace > > and that applies to packages, modules, classes, and instances. > > Last but not least, another clue: in some languages, such as Java, what Python > calls "attributes" are known as *variables*. So per-instance members are > called > "instance variables", per-class members are sometimes called "class variables" > (although not in Java, where I believe they are known as static variables for > technical reasons). Personally, I don't like that terminology, but I do > recognise > that it does reflect a certain connection between names in > local/global/instance/class namespaces. > > > > BTW, the recommended Python 3.x way is > > > > class Rec (object): > > pass > > > I think you mean Python 2 rather than 3. In Python 2, we have legacy "old > style" > or "classic" classes, and "new style" classes which inherit from object. In > Python > 3, classic classes are gone, and inheriting
Classes - "delegation" question.
we embedding "Person" into "Manager" class, On the other hand, when I write this code: >>> tom = Manager('Tom Jones', 5000) I create an instance of Manager that have an attribute named: tom.person, which in turn is a class named Person. And when typing: >>>tom.giveRaise(.10) I do kinda same thing. For my assumption I say: Person.giveRaise( percent + bonus) (when self.person actually implies "Person") But why we don't use "self" argument in --> self.person.giveRaise(percent + bonus)? So it should look like --> self.person.giveRaise(self, percent + bonus)? Is it because of embedding "Person" into "Manager" so there is no hierarchy considerations, and by embedding(compositing) classes, we place them at the same level? And as it seems to me, there is no relevance for " inheritance" stuff. As a direct consequence, when I type: >>> tom.giveRaise(.10) I made a "call" through instance, and there is no need for "self"? Thanks a lot in advance, Ivan -- https://mail.python.org/mailman/listinfo/python-list
Advice needed - Choosing appropriate GUI (IDE) and Data Visualization software (3D also)
Hello guys, Here is a brief description for my question: I'm currently dealing with my EE B.Sc. final project. This projects generally relates to the SDN Optical Networks. One of its goals is to build some GUI framework based on mininet software (http://mininet.org/) Mostly, I'll need expand its capabilities and add some new features for Layer 1. As a general concept I need to build something which looks like that: 1. http://www.brianlinkletter.com/wp-content/uploads/2014/01/GNS3-setup-Virtual Box-9.png or that (even better): 2. https://www.safaribooksonline.com/library/view/learning-omnet/9781849697149/ graphics/7149OT_02_03.jpg When at middle window I'll place my interactive display, which (at initial state) should look like this one: 3. http://3.bp.blogspot.com/_2bTtOorcilA/S-jVtqNy0xI/AAM/R9l6L26yAV0/s1 600/ChordIPv4.png I said 'interactive' because it need to be: scalable, zoomable, movable(and other "able") ^_^ Moreover it actually need to provide access to device properties, for instance behave (at least) like that one: 4. http://youtu.be/XAzXKnAwKxo?t=4m20s Finally I found this one : 5. http://youtu.be/L-ad0Phy0eI?t=10s This one looks awesome! ))) This is an interactive model to which I want to aspire. Furthermore, if this design: 6. https://www.youtube.com/watch?v=JsEm-CDj4qM could be implemented to the above links, this will realize my "wet dream" of blurry bubbles and shaded backgrounds Of course, as a EE student I'll tend more to the practical side rather than design. But still it could be nice to make some good looking product. In conclusion: 1. For my core GUI(IDE) I'll likely use PythonQt. I've read couple of reviews , most of them say that this one good for beginners. Of cause, if there any other frameworks that worth to consider, and seems more suitable for beginners, I would be glad to hear for your advice. Here I need most of your help: 2. The interactive "middle window", unfortunately I have no idea what is a suitable software for such kind of things. For almost a week I delve the NET for possible options, there are innumerable quantity of Python packages and tools (my Chrome is blown up with opened tabs), but still don't know what to choose or how to implement this one. (especially link's #5 model) (Python OpenGL? ) 3. For those of you who will ask: why I don't want to take something already done before: My answer will be simple: a. Unfortunately I'm not a guru of programming. My programming scope includes only some C, Matlab, and now Python. For this reason I can't take some modules from "omninet ++" software (which actually written in C++) and implement them in my project. Or for instance to use OpenDayLight software modules I know that I will mess up with this and waste a lot of time for getting it work properly. (But I'm not whining here ^_^) b. I'm short in time (as most of us). I can't afford myself to learn additional languages (at least at this moment) c. My basis software (mininet) is written on Python. d. Most of an existing software for SDN deal with Layer 3. So their models not so suitable for my purposes. I need to redefine a lot of things and build them from scratch. e. In general I think Python can handle all my needs Any advice will be highly appreciated. Sincerely, Ivan. -- https://mail.python.org/mailman/listinfo/python-list
symple programming task
hi all, i have simple programming task: [quot] If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. [/quote] this task from http://projecteuler.net/ site I wrote a solution in python http://pastebin.com/QXtNuRWU this script returned correctly result if "basis < 10", but if "basis < 1000" result is 266333 and it is not correctly answer on site http://projecteuler.net it is my script problem or site not working correctly? thanks sorry for my english -- https://mail.python.org/mailman/listinfo/python-list
Re: symple programming task
On Sunday, April 20, 2014 10:43:37 PM UTC+4, Ivan Ivanivich wrote: > hi all, i have simple programming task: > > > > [quot] > > If we list all the natural numbers below 10 that are multiples of 3 or 5, we > get 3, 5, 6 and 9. The sum of these multiples is 23. > > > > Find the sum of all the multiples of 3 or 5 below 1000. > > [/quote] > > > > this task from http://projecteuler.net/ site > > > > I wrote a solution in python > > > > http://pastebin.com/QXtNuRWU > > > > this script returned correctly result if "basis < 10", but if "basis < 1000" > result is 266333 and it is not correctly answer on site > http://projecteuler.net > > > > it is my script problem or site not working correctly? > > > > thanks > > > > sorry for my english thanks, i found the bag -- https://mail.python.org/mailman/listinfo/python-list
Re: symple programming task
On Sunday, April 20, 2014 10:43:37 PM UTC+4, Ivan Ivanivich wrote: > hi all, i have simple programming task: > > > > [quot] > > If we list all the natural numbers below 10 that are multiples of 3 or 5, we > get 3, 5, 6 and 9. The sum of these multiples is 23. > > > > Find the sum of all the multiples of 3 or 5 below 1000. > > [/quote] > > > > this task from http://projecteuler.net/ site > > > > I wrote a solution in python > > > > http://pastebin.com/QXtNuRWU > > > > this script returned correctly result if "basis < 10", but if "basis < 1000" > result is 266333 and it is not correctly answer on site > http://projecteuler.net > > > > it is my script problem or site not working correctly? > > > > thanks > > > > sorry for my english my bag is: Adding twice the same elements to the total for exemple: for divider in 3, 5: basis=divider while basis < 1000: mod = basis % divider if mod == 0: total = total + basis if "basis" is 15, then "mod" == 0 twice - when the "divider" is 3 and 15 my new version of script: total = 0 div1 = 3 div2 = 5 for basis in range(0, 1000): mod = basis % div1 if mod == 0: total = total + basis continue mod = basis % div2 if mod == 0: total = total + basis continue print("total = ", total) -- https://mail.python.org/mailman/listinfo/python-list
Function Defaults - avoiding unneccerary combinations of arguments at input
Hello all , Just a little question about function's default arguments. Let's say I have this function: def my_fun(history=False, built=False, current=False, topo=None, full=False, file=None): if currnet and full: do something_1 elif current and file: do something_2 elif history and full and file: do something_3 .. some code here.. and so on... I won't cover all the possibilities here (actually I don't use all of them ^_^). The question is about avoiding the response for unnecessary combinations? For instance, if user will call function this way: >>>my_fun(current=True, full=True, topo='some str', file="some_file") That will lead to function's misbehavior. As a particular case it will choose "current and full" condition. What is the common accepted way to deal with such unwanted situations? Thanks a lot in advance, Ivan. -- https://mail.python.org/mailman/listinfo/python-list
RE: Function Defaults - avoiding unneccerary combinations of arguments at input
Hi Terry, Thanks for answer, I'll google these stdlib instances. Sincerely, Ivan. > -Original Message- > From: Python-list [mailto:python-list- > bounces+webmailgroups=gmail@python.org] On Behalf Of Terry Reedy > Sent: Wednesday, March 25, 2015 20:43 > To: python-list@python.org > Subject: Re: Function Defaults - avoiding unneccerary combinations of > arguments at input > > On 3/25/2015 1:43 PM, Ivan Evstegneev wrote: > > Hello all , > > > > > > Just a little question about function's default arguments. > > > > Let's say I have this function: > > > > def my_fun(history=False, built=False, current=False, topo=None, > > full=False, file=None): > > if currnet and full: > > do something_1 > > elif current and file: > > do something_2 > > elif history and full and file: > > do something_3 > > > > > > .. some code here.. > > > > and so on... > > > > I won't cover all the possibilities here (actually I don't use all of > > them ^_^). > > > > The question is about avoiding the response for unnecessary > combinations? > > > > For instance, if user will call function this way: > > > > > >>>> my_fun(current=True, full=True, topo='some str', file="some_file") > > > > That will lead to function's misbehavior. As a particular case it will > > choose "current and full" condition. > > > > > > What is the common accepted way to deal with such unwanted situations? > > Raise a value error for illegal combinations. There are a few instances in the > stdlib where 2 of several options are mutually incompatible. > > > -- > Terry Jan Reedy > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: Function Defaults - avoiding unneccerary combinations of arguments at input
Hello again ^_^, Googled a bit, and found only one, a "ValueError" exception, but still don't understand how it should be implemented in my case. Should my code look like this one: def my_fun(history=False, built=False, current=False, topo=None, full=False, file=None): try: if currnet and full: do something_1 elif current and file: do something_2 elif history and full and file: do something_3 except ValueError: print("No valid input! Please try again ...") .. some code here.. Or I'm just too optimistic ^_^? Thanks in advance, Ivan. > -Original Message- > From: Python-list [mailto:python-list- > bounces+webmailgroups=gmail@python.org] On Behalf Of Terry Reedy > Sent: Wednesday, March 25, 2015 20:43 > To: python-list@python.org > Subject: Re: Function Defaults - avoiding unneccerary combinations of > arguments at input > > On 3/25/2015 1:43 PM, Ivan Evstegneev wrote: > > Hello all , > > > > > > Just a little question about function's default arguments. > > > > Let's say I have this function: > > > > def my_fun(history=False, built=False, current=False, topo=None, > > full=False, file=None): > > if currnet and full: > > do something_1 > > elif current and file: > > do something_2 > > elif history and full and file: > > do something_3 > > > > > > .. some code here.. > > > > and so on... > > > > I won't cover all the possibilities here (actually I don't use all of > > them ^_^). > > > > The question is about avoiding the response for unnecessary > combinations? > > > > For instance, if user will call function this way: > > > > > >>>> my_fun(current=True, full=True, topo='some str', file="some_file") > > > > That will lead to function's misbehavior. As a particular case it will > > choose "current and full" condition. > > > > > > What is the common accepted way to deal with such unwanted situations? > > Raise a value error for illegal combinations. There are a few instances in the > stdlib where 2 of several options are mutually incompatible. > > > -- > Terry Jan Reedy > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
RE: Function Defaults - avoiding unneccerary combinations of arguments at input
> -Original Message- > From: Python-list [mailto:python-list- > bounces+webmailgroups=gmail@python.org] On Behalf Of Rob Gaddi > Sent: Wednesday, March 25, 2015 22:07 > To: python-list@python.org > Subject: Re: Function Defaults - avoiding unneccerary combinations of > arguments at input > > On Wed, 25 Mar 2015 21:50:40 +0200, Ivan Evstegneev wrote: > > > Hello again ^_^, > > > > Googled a bit, and found only one, a "ValueError" exception, but still > > don't understand how it should be implemented in my case. > > > > Should my code look like this one: > > > > def my_fun(history=False, built=False, current=False, topo=None, > > full=False, file=None): > > try: > > if currnet and full: > > do something_1 > > elif current and file: > > do something_2 > > elif history and full and file: > > do something_3 > > > > except ValueError: > > print("No valid input! Please try again ...") > > > > > > .. some code here.. > > > > > > Or I'm just too optimistic ^_^? > > > > Thanks in advance, > > > > Ivan. > > > > A) Please don't top-post. Put your new stuff below previous context, so it > flows in readable order. > > B) You've got the concept backwards. You're not trying to catch a ValueError > because one came up below your function. Your function was called > incorrectly, and you're kicking the responsibility for dealing with it back to the > guy who got it wrong. > > def my_fun(): > if invalid_argument_combination: >raise ValueError('Hey jerk, read the documentation.') > > # otherwise you do your thing in here. > > > -- > Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email > address domain is currently out of order. See above to fix. > -- > https://mail.python.org/mailman/listinfo/python-list Ok thanks fo the answer. Got it. About top-posting... will need to tweak Outlook settings. -- https://mail.python.org/mailman/listinfo/python-list