Re: xkcd.com/353 ( Flying with Python )
On Mon, Apr 1, 2024 at 1:26 PM HenHanna via Python-list < python-list@python.org> wrote: > Johanne Fairchild wrote: > > > HenHanna writes: > > >> https://xkcd.com/1306/ > >> what does SIGIL mean? > > > A glyph used in magic. Or, for Perl, the symbol in front of a variable > > name, such as $, @, and %. > > > Source: https://perldoc.perl.org/perlglossary#sigil > > > Sigil is noun. Definitions: > > > A seal; a signet. > > A sign or an image considered magical. > > A seal; a signature. > > > Source: The American Heritage® Dictionary of the English > Language, 5th Edition. > > > > > > omg...Sigil is a real word??? > > > The word "sigil" comes from the Latin term "sigillum," which means "little > sign." This Latin root is also the source of our English word "seal," > making "sigil" and "seal" doublets. > > https://en.wiktionary.org/wiki/sigil > > > I understand "sigil" as referring to symbols occultists make up and use to aid in their magick. -- https://mail.python.org/mailman/listinfo/python-list
Re: it seems like a few weeks ago... but actually it was more like 30 years ago that i was programming in C, and
On Mon, Feb 27, 2023 at 3:56 AM inhahe wrote: > > > On Mon, Feb 27, 2023 at 3:52 AM Roel Schroeven > wrote: > >> Op 26/02/2023 om 6:53 schreef Hen Hanna: >> > > There are some similarities between Python and Lisp-family >> > > languages, but really Python is its own thing. >> > >> > >> > Scope (and extent ?) of variables is one reminder that Python is >> not Lisp >> > >> > fori in range(5): print( i ) >> > . >> > print( i ) >> > >> > ideally, after the FOR loop is done, the (local) var i should also >> disappear. >> > (this almost caused a bug for me) >> I wouldn't say "i *should* also disappear". There is no big book of >> programming language design with rules like that that all languages have >> to follow. Different languages have different behavior. In some >> languages, for/if/while statements introduce a new scope, in other >> languages they don't. In Python, they don't. I won't say one is better >> than the other; they're just different. >> >> -- >> >> > I'm not sure, but I think I remember this was actually a bug in the > interpreter, and presumably they didn't fix it because they didn't want to > break backward compatibility? > > Maybe I'm thinking of a variable scope leak after list comprehensions. -- https://mail.python.org/mailman/listinfo/python-list
Re: it seems like a few weeks ago... but actually it was more like 30 years ago that i was programming in C, and
On Mon, Feb 27, 2023 at 3:52 AM Roel Schroeven wrote: > Op 26/02/2023 om 6:53 schreef Hen Hanna: > > > There are some similarities between Python and Lisp-family > > > languages, but really Python is its own thing. > > > > > > Scope (and extent ?) of variables is one reminder that Python is > not Lisp > > > > fori in range(5): print( i ) > > . > > print( i ) > > > > ideally, after the FOR loop is done, the (local) var i should also > disappear. > > (this almost caused a bug for me) > I wouldn't say "i *should* also disappear". There is no big book of > programming language design with rules like that that all languages have > to follow. Different languages have different behavior. In some > languages, for/if/while statements introduce a new scope, in other > languages they don't. In Python, they don't. I won't say one is better > than the other; they're just different. > > -- > > I'm not sure, but I think I remember this was actually a bug in the interpreter, and presumably they didn't fix it because they didn't want to break backward compatibility? -- https://mail.python.org/mailman/listinfo/python-list
Re: ModuleNotFoundError
sorry, I may have misused the term "namespace." I'm not sure what the proper word is for the names currently loaded into the global scope. On Fri, Jun 17, 2022 at 8:26 AM inhahe wrote: > sys is a built-in module, but it's not in the namespace unless you import > it first. > before your print statement, enter "import sys" > > On Fri, Jun 17, 2022 at 8:23 AM wrote: > >> Thank you for your email. >> >> C:\Users\zszen>python.exe >> Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> print(sys.version) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'sys' is not defined >> >> >>> print(sys.executable) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'sys' is not defined >> >> On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: >> > On 6/17/22, Zoltan Szenderak wrote: >> > > >> > > print(sys.version_info) and executable: >> > > Unable to initialize device PRN >> > >> > That's the command-line "print" program. You need to first start the >> > Python shell via python.exe. The prompt should change to ">>> ". Then >> > run print(sys.version) and print(sys.executable). >> > >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > -- https://mail.python.org/mailman/listinfo/python-list
Re: ModuleNotFoundError
sys is a built-in module, but it's not in the namespace unless you import it first. before your print statement, enter "import sys" On Fri, Jun 17, 2022 at 8:23 AM wrote: > Thank you for your email. > > C:\Users\zszen>python.exe > Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 > bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> print(sys.version) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sys' is not defined > > >>> print(sys.executable) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'sys' is not defined > > On Fri, Jun 17, 2022, at 12:35 PM, Eryk Sun wrote: > > On 6/17/22, Zoltan Szenderak wrote: > > > > > > print(sys.version_info) and executable: > > > Unable to initialize device PRN > > > > That's the command-line "print" program. You need to first start the > > Python shell via python.exe. The prompt should change to ">>> ". Then > > run print(sys.version) and print(sys.executable). > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: NOT ABLE TO SEE PICTURES
Maybe your file explorer is set to ignore system and/or hidden files, and Python isn't? You can check that in folder settings.. On Wed, Dec 1, 2021 at 10:31 AM Ragavendar wrote: >When the python runs in file explorer when I open a folder it shows NO >ITEAMS FOUND and if I open same folder without python ITEAMS ARE THERE > so >kindly help me > > > > > >Sent from [1]Mail for Windows > > > > References > >Visible links >1. https://go.microsoft.com/fwlink/?LinkId=550986 > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: How to debug python + curses? [was: RE: Applying winpdb_reborn]
On Sun, May 30, 2021 at 1:43 PM wrote: > I tried winpdb-reborn some time last year on my Win10 system (python 3.8.3 > at that time), but could not figure out how to use it to debug a python > script that uses the curses module. > > Does anyone here know if winpdb-reborn or any other debugger can support > 2-window debugging for a python script that uses the curses module? It > seems to me that a 2-window debugging session is necessary for a python > script that uses the curses module because using curses takes over the > screen from which the script is started, so debugging output and script > output need to be in separate windows. > > I've been forced to use a logger to trace critical values and program flow > for errors in such a script. It works, but it is annoyingly slow to debug > that way. > > TIA for any advice or RTFM you can provide. > > Peter > -- > > -- > https://mail.python.org/mailman/listinfo/python-list I don 't know if this solution was mentioned, but someone in IRC just said this is especially useful for debugging curses, and it reminded me of this thread. https://pypi.org/project/q/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Python language packages isn't working in Visual Studio Code
I don't think attaching images works on this kind of list. Maybe send a link to it.. On Mon, May 3, 2021 at 1:51 PM Osmany Guerra wrote: > Hi, I have problem with the python interpreter in the Visual Studio Code. > It was running ok, but now isn't working. I have downloaded, installed and > unistalled several times without having results. How could I fix that? > I'm using windows 10 64-bit, VSCode x64-1.55.2, and Python 3.9.4. > I'm sending you a picture of my laptop screen too. > Waiting for your reply > Regards Osmany > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Fwd: How to cycle through servers on Connection Fail in an IRC client?
I'm not sure if it's okay to ask about Twisted in this mailing list, but Twisted's mailing list seems to have ignored my submission for some reason. And their mailing list seems mostly dead anyway. So here goes: I'm making an IRC client using Twisted, and I want to connect to a different server when connection fails, but I haven't been able to figure out how to do that.. Here's a more or less minimal code sample reflecting what I have now: from twisted.words.protocols import irc from twisted.internet import protocol from twisted.internet import reactor class ServerConnection(irc.IRCClient): def __init__(self): self.signedon = False self.nickindex = 0 def signedOn(self): print("signed on") def nickChanged(self, newnick): self.nickname = newnick class Network(object): def __init__(self, servers, mynick=None): self.servers = servers self.mynick = mynick self.serverindex = 0 class ServerFactory(protocol.ReconnectingClientFactory): def __init__(self, nickname="qttwirc", password=None, username="qttwirc", realname=None, network=None): self.network = network self.network.mynick = nickname self.nickname = nickname self.username = username self.password = password self.realname = realname protocol.ReconnectingClientFactory.initialDelay = 10 #should i leave this at 1? protocol.ReconnectingClientFactory.maxDelay = 10 #no idea what value this should be. 3.5 wasn't slow enough, i was being throttled. def buildProtocol(self, addr): p = ServerConnection() self.serverconnection = p p.server = self p.nickname = self.nickname p.username = self.username self.resetDelay() return p def clientConnectionLost(self, connector, reason): self.serverconnection = None protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason) def clientConnectionFailed(self, connector, reason): self.serverconnection = None addr, port = self.network.servers[self.network.serverindex] self.network.serverindex = (self.network.serverindex+1) % len(self.network.servers) #todo: make it actually use these values #reactor.callLater(config.reconnectdelay, reactor.connectTCP, addr.encode("ascii"), port, self) #reactor.connectTCP(addr, port, self) #is this feasible? i don't know a better way to do this. connector.connect() apparently doesn't take server/port as arguments. protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason) network = Network([("hitchcock.freenode.net", 6667), ("verne.freenode.net", 6667)]) server = ServerFactory(nickname="test123", username="test123", network=network) reactor.connectTCP(*network.servers[network.serverindex], server) reactor.run() If I have to completely change the structure of how I connect, that's fine.. I don't understand Twisted very well, so I'm not aware of what some other options are for how to make an IRC client. (It probably doesn't matter, but in my actual program I'm using both Twisted and PyQt5 in the same run loop using qt5reactor..) Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: editor recommendations?
My editor of choice is Komodo IDE, which used to be commercialware but is free now. I'm pretty sure it has dark modes, but I haven't used them. I just thought I'd mention it because it's a good, solid IDE but I never see anybody mention it, e.g. in lists of Python editors and such.. On Fri, Feb 26, 2021 at 9:52 AM Ethan Furman wrote: > I'm looking for an editor to use for Python programming, as well as > related incidentals such as markdown files, restructured text, etc. > > I'm currently using vim, and the primary reason I've stuck with it for so > long is because I can get truly black screens with it. By which I mean > that I have a colorful window title bar, a light-grey menu bar, and then a > light-grey frame around the text-editing window (aka the only window), and > a nice, black-background editing area. > > When I have occasionally tried other editors, they either don't support a > black background, or the black background is only for the text-editing > portion which leaves large portions of screen real-estate with a bright > background, which is hard on my eyes. > > So, what's the state-of-the-art with regards to editors supporting dark > color themes? > > TIA. > > -- > ~Ethan~ > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Letter replacer - suggestions?
Besides what others have said (especially re using a dict instead), I think it's unpythonic/can result in unexpected behavior to change a list as it's being iterated over. Your modified word_list should be a separate list, I think. Also, if you use enumerate(), you won't have to use .index and it would be more efficient. And I'm not sure what the 'while True' accomplishes. Seems it would put it in an endless loop? If the 'while True' were in the beginning of the program, before the inputs, it would make more sense. (And in that case you'd probably want to break the loop if `word` is empty) On Mon, Dec 7, 2020 at 10:51 AM Bischoop wrote: > > I worked on my wee script that replaces a letters: https://bpa.st/OYBQ . > I would like to have some suggestions about the code from more > experienced programmers, the code does work and do its job but perhaps > could work in a better way. > > Thanks > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: How can I make this more complex?
if 100 > grade >= 90: On Mon, Nov 9, 2020 at 6:01 PM Quentin Bock wrote: > grade = input("Enter your grade: ") > if grade >= 90: > print("You got an A ") > if grade >= 80: > print("You got a B ") > if grade >= 70: > print("You got a C") > if grade >= 60: > print("You got a D ") > if grade >= 50: > print("You failed") > > > > > How can I make this to say if your grade is 90 or higher BUT less than 100 > you got an A, > Thanks > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: returning totals in functions of math
On Sun, Nov 8, 2020 at 1:51 PM Quentin Bock wrote: > Errors say that add takes 1 positional argument but 3 were given? Does this > limit how many numbers I can have or do I need other variables? > Here is what I have: > def add(numbers): >total = 1 >for x in numbers: > total += x >return total > print(add(1999, -672, 84)) > > I have a multiply function above it but that was solved and I'm trying to > figure everything out for each of the different math functions. > Thank you > -- > https://mail.python.org/mailman/listinfo/python-list By the way, did you know about the `sum` function? It does basically what your add function does, except I think you'd need to pass it an initial value so it knows what type it's adding, or something like that. -- https://mail.python.org/mailman/listinfo/python-list
Re: Any better way for this removal?
> > > On Sat, Nov 7, 2020 at 8:51 AM Bischoop wrote: > >> >> >> So I was training with slicing. >> Came to idea to remove text after second occurence of character, below >> is how I've figured it out, I know if it works it good but how you >> guys would made it in more pythonic way? >> >> text = "This is string, remove text after second comma, to be removed." >> >> k= (text.find(",")) #find "," in a string >> m = (text.find(",", k+1)) #Find second "," in a string >> new_string = text[:m] >> >> print(new_string) >> >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > Not sure what's more Pythonic, but another way of doing it would be to use `m = text.split(",", 2)`, then rejoin the string via `",".join(m[:2])`, and I guess you'd also have to add a comma at the end if you want that, `+","` Another way to do it would be with regex with capturing. `m = re.find("^(.*?,.*?,).*", text)` or something like that. Sorry, my Python is a little rusty. -- https://mail.python.org/mailman/listinfo/python-list
Re: Asynchronous generators
I know of a URL that explains asyncio: https://hackernoon.com/a-simple-introduction-to-pythons-asyncio-595d9c9ecf8c. As to your specific problem, I can't help and don't know if the URL helps. I haven't studied asyncio much. On Tue, Jun 23, 2020 at 3:53 PM Jonathan Gossage wrote: > -- > I am attempting to learn how to use asyncio and I have been unable to find > any documentation or Internet posts that give information on the principles > underlying asyncio, let alone any examples showing how asynchronous > generators should be used. I have built a toy program to test trying to > read a text file, line by line, and process each line asynchronously. I > wind up with a message complaining that my asynchronous generator is not a > coroutine. I am posting a copy of my program here along with the results > from trying to run it. I am hoping for some suggestions about how to fix > it. I am using Python 3.8.3 on Ubuntu 20.04 > > import asyncio > > from pathlib import Path > > import timeit > > > > async def _read_password() -> str: > > with Path('/etc/passwd').open() as f: > > line: str = f.readline() > > yield line > > print('read_password has read everything') > > > > async def main(_rp) -> int: > > line = '' > > async for line in _rp: > > try: > > print(f'Got line {line}') > > except StopAsyncIteration: > > line = None > > _rp.aclose() > > return 0 > > > > if __name__ == '__main__': > > _loop = asyncio.get_event_loop() > > _rp = _read_password() > > _m = main(_rp) > > _loop.create_task(_m) > > _loop.create_task(_rp) > > timeit.Timer(_loop.run_until_complete()).timeit() > > _loop.close() > > > Here is the output: > > Traceback (most recent call last): > File "/usr/local/lib/python3.8/runpy.py", line 194, in > _run_module_as_main > return _run_code(code, main_globals, None, > File "/usr/local/lib/python3.8/runpy.py", line 87, in _run_code > exec(code, run_globals) > File > > "/home/jgossage/EclipseWorkspaces/GlobalVillage/Infrastructure/Play/Async/passwd.py", > line 34, in > _loop.create_task(_rp) > File "/usr/local/lib/python3.8/asyncio/base_events.py", line 431, in > create_task > task = tasks.Task(coro, loop=self, name=name) > TypeError: a coroutine was expected, got _read_password at 0x7f1f2454b8b0> > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Fwd: python script to give a list of prime no.
On Sun, Apr 5, 2020 at 8:26 AM Sathvik Babu Veligatla < sathvikveliga...@gmail.com> wrote: > hi, > I am new to python, and i am trying to output the prime numbers beginning > from 3 and i cannot get the required output. > It stops after giving the output "7" and that's it. > > CODE: > a = 3 > l = [] > while True: > for i in range(2,a): > if a%i == 0: > l.append(1) > else: > l.append(0) > > if l.count(1) == 0: > print(a) > a = a + 2 > elif l.count(1) >> 0: > a = a + 2 > > > > Any help is appreciated, > Thank you. > -- > https://mail.python.org/mailman/listinfo/python-list "l = []" needs to go inside the "while True" loop. as it is, it keeps adding 1's and 0's to the list with each new "a" value, and then counts the 1's and 0's, without ever resetting the list back to empty, so once it gets to 9 the list has a 1 in it and l.count(1) will never be false again. 3, 5 and 7 are prime so a 1 doesn't get added yet with those values, which is why 7 is the highest it gets to. so with "l = []" inside the while loop, "l" would be reset to empty with each new "a" value. btw, this is a very inefficient way to compute prime numbers. for example, why add the 0's to the list? you never count the number of 0's so it's unnecessary. another example.. why use a list at all? all that matters is that it find *one* result where a%i==0, it doesn't matter how many results it found after that, so all you need is a boolean. and you might as well stop testing a%i for *all* i values up to i, because once it finds the first result that's 0, you know it's prime so you can just go to the next number. and you don't need i to go all the way to a, because a%i will always be > 0 for any i over a/2. and since you're not testing evens, it's actually any i over a/3. in actuality, though, computing any a%i where i > the square root of a is redundant because for each factor of a above the square root of a, you've already tested its cofactor, say a is 100. the square root of 100 is 10. if you're testing 100%20, that's unnecessary because 100/20 is 5 and you've already tested 100%5. -- https://mail.python.org/mailman/listinfo/python-list
Re: Sandboxing eval()
> I have written a simple parser/evaluator that is sufficient for my > simple requirements, and I thought I was safe. > > Then I saw this comment in a recent post by Robin Becker of ReportLab - > > "avoiding simple things like ' '*(10**200) seems quite difficult" > > I realised that my method is vulnerable to this and, like Robin, I have > not come up with an easy way to guard against it. > > Frank Millman > > Just use floats instead of integers. -- https://mail.python.org/mailman/listinfo/python-list
Re: phyton
On Tue, Sep 10, 2019 at 12:06 PM tim.gast--- via Python-list < python-list@python.org> wrote: > Op dinsdag 10 september 2019 13:03:46 UTC+2 schreef tim...@quicknet.nl: > > Hi everybody, > > > > For school i need to write the right code to get the following outcome. > > Can someone help me with this > > I can't find a solution to link the word high to 1.21. > > > > 11 print(add_vat(101, 'high')) > > 12 print(add_vat(101, 'low')) > > > > Outcome: > > > > 122.21 > > 110.09 > > > > Thanks! > > Hi inhahe, > > Yeah the 21 was just an example the calculation will come later. > First i need to figure this out... > Is this what you mean with adding a dictionary? > berekening = amount * (1+(vat_rate={'high':21, 'low':5}) > -- > https://mail.python.org/mailman/listinfo/python-list No, I mean add a dictionary lookup, meaning instead of vat_rate, use a value that you look up in the dictionary, by using the syntax for looking up values in dictionaries. What you wrote above would result in a syntax error. Hope this isn't considered doing your homework for you, but tell you how to make a dictionary and look up a value from it. #making the dictionary: primeNumberIndexes = {179:41, 181:42, 191:43, 193:44} #looking up a value in it: IndexOf179 = primeNumberIndexes[179] #IndexOf179 is now 41 Of course you can put a variable (actually a "name" in python terminology, I think) in the brackets instead of a direct value, which you'll want to do. -- https://mail.python.org/mailman/listinfo/python-list
Re: phyton
On Tue, Sep 10, 2019 at 8:41 AM Pankaj Jangid wrote: > tim.g...@quicknet.nl writes: > > > For school i need to write the right code to get the following outcome. > > Can someone help me with this > > I can't find a solution to link the word high to 1.21. > > > > 11 print(add_vat(101, 'high')) > > 12 print(add_vat(101, 'low')) > > > > Outcome: > > > > 122.21 > > 110.09 > > > You can do something like this ;-) > > > import math > > def add_vat(a, b): > return math.ceil(100*(a * 0.57 + sum([ord(c) for c in list(b)]) * > 0.15538))/100 > > print(add_vat(101, 'high')) > print(add_vat(101, 'low')) > > -- > Pankaj Jangid > -- > https://mail.python.org/mailman/listinfo/python-list BAD BAD BAD don't do Pankaj's suggestion, tim, it's DEVILSPEAK -- https://mail.python.org/mailman/listinfo/python-list
Re: phyton
On Tue, Sep 10, 2019 at 8:31 AM inhahe wrote: > > > On Tue, Sep 10, 2019 at 8:10 AM tim.gast--- via Python-list < > python-list@python.org> wrote: > >> Op dinsdag 10 september 2019 13:03:46 UTC+2 schreef tim...@quicknet.nl: >> > Hi everybody, >> > >> > For school i need to write the right code to get the following outcome. >> > Can someone help me with this >> > I can't find a solution to link the word high to 1.21. >> > >> > 11 print(add_vat(101, 'high')) >> > 12 print(add_vat(101, 'low')) >> > >> > Outcome: >> > >> > 122.21 >> > 110.09 >> > >> > Thanks! >> >> I have tried to get it with the dictonary but it doesn't work >> You are right that it is homework and i am trying to figure it out but i >> cant find anything on the internet that can help me. >> What am i doing wrong. >> >> my_dict('high':21,'low':5) >> >> def add_vat(amount, vat_rate): >> berekening = amount * (1+vat_rate) >> return round(berekening,2) >> >> print(add_vat(101, 'high')) >> -- >> https://mail.python.org/mailman/listinfo/python-list > > > I'm not sure exactly what you're trying to do (since 101+21 would give you > 122, not 122.21), but I think your problem is that you're not actually > using the dictionary in your add_vat function. You're just adding 1 to > vat_rate which is 'high'. Adding an integer to a string should be an error. > Instead of "vat_rate" in "1+vat_rate" you need to do a dictionary lookup. > Oh, and my_dict('high':21, 'low':5) isn't actually how you set dictionary values. Unless you have some weird function my_dict in your code that does that that you're not listing -- https://mail.python.org/mailman/listinfo/python-list
Re: phyton
On Tue, Sep 10, 2019 at 8:10 AM tim.gast--- via Python-list < python-list@python.org> wrote: > Op dinsdag 10 september 2019 13:03:46 UTC+2 schreef tim...@quicknet.nl: > > Hi everybody, > > > > For school i need to write the right code to get the following outcome. > > Can someone help me with this > > I can't find a solution to link the word high to 1.21. > > > > 11 print(add_vat(101, 'high')) > > 12 print(add_vat(101, 'low')) > > > > Outcome: > > > > 122.21 > > 110.09 > > > > Thanks! > > I have tried to get it with the dictonary but it doesn't work > You are right that it is homework and i am trying to figure it out but i > cant find anything on the internet that can help me. > What am i doing wrong. > > my_dict('high':21,'low':5) > > def add_vat(amount, vat_rate): > berekening = amount * (1+vat_rate) > return round(berekening,2) > > print(add_vat(101, 'high')) > -- > https://mail.python.org/mailman/listinfo/python-list I'm not sure exactly what you're trying to do (since 101+21 would give you 122, not 122.21), but I think your problem is that you're not actually using the dictionary in your add_vat function. You're just adding 1 to vat_rate which is 'high'. Adding an integer to a string should be an error. Instead of "vat_rate" in "1+vat_rate" you need to do a dictionary lookup. -- https://mail.python.org/mailman/listinfo/python-list
Re: Handle foreign character web input
: > > On 6/28/19 1:33 PM, Chris Angelico wrote:> On Sat, Jun 29, 2019 at 6:31 AM > Tobiah wrote: > > >> Also, what do people do when searching for a record. > >> Is there some way to get 'Ronngren' to match the other > >> possible foreign spellings? > > > > I think I've heard of algorithms that can match spellings with exotic characters, but I don't remember what they're called. I think they're out there. It's a black science, though, so some of their decisions in how to match or not match are probably arbitrary. -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP 594 cgi & cgitb removal
Re cgitb, not sure if this is what you want, but I just came across this this week: https://github.com/cknd/stackprinter On Wed, May 22, 2019 at 3:52 AM Robin Becker wrote: > In PEP 594 t has been proposed that cgi & cgitb should be removed. I > suspect I am not the only person in the world that likes > using cgi and cgitb. > > One of the nice features in cgitb is the ability to get a nice traceback > with variable values etc etc etc. I have used the > underlying mechanism to produce better traceback information on several > occasions and not only in cgi applications. > > I filed a bug against cgitb in 2004 with (apparently unacceptable patches) > that is still unfixed. > > Although cgi is claimed to be dead it is still one of the easiest ways to > get a web service to operate; it is also stateless and > robust. If cgi and similar are removed from the stdlib python will become > significantly less charged. These batteries are not dead > they are pining. > > There is some discussion on the python-dev list of moving these allegedly > dead packages to pypi, but of course that means issues > of control, where do the sources reside and other politics. > > Django has a similar feature to cgitb's output for tracebacks, but is too > deeply embedded for use elsewhere; is there anything > suitable elsewhere? > -- > Robin Becker > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: What does at 0x0402C7B0> mean?
Short answer: (some generator expression) is for iterating over, as others have said. try this: print([fruit for fruit in favorite_fruits]) a loop would work too, as someone mentioned, but the result would be different. you'd get your fruits separated by line breaks (or something else if you specify that), and with no quotation marks, instead of in list form. also note: print(favorite_fruits) will do the same thing as print([fruit for fruit in favorite_fruits]) so there's no need to put a list comprehension there. On Tue, May 21, 2019 at 9:16 PM CrazyVideoGamez wrote: > I tried doing a list comprehension. I typed: > > favorite_fruits = ['watermelon', 'blackberries'] > print(fruit for fruit in favorite_fruits) > > And I got: > > at 0x0402C7B0> > > What does this mean and what do I have to fix? > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Help a noob out
On Thu, May 2, 2019 at 5:26 AM wrote: > Hey guys, can someone quickly explain why this piece of code doesn't work? > (I'm really new to Python) > > birth_year = input("What year are you born? ") > current_year = 2019 > age = current_year - birth_year > print(age) > -- > https://mail.python.org/mailman/listinfo/python-list input() returns a string. So the user enters "1978" for example but he could just have easily entered "Honda Civic". Python doesn't know to interpret it as a number in order to do arithmetic or it until you convert it to an integer. birth_year = int(input("What year were you born?")) should work, unless I missed something else. (the int() converts the string to an integer) Maybe it would be more professional to do some error checking though, e.g. print that there was incorrect input and ask again if they didn't actually input an integer. You could do this using the try and except keywords (in some kind of loop), as int() raises an exception when the string you pass it isn't an actual integer. -- https://mail.python.org/mailman/listinfo/python-list
help! PyQt4 and UTF-8
I can display UTF-8 when I use wxPython: -- import wx app = wx.App() s = 'testing\xf0\x9f\x98\x80' frame = wx.Frame(None, wx.ID_ANY) font = wx.Font("Arial") textbox = wx.TextCtrl(frame, id=wx.ID_ANY) textbox.SetFont(font) textbox.WriteText(s) frame.Show() app.MainLoop() -- But when I try the same thing with PyQt4.. -- from PyQt4 import QtGui import sys s = 'testing\xf0\x9f\x98\x80' app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() font = QtGui.QFont("Arial") textbox = QtGui.QLineEdit(w) textbox.setFont(font) textbox.setText(s) w.show() sys.exit(app.exec_()) -- Instead of "testing" ("testing" with a smiley face after it, if you can't see it in this message), I get "testingð" ("testing", then an o with some kind of mark above it). I tried replacing "s = 'testing\xf0\x9f\x98\x80'" with "s = 'testing\xf0\x9f\x98\x80'.decode('UTF-8')" in case PyQt takes Unicode instead of UTF-8, but in that case I get "testing" and then a little square after it (like the character isn't found in the font). If I copy it and paste it here I get "testing" ("testing" with a smiley face after it, like I want), so I guess displaying it in the font is the problem, but I don't know why.. as you can see, both the wxPython and the PyQt examples use "Arial." I've also tried "FixedSys Excelsior 3.01". Python version: CPython 2.7.14 OS: Windows 10 thanks for any help -- https://mail.python.org/mailman/listinfo/python-list
Can't figure out how to do something using ctypes (and maybe struct?)
I need to make a list of instances of a Structure, then I need to make an instance of another Structure, one of the fields of which needs to be an arbitrary-length array of pointers to the instances in the list. How do I do that? Just in case it helps, I'll include what I tried that didn't work: -- class NoteEvent(ctypes.Structure): _fields_ = [('type', ctypes.c_int), ('byteSize', ctypes.c_int), ('deltaFrames', ctypes.c_int), ('flags', ctypes.c_int), ('noteLength', ctypes.c_int), ('noteOffset', ctypes.c_int), ('commandCode', ctypes.c_char), ('noteNumber', ctypes.c_char), ('velocity', ctypes.c_char)] def mkVstEvents(events): class Events(ctypes.Structure): _fields_ = [('numEvents', ctypes.c_int), ('reserved', ctypes.c_int), ('eventspointerarray', ctypes.c_void_p * len(events))] return Events(len(events), 0, tuple([ctypes.pointer(event) for event in events])) def mkNoteEvent(deltaFrames, flags, noteNumber, channel, velocity, noteLength, noteOffset, detune, noteOffVelocity): vstEvent = NoteEvent(type=1, bytesize=11, deltaFrames=deltaFrames, flags=1, noteLength=0, noteOffset=0, commandCode=chr(144+channel), noteNumber=chr(noteNumber), velocity=chr(velocity)) return vstEvent def onSendMidiButton(self, event): plugins[0].plugin.process_events(ctypes.pointer(mkVstEvents([mkNoteEvent(deltaFrames=0, flags=1, noteNumber=60, channel=0, velocity=127, noteLength=0, noteOffset=0, detune=0, noteOffVelocity=0)]))) -- Here's the error I got: -- Traceback (most recent call last): File "soundshop.9.1.2.py", line 216, in onSendMidiButton noteOffVelocity=0)]))) File "soundshop.9.1.2.py", line 76, in mkVstEvents return Events(len(events), 0, tuple([ctypes.pointer(event) for event in events])) RuntimeError: (c_void_p_Array_1) : incompatible types, LP_NoteEvent instance instead of c_void_p instance -- I also tried to use struct.pack: -- def mkVstEvents(events): st = struct.pack("=ii"+"L"*len(events), len(events), 0, *(ctypes.pointer(event) for event in events)) return st --- Here's the error I got: -- Traceback (most recent call last): File "soundshop.9.3.py", line 213, in onSendMidiButton noteOffVelocity=0)]))) File "soundshop.9.3.py", line 72, in mkVstEvents st = struct.pack("=ii"+"p"*len(events), len(events), 0, *(ctypes.pointer(event) for event in events)) struct.error: argument for 'p' must be a string -- I also tried replacing "p"*len(events) with "i"*len(events) and also with "L"*len(events), both of which gave me errors. Thanks for your help. -- https://mail.python.org/mailman/listinfo/python-list
Question about how to do something in BeautifulSoup?
I hope this is an appropriate mailing list for BeautifulSoup questions, it's been a long time since I've used python-list and I don't remember if third-party modules are on topic. I did try posting to the BeautifulSoup mailing list on Google groups, but I've waited a day or two and my message hasn't been approved yet. Say I have the following HTML (I hope this shows up as plain text here rather than formatting): "Is today the day?" And I want to extract the "Is today the day?" part. There are other places in the document with and , but this is the only place that uses color #00, so I want to extract anything that's within a color #00 style, even if it's nested multiple levels deep within that. - Sometimes the color is defined as RGB(0, 0, 0) and sometimes it's defined as #00 - Sometimes the is within the and sometimes the is within the . - There may be other discrepancies I haven't noticed yet How can I do this in BeautifulSoup (or is this better done in lxml.html)? Thanks -- https://mail.python.org/mailman/listinfo/python-list
trying to use sdl_pango with python
i'm new to ctypes. can someone help me use sdl_pango with python? here's the documentation: http://sdlpango.sourceforge.net/ here's my code: - import pygame from ctypes import * import win32api MATRIX_TRANSPARENT_BACK_WHITE_LETTER = c_char_p(\xFF\xFF\0\0\xFF\xFF \0\0\xFF\xFF\0\0\0\xFF\0\0) margin_x = margin_y = 10 def sdlwrite(rtext, width, height=None): context = sdlpango.SDLPango_CreateContext() sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) sdlpango.SDLPango_SetMinimumSize(context, width, height) sdlpango.SDLPango_SetMarkup(context, rtext, -1) w = sdlpango.SDLPango_GetLayoutWidth(context) h = sdlpango.SDLPango_GetLayoutHeight(context) surface = sdl.SDL_CreateRGBSurface(sdlpango.SDL_SWSURFACE, w + margin_x, h + margin_y, 32, 255 (8*3), 255 (8*2), 255 (8*1), 255) sp = POINTER(surface) sdlpango.SDLPango_Draw(context, ps, margin_x, margin_y) sdl.SDL_FreeSurface(ps) return context def surfwrite(rtext, width, height=None): sdlcontext = sdlwrite(rtext, width, height) print 'sdlcontext:', sdlcontext #scr = pygame.set_mode() #rloss, gloss, bloss, aloss = scr. sdlpango = windll.LoadLibrary(rC:\projects\soundshop\pango-1.18.3\bin \sdl_pango.dll) sdl = windll.LoadLibrary(rsdl.dll) #sdlpango.SDLPango_SetDefaultColor.argtypes = [c_void_p, c_char_p] #sdlpango.SDLPango_SetMinimumSize.argtypes = [c_void_p, c_int, c_int] #sdlpango.SDLPango_SetMarkup.argtypes = [c_void_p, c_char_p, c_int] #sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_void_p] #sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_void_p] #sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] #sdlpango.SDLPango_Draw.argtypes = [c_void_p, c_uint, c_int, c_int] #sdl.SDL_FreeSurface.argtypes = [c_void_p] sdlpango.SDLPango_SetDefaultColor.argtypes = [c_uint, c_uint] sdlpango.SDLPango_SetMinimumSize.argtypes = [c_uint, c_int, c_int] sdlpango.SDLPango_SetMarkup.argtypes = [c_uint, c_char_p, c_int] sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_uint] sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_uint] sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] sdlpango.SDLPango_Draw.argtypes = [c_uint, c_uint, c_int, c_int] sdl.SDL_FreeSurface.argtypes = [c_uint] surfwrite(hello, 640) - here's the .h file that i got MATRIX_TRANSPARENT_BACK_WHITE_LETTER from. http://sdlpango.sourceforge.net/_s_d_l___pango_8h-source.html - here's my error: Traceback (most recent call last): File C:\projects\soundshop\sdlpango.py, line 54, in module surfwrite(hello, 640) File C:\projects\soundshop\sdlpango.py, line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File C:\projects\soundshop\sdlpango.py, line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ctypes.ArgumentError: argument 2: type 'exceptions.TypeError': wrong type - i've tried other things, like using c_char_p instead for MATRIX_TRANSPARENT_BACK_WHITE_LETTER, but the only other result i can manage to get is this: C:\projects\soundshopsdlpango.py Traceback (most recent call last): File C:\projects\soundshop\sdlpango.py, line 52, in module surfwrite(hello, 640) File C:\projects\soundshop\sdlpango.py, line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File C:\projects\soundshop\sdlpango.py, line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ValueError: Procedure probably called with too many arguments (8 bytes in excess) - thx for any help. -- http://mail.python.org/mailman/listinfo/python-list
struct pointing to another struct?
say i have this definition: 1 typedef struct SDL_Surface { 2 Uint32 flags; /* Read-only */ 3 SDL_PixelFormat *format;/* Read-only */ 4 int w, h; /* Read-only */ 5 Uint16 pitch; /* Read-only */ 6 void *pixels; /* Read-write */ 7 SDL_Rect clip_rect; /* Read-only */ 8 int refcount; /* Read-mostly */ 9 10 /* This structure also contains private fields not shown here */ 11 } SDL_Surface; notice two pointers, format and pixels. say format has this definition. 1 typedef struct { 2 SDL_Palette *palette; 3 Uint8 BitsPerPixel; 4 Uint8 BytesPerPixel; 5 Uint8 Rloss, Gloss, Bloss, Aloss; 6 Uint8 Rshift, Gshift, Bshift, Ashift; 7 Uint32 Rmask, Gmask, Bmask, Amask; 8 Uint32 colorkey; 9 Uint8 alpha; 10 } SDL_PixelFormat; so say i want to create a mock sdl handle and pass it to some library function that requires an sdl handle. (would it even work? would i need to use an SDL_SWSURFACE?) so i make the pixelformat data using struct.pack, and make the surface data using struct.pack, but how do i link the surface data to the pixelformat data? if i just use id() it'll give me the memory address of the box for the string and not the string data itself. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: struct pointing to another struct?
On Aug 13, 4:07 pm, Peter Otten __pete...@web.de wrote: inhahe wrote: say i have this definition: 1 typedef struct SDL_Surface { 2 Uint32 flags; /* Read-only */ 3 SDL_PixelFormat *format; /* Read-only */ 4 int w, h; /* Read-only */ 5 Uint16 pitch; /* Read-only */ 6 void *pixels; /* Read-write */ 7 SDL_Rect clip_rect; /* Read-only */ 8 int refcount; /* Read-mostly */ 9 10 /* This structure also contains private fields not shown here */ 11 } SDL_Surface; notice two pointers, format and pixels. say format has this definition. 1 typedef struct { 2 SDL_Palette *palette; 3 Uint8 BitsPerPixel; 4 Uint8 BytesPerPixel; 5 Uint8 Rloss, Gloss, Bloss, Aloss; 6 Uint8 Rshift, Gshift, Bshift, Ashift; 7 Uint32 Rmask, Gmask, Bmask, Amask; 8 Uint32 colorkey; 9 Uint8 alpha; 10 } SDL_PixelFormat; so say i want to create a mock sdl handle and pass it to some library function that requires an sdl handle. (would it even work? would i need to use an SDL_SWSURFACE?) so i make the pixelformat data using struct.pack, and make the surface data using struct.pack, but how do i link the surface data to the pixelformat data? if i just use id() it'll give me the memory address of the box for the string and not the string data itself. thanks. I think you are looking at the wrong module; you need ctypes, not struct. http://docs.python.org/library/ctypes.html Peter can you (or anybody) tell me how to link one c struct to another using ctypes? Thx -- http://mail.python.org/mailman/listinfo/python-list
I think I found a bug in Python 2.6.4 (in the inspect module)
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import inspect def a(b=1): pass ... inspect.getargvalues(a) Traceback (most recent call last): File stdin, line 1, in module File C:\Python26\lib\inspect.py, line 816, in getargvalues args, varargs, varkw = getargs(frame.f_code) AttributeError: 'function' object has no attribute 'f_code' dir(a) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr_ _', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globa ls__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__' , '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subcla sshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc' , 'func_globals', 'func_name'] So i'm guessing that the attribute has been changed from func_code to f_code but the inspect module wasn't updated to reflect that. -- http://mail.python.org/mailman/listinfo/python-list
Re: I think I found a bug in Python 2.6.4 (in the inspect module)
On Tue, Dec 29, 2009 at 5:10 PM, inhahe inh...@gmail.com wrote: So i'm guessing that the attribute has been changed from func_code to f_code but the inspect module wasn't updated to reflect that. er i mean from f_code to func_code -- http://mail.python.org/mailman/listinfo/python-list
Re: I think I found a bug in Python 2.6.4 (in the inspect module)
On Tue, Dec 29, 2009 at 5:11 PM, inhahe inh...@gmail.com wrote: On Tue, Dec 29, 2009 at 5:10 PM, inhahe inh...@gmail.com wrote: So i'm guessing that the attribute has been changed from func_code to f_code but the inspect module wasn't updated to reflect that. er i mean from f_code to func_code f_locals doesn't even seem to exist at all. Traceback (most recent call last): File E:\jsterm\specs\test.py, line 6, in module print inspect.getargvalues(a) File E:\Python26\lib\inspect.py, line 817, in getargvalues return ArgInfo(args, varargs, varkw, frame.f_locals) AttributeError: 'function' object has no attribute 'f_locals dir(a) ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__ hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_clo sure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] -- http://mail.python.org/mailman/listinfo/python-list
Re: I think I found a bug in Python 2.6.4 (in the inspect module)
On Tue, Dec 29, 2009 at 6:38 PM, Irmen de Jong irmen-nosp...@xs4all.nl wrote: On 29-12-2009 23:22, inhahe wrote: inspect.getargvalues is used on frames, not on regular code objects. Maybe you were looking for inspect.getargspec? That explains it! I knew I'd done this before, I was just looking at the wrong function name. thx -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set object parameters nicely?
On Thu, Dec 3, 2009 at 9:16 AM, Lie Ryan lie.1...@gmail.com wrote: On 12/2/2009 10:26 AM, allen.fowler wrote: I've tried this, but have found two issues: 1) I can't set default values. 2) I can't set required values. In both of the above cases, if the object is created without the exact dict() I expect, all the assumption my methods make about what is available in self fall apart. def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): for par in kwargs: self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 or def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): for par in kwargs: self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set object parameters nicely?
On Thu, Dec 3, 2009 at 9:32 AM, inhahe inh...@gmail.com wrote: On Thu, Dec 3, 2009 at 9:16 AM, Lie Ryan lie.1...@gmail.com wrote: On 12/2/2009 10:26 AM, allen.fowler wrote: I've tried this, but have found two issues: 1) I can't set default values. 2) I can't set required values. In both of the above cases, if the object is created without the exact dict() I expect, all the assumption my methods make about what is available in self fall apart. def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): for par in kwargs: self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 or def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): for par in kwargs: self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 (sorry, sent the same code twice. i was going to do it a different way and realized it would be too magically) -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring a class level nested class?
it seems to me like it should work just fine if you just take out the second line where it just says nestedClass On Wed, Dec 2, 2009 at 11:55 PM, cmckenzie mckenzi...@gmail.com wrote: Hi. I'm new to Python, but I've managed to make some nice progress up to this point. After some code refactoring, I ran into a class design problem and I was wondering what the experts thought. It goes something like this: class module: nestedClass def __init__(): self.nestedClass = nested() print self.nestedClass.nestedVar class nested(): nestedVar = 1 def __init__(self): print Initialized... I can't figure out what the correct way to construct the nested class so it can belong to module. I want a class level construct of nested to belong to module, but I keep getting nestedClass isn't defined. My example isn't great or 100% accurate, but I hope you get the idea. Thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Q. interrogate html object OR file search?
or i guess you could go the middle-way and just use regex. people generally say don't use regex for html (regex can't do the nesting), but it's what i would do in this case. though i don't exactly understand the question, re the html file parsing script you say you have already, or how the date is 'modified from' the meta-data. On Wed, Dec 2, 2009 at 10:24 PM, Mark G markgraha...@gmail.com wrote: Hi all, I am new to python and don't yet know the libraries well. What would be the best way to approach this problem: I have a html file parsing script - the file sits on my harddrive. I want to extract the date modified from the meta-data. Should I read through lines of the file doing a string.find to look for the character patterns of the meta- tag, or should I use a DOM type library to retrieve the html element I want? Which is best practice? which occupies least code? Regards, Mark -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
one point of confusion could be the use of ** instead of superscript. it might make things a little bit more counterintuitive-looking than with superscripts, since the issue with would only apply to exponents, as -5*4 and a = -5 a*4 return the same answer, and superscripts make it a little easier to associate the exponent value with the base more than with the - before it. On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Esmail wrote: Wow .. never heard of Concatenative_languages languages before or the distinction you make. Your distinction explains the behavior, but I find it somewhat counter-intuitive. You shouldn't find it any more surprising than the fact that a = 2 + 3 print a * 5 gives a different result from print 2 + 3 * 5 -- Greg -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python
to put it simplistically it's a way of combining multiple variables into one for example, for a person you could have person.haircolor person.echnicity person.age etc. but you can then also manipulate 'person' as a whole like you would any other variable, such as x[n] = person a struct, as far as i know, is like a class but with no methods. or a class is like a struct but with methods that act on the struct's data. i don't think structs technically exist in Python (though they exist in C/C++), but you could always use a plain class like a struct, like this, for a simple example: class Blah: pass b = blah() b.eyecolor = brown b.haircolor = blond b.ethnicity = caucasion On Mon, Nov 30, 2009 at 11:20 AM, Ronn Ross ronn.r...@gmail.com wrote: I have recently come across something called a struct. I have googled this, but have note found a good explanation. Can someone give me a good definition or point me to a page that has one. Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with lambda / closures
On Mon, Nov 30, 2009 at 10:54 AM, Benjamin Kaplan benjamin.kap...@case.edu wrote: I don't know if anyone considers python's incomplete implementation of closures a feature but it's documented so it's not really a bug either. I believe there is a trick with default arguments to get this to work, but I don't use lambdas enough to remember it. -- http://mail.python.org/mailman/listinfo/python-list Well default arguments isn't the only way - and *sometimes* it's not workable. Another way to make closures in Python is to define the function a within function b which returns function a and in your loop call function b. i guess if you wanted to do that purely with lambas (outside of using default arguments like i=i) you'd have to do something like a = [] for x in xrange(10): a.append((lambda x: lambda: x)(x)) never tried that though.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
i'm pretty new to javascript programming, but i'm pretty sure you just need ajax, which AFAIK is a highly technical way of saying using javascript in a way that makes web pages interactive JSON afaik is a way of data to and from the server that allows for lists and more variable types and such, but also requires the user download a third-party js file that implements JSON. i don't think you'd technically need JSON, because you could simply send the server a string of all the colors selected delimited by a space or | or something. javascript also probably has inherent functions for generating xml, considering that the object you use to communicate with the server is an xmlhttprequst. but i think xml might be overkill in this case. the javascript would populate the list for the colors the user selects (the easiest way would probably be to give the list an id and use getElementByID()), and then when he's done it would create an xmlhttprequest object to send the data to the server. On Mon, Nov 30, 2009 at 7:26 AM, Victor Subervi victorsube...@gmail.com wrote: Hi; I need a recommendation. I want to print out data like this: td bgcolor='blue'a href='???'blue/a/td td bgcolor='red'a href='???'red/a/td and enable the user to select the various colors he wants to add to a list that would populate itself on the same page where the selections are, and then, once he's selected all the colors he wants, click to add them all at once to a table in a database, and move on to the next page. I believe this is achieved through JSON and AJAX; however, I haven't been able to google any demonstrations of this sort. Am I correct, or should I use some other sort of technology? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from a text file
i don't understand the point of using 'with' but i don't understand what 'with' does at all i've tried to understand it a few times anyway here: import random result = random.choice(open(c:\\test.txt).readlines()) On Mon, Nov 30, 2009 at 10:41 AM, Tim Golden m...@timgolden.me.uk wrote: Olof Bjarnason wrote: 2009/11/27 baboucarr sanneh sanne...@hotmail.com: hi all i would like to create a python program that would read from a text file and returns one result at random. e.g in the text file i have these data 1.hello 2.my name 3.is 4.World Your help is highly appreciated..thnx in advance Hi babourarr; import random with open(c:/test.txt) as f: lines = f.read().splitlines() random_line = lines[random.randrange(len(lines))] print(random_line) Or, slightly more simply: import random with open (c:/test.txt) as f: print random.choice (list (f)) You need the list () because random.choice only works on a finite iterable. TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi victorsube...@gmail.com wrote: On Mon, Nov 30, 2009 at 1:39 PM, inhahe inh...@gmail.com wrote: i'm pretty new to javascript programming, but i'm pretty sure you just need ajax, which AFAIK is a highly technical way of saying using javascript in a way that makes web pages interactive JSON afaik is a way of data to and from the server that allows for lists and more variable types and such, but also requires the user download a third-party js file that implements JSON. i don't think you'd technically need JSON, because you could simply send the server a string of all the colors selected delimited by a space or | or something. javascript also probably has inherent functions for generating xml, considering that the object you use to communicate with the server is an xmlhttprequst. but i think xml might be overkill in this case. the javascript would populate the list for the colors the user selects (the easiest way would probably be to give the list an id and use getElementByID()), and then when he's done it would create an xmlhttprequest object to send the data to the server. If I'm not mistaken, that won't help me actually print to screen the user's choices as he selects them, which in my application, is important. Please advise. TIA, V sure, that's where this part comes in: the javascript would populate the list for the colors the user selects (the easiest way would probably be to give the list an id and use getElementByID()) so basically you'd define, e.g., an onClick=blah('red'); return true within the red element's tag, and then define a function blah(x) that says getElementById(my_list_id).innerHtml += br + x; and of course give your list textarea an id=my_list_id attribute in the tag. that could be slightly wrong, my javascript's rusty -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
On Mon, Nov 30, 2009 at 12:58 PM, inhahe inh...@gmail.com wrote: On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi victorsube...@gmail.com wrote: If I'm not mistaken, that won't help me actually print to screen the user's choices as he selects them, which in my application, is important. Please advise. TIA, V sure, that's where this part comes in: the javascript would populate the list for the colors the user selects (the easiest way would probably be to give the list an id and use getElementByID()) so basically you'd define, e.g., an onClick=blah('red'); return true within the red element's tag, and then define a function blah(x) that says getElementById(my_list_id).innerHtml += br + x; and of course give your list textarea an id=my_list_id attribute in the tag. that could be slightly wrong, my javascript's rusty also don't forget to sanitize the data you receive before committing it to the database, or someone can hack the javascript and send an SQL injection attack -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about list-creation
On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune manuel.gra...@koeln.de wrote: Hello, in (most) python documentation the syntax list() and [] is treated as being more or less the same thing. For example help([]) and help(list()) point to the same documentation. Since there are at least two cases where this similarity is not the case, (see below) can someone explain the reasoning behind this and point to further / relevant documentation? (To clarify: I am not complaining about this, just asking.) 1.) when using local variables in list comprehensions, say a=[i for i in xrange(10)] the local variable is not destroyed afterwards: print a,a print i,i using the similar code b=list(j for j in xrange(10)) the local variable is destroyed after use: print b,b print j,j I could be wrong, but I think this was actually a bug that was fixed later. and 2) a=list([]) vs. b=[[]] those don't return the same thing list([]) will create a shallow copy of [], which will of course be [] i can't think of a place where you'd want to use list() instead of [], but sometimes you might want to use 'list', such as in a defaultdict, in which case it's being used as a factory Regards, Manuel Graune -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about list-creation
i should also mention that a=[i for i in xrange(10)] and b=list(j for j in xrange(10)) isn't really just a difference of using [] vs. list() the first case is a list comprehension, the second case is a generator comprehension which is then converted to a list (the bug only applies to list comprehensions, not generator comprehensions) i.e. notice that you can do this ''.join(x for x in ['a','b','c']) no list or [] involved - it's just a generator comprehension being passed to a function. On Mon, Nov 30, 2009 at 1:12 PM, inhahe inh...@gmail.com wrote: On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune manuel.gra...@koeln.de wrote: Hello, in (most) python documentation the syntax list() and [] is treated as being more or less the same thing. For example help([]) and help(list()) point to the same documentation. Since there are at least two cases where this similarity is not the case, (see below) can someone explain the reasoning behind this and point to further / relevant documentation? (To clarify: I am not complaining about this, just asking.) 1.) when using local variables in list comprehensions, say a=[i for i in xrange(10)] the local variable is not destroyed afterwards: print a,a print i,i using the similar code b=list(j for j in xrange(10)) the local variable is destroyed after use: print b,b print j,j I could be wrong, but I think this was actually a bug that was fixed later. and 2) a=list([]) vs. b=[[]] those don't return the same thing list([]) will create a shallow copy of [], which will of course be [] i can't think of a place where you'd want to use list() instead of [], but sometimes you might want to use 'list', such as in a defaultdict, in which case it's being used as a factory Regards, Manuel Graune -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
On Mon, Nov 30, 2009 at 1:21 PM, Victor Subervi victorsube...@gmail.com wrote: On Mon, Nov 30, 2009 at 2:00 PM, inhahe inh...@gmail.com wrote: On Mon, Nov 30, 2009 at 12:58 PM, inhahe inh...@gmail.com wrote: On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi victorsube...@gmail.com wrote: If I'm not mistaken, that won't help me actually print to screen the user's choices as he selects them, which in my application, is important. Please advise. TIA, V sure, that's where this part comes in: the javascript would populate the list for the colors the user selects (the easiest way would probably be to give the list an id and use getElementByID()) so basically you'd define, e.g., an onClick=blah('red'); return true within the red element's tag, and then define a function blah(x) that says getElementById(my_list_id).innerHtml += br + x; and of course give your list textarea an id=my_list_id attribute in the tag. that could be slightly wrong, my javascript's rusty also don't forget to sanitize the data you receive before committing it to the database, or someone can hack the javascript and send an SQL injection attack Good call! However, in my case I can put this all behind a firewall. It's only for the shop builder's use, and that's my client...whom I can track! But I presume this would entail doing searches for and eliminating all unnecessary characters, right? V depends on if you're using python or php on the server side if you're using Python, just use parameterized sql, which completely avoids the issue of sql injection if you're using php, parameterized sql is kind of pain in the ass, but it includes a function for sanitizing strings so you don't have to make one yourself. if i remember correctly though, my friend and i had issues with that function, for example ' would be saved as \' in our database, or something like that i'm not sure which characters you need to eliminate to sanitize sql parameters.. i wouldn't be comfortable relying on my own function to do that without thoroughly researching the issue... and i'd probably just rather find a function that's already been written -- http://mail.python.org/mailman/listinfo/python-list
Re: High-performance Python websites
On Wed, Nov 25, 2009 at 7:33 PM, ShoqulKutlu kursat.ku...@gmail.com wrote: Hi, Managing load of high volume of visitors is a common issue for all kind of web technologies. I mean this is not the python issue. This issue is mostly about server level designs. You need to supply load balancing for both web servers and databases to make your web site able to respond to several concurrent visitors. Of course a good programmed website is a key performance issue but for your mention I would also suggest considering how many hardwares, how many webservers, how many database cluster and which database server should be used or will be used in the future.. I don't know a lot about this issue, but take apache + php. every time a page is loaded a new instance of php is loaded to run the page, so i imagine load balancing can easiry be done on the page request level by distributing instances of php processes. whereas if you use python, you don't really want to load the python interpreter for every page request. as far as i can tell, the canonical way is to have one app for the whole website that's constantly running and communicates with the server via WSGI. or is that wrong? and wouldn't that make load balancing a little bit more tricky, or at least different? not sure.. -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
On Mon, Nov 30, 2009 at 1:53 PM, Chris Rebert c...@rebertia.com wrote: On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Esmail wrote: Wow .. never heard of Concatenative_languages languages before or the distinction you make. Your distinction explains the behavior, but I find it somewhat counter-intuitive. You shouldn't find it any more surprising than the fact that a = 2 + 3 print a * 5 gives a different result from print 2 + 3 * 5 On Mon, Nov 30, 2009 at 3:41 AM, inhahe inh...@gmail.com wrote: one point of confusion could be the use of ** instead of superscript. it might make things a little bit more counterintuitive-looking than with superscripts, since the issue with Well, since source code is almost universally just plain ASCII and not in some file format with typesetting, superscripts aren't going to happen any time soon. (Also, avoid top-posting in the future.) i wasn't suggesting it as a feature for python, just pointing out why it might seem counterintuitive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Completely OT
On Mon, Nov 30, 2009 at 2:17 PM, Lie Ryan lie.1...@gmail.com wrote: On 12/1/2009 5:00 AM, inhahe wrote: On Mon, Nov 30, 2009 at 12:58 PM, inhaheinh...@gmail.com wrote: On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi victorsube...@gmail.com wrote: If I'm not mistaken, that won't help me actually print to screen the user's choices as he selects them, which in my application, is important. Please advise. That's where Javascript kicks in. You only need to use the javascript to modify your document (visual effect); you won't need it to submit to the server (the real action). Oh yes, good point - even though (if he were still going to go the JavaScript route) he'd modify the textarea using javascript, a regular submit button could be used because it'll submit the current contents of that textarea all the same. also don't forget to sanitize the data you receive before committing it to the database, or someone can hack the javascript and send an SQL injection attack Or a XSS attack (Cross-site scripting). Basically, you want to check whether the string received by the server matches your own predefined list of colors before storing to the database. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
On Mon, Nov 30, 2009 at 2:05 PM, Lie Ryan lie.1...@gmail.com wrote: On 12/1/2009 5:58 AM, inhahe wrote: i wasn't suggesting it as a feature for python, just pointing out why it might seem counterintuitive. I'm interested, what do YOU (inhahe) think the result should be? Should both become -9 or both become 9. What was your expectation when you wrote that post? -- http://mail.python.org/mailman/listinfo/python-list i think the way it works currently is the sane way..pays respect to the standard order of operations, doesn't have to do anything special with x = -3, just treats it as an integer, and corresponds with normal algebra. -- http://mail.python.org/mailman/listinfo/python-list
Re: Filling in a tuple from unknown size list
maybe that thing in python 3 that someone mentioned is the answer, but otherwise i always think Python should admit something like this: a, b, c, *d = list i.e. if list were [1,2,3,4,5], you'd get a=1, b=2, c=3, d=[4, 5] not that that solves the None problem, though i don't have any feature suggestions that would address that. On Fri, Nov 27, 2009 at 7:18 AM, boblatest boblat...@googlemail.com wrote: Hello all, (sorry for posting from Google. I currently don't have access to my normal nntp account.) Here's my question: Given a list of onknown length, I'd like to be able to do the following: (a, b, c, d, e, f) = list If the list has fewer items than the tuple, I'd like the remaining tuple elements to be set to None. If the list is longer, I'd like the excess elements to be ignored. The code snippet below does what I want, I was just wondering if there was an interesting Pythonic way of expressing the same thing. Thanks, robert def iter_inf(li, n): for i in range(n): if i len(li): r = li[i] else: r = None i += 1 yield r li = ['a', 'b', 'c'] (a, b, c, d, e) = iter_inf(li, 5) print a, b, c, d, e -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Filling in a tuple from unknown size list
On Sun, Nov 29, 2009 at 4:42 AM, inhahe inh...@gmail.com wrote: maybe that thing in python 3 that someone mentioned is the answer, but otherwise i always think Python should admit something like this: a, b, c, *d = list i.e. if list were [1,2,3,4,5], you'd get a=1, b=2, c=3, d=[4, 5] not that that solves the None problem, though i don't have any feature suggestions that would address that. Maybe instead of Python working this way: a, b = xrange(10) Traceback (most recent call last): File stdin, line 1, in module ValueError: too many values to unpack it should work this way: a, b = xrange(10) print a, b 0 1 and then they could include something in itertools that automatically fills extras with None, like Peter Otten's implementation but without having to pass it a value for the number of assignments, i.e.: a, b, c = itertools.ifill(list) with None being the default fill value, but if we wanted 1 to be, we could do a, b, c = itertools.ifill(list, 1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: String-inferred names
On Sun, Nov 29, 2009 at 5:15 AM, The Music Guy fearsomedragon...@gmail.comwrote: Okay, I'm having a really hard time telling which messages are getting on to the list and which ones aren't. Some of the messages I send show up in the comp.lang.python mirror in Google Groups, and some aren't. Others show up on the Groups mirror, but don't show up in Gmail, or show up in a different order. It seems the only way I can guarantee anything showing up on Groups is to post on Groups, but that makes it difficult because I can't see the messages in the thread that only appear in my inbox. Is there a quick fix for this, because it's getting pretty aggravating trying to figure out who heard what. I don't like mailing lists. :P -- http://mail.python.org/mailman/listinfo/python-list Did you say you were using gmail to post? I think mailing lists tend to have issues with gmail because it puts html in the message or something like that. Btw I recently set up this mailing list to send me a message back when I successfully posted something. oddly enough, i only remember getting one such message, so maybe none of my other messages got through. :P i think there's a way to disable html when sending a gmail message, but don't quote me on that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Arcane question regarding white space, editors, and code collapsing
I had this same problem with an application called Notepad++, which is a shame because I like the way it works and it's nice and tight. Now I use Komodo Edit instead, which doesn't have that problem, and has all the features of Notepad++ but just isn't as fast. Also all the colors were awful, and I realized Notepad++'s were perfect so I spent some time using GetColor! to sample every token color Notepad++ uses and configure Komodo Edit to do the same. I guess this is all irrelevant information since you don't even use a PC, but I just wanted to say that apparently this strange problem is a popular phenomenon. And that Komodo Edit is cool. On Wed, Nov 18, 2009 at 6:28 PM, Wells we...@submute.net wrote: I work in TextMate a lot, which I generally love, but it's code collapsing confounds me. Essentially you have to indent blank lines to the proper level for the current block. Then it will collapse that section as one section. If you have simply a new line, it will see it as a break, and not collapse, though the python interpreter doesn't care- it only cares about lines of actual code. Is it... pythonic, then, to have these lines of tabs/spaces to support code collapsing? Is it proper, improper, or irrelevant? Thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
staticmethod not callable? (trying to make a Singleton metaclass..)
I'm trying to come up with a system for singletons, where I don't have to modify anything for an individual class except to define __metaclass__ or, if possible, to inherit another class. I want it to raise an error if making a duplicate instance of a class is attempted, rather than to return the same object, because my philosophy is that if your class is a singleton and you're trying to make another instance of it then you're doing it wrong and you should probably know. Although the way I'm trying to do it could apply to either philosophy. I've seen several solutions for singletons in Python, but I don't like them, either because they require modification to each individual singleton class, or they require something after the class definition like Class = Class(), or I totally don't understand them. The novel way I've attempted to come up with is this: class Singleton(type): def __new__(meta, classname, bases, classDict): @staticmethod def nonewinst(*args, **kwargs): raise ValueError(Can't make duplicate instance of singleton + classname) @staticmethod def newoldnew(obj): return obj oldnew = classDict.get(__new__, newoldnew) @staticmethod def newnew(obj, *args, **kwargs): o = oldnew(obj, *args, **kwargs) obj.__new__ = nonewinst return o classDict[__new__] = newnew return type.__new__(meta, classname, bases, classDict) a little bit of experimentation revealed that apparently even functions defined within a method become class methods, so i tried making them all static methods. however, python is strange to me when it comes to methods and the self parameter. i mean i understand a function being free of the class so that the 'self' parameter doesn't mean anything in particular unless you explicitly pass it an instance. and i understand the method being bound to an object so that when it's called its self parameter is automatically sent the instance. but python seems to have this in-between mode where sometimes a function isn't particularly bound to an instance but if you try to pass the wrong kind of instance to 'self' it'll complain, which gets annoying, and i don't understand how its binding works. but anyway, the problem i'm currently having with the code might not even be related to that..because here's the error I'm getting: from funcs import Singleton class A: ... __metaclass__ = Singleton ... b = A() Traceback (most recent call last): File stdin, line 1, in module File c:\python25\funcs.py, line 68, in newnew o = oldnew(obj, *args, **kwargs) TypeError: 'staticmethod' object is not callable i'm not that experienced with metaclasses, but it seems to me that something's obviously going fubar here because at that point oldnew should be the function newoldnew (since class A doesn't have a __new__ defined) which is clearly defined right there with a staticmethod decorator, and first of all, functions *should* be callable, and secondly, why is my object a 'staticmethod' object just because I used a decorator on it? it would seem it should be a function, so i tested it like this: class A: ... @staticmethod ... def b(): pass ... type(A.b) type 'function' in that case, using @staticmethod returns a function. i have nfi why it's different in my Singleton class. oh, and thirdly, staticmethod is a decorator and decorators are callables so even given that for some mysterious reason it's a staticmethod object i don't know why it's not callable. so that's pretty confusing. can anyone clear this up for me? thanks.. ps. i'm aware of the evils of singletons and all that. short answer: I don't care. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Number of distinct substrings of a string [continuation]
On Sun, Nov 29, 2009 at 9:10 AM, n00m n...@narod.ru wrote: Even if Py by 4x *slower* -- it's still a perfect Ok for it (C# will be much (much) slower than Python). How do you figure? As far as I know C# is many, many times faster than Python. (i was disappointed to find out that even IronPython is dozens of times slower than other .net langs) -- http://mail.python.org/mailman/listinfo/python-list
Re: * for generic unpacking and not just for arguments?
On Sun, Nov 29, 2009 at 10:40 AM, Mel mwil...@the-wire.com wrote: Russell Warren wrote: Maybe it's just that * is strictly for arguments, and trying it for generic tuple unpacking is abuse (which is down the corridor in 12A). I'd agree with that. It's a feature of function calls, not a feature of sequence types, so that you can handle a set of function arguments as a bunch, and apply them when you want. The other function call feature that sequence types don't do is a, b, c = **{'b':3, 'c':a, 'a':c} Mel. that's wicked i'd go for that i'd definitely go for the a, b, *c = lst syntax though -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
On Sun, Nov 29, 2009 at 8:04 PM, Esmail ebo...@hotmail.com wrote: Chris Rebert wrote: Wow .. never heard of Concatenative_languages languages before or the distinction you make. Your distinction explains the behavior, but I find it somewhat counter-intuitive. (I use the Python interpreter frequently for small calculations - otherwise I'd never have realized this) Well I think of it like this -3**2, because of the order of operations as you know, groups as -(3**2) now if you set x to -3, (-3) is now automatically, inseparably grouped. so in a sense by setting x to that you're grouping it. x == (-3) x**2 == (-3)**2 if it still seems counterintuitive, what about the fact that it's exactly the same way in Algebra? basic algebra: -3(superscript)2 is -9 but if x is -3, then x(superscript)2 is 9 -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: String-inferred names
i like this idea (i posted some thoughts on it in the blog, but it's not approved yet as of this writing) in short, i suggested extending the idea to make it more a) generalized, b) simple, c) intuitive, and d) flexible. so instead of just using $ for attributes, you could use it anywhere you define or reference a name. as in.. class $a: pass or $a = 1 also, you might want to do something like this b = [zero, one] $b[0] = 0 but that's ambiguous, so you need some sort of grouping mechanism like for example ${b[0]} = 0 although $(b[0]) = 0 might be just as reasonable. also maybe: b = 'bar' foo$b = 'baz' print foobar #prints baz ${b}foo = 'baz' print barfoo #prints baz $foo{b}baz = 1 print foobarbaz #prints 1 but i know that last idea is getting way into php-land and probably isn't (quote-unquote) necessary. i know a lot of people would probably hate this idea with a passion. i tend to be more liberal when it comes to adding concision and dynamicism in a language, although that could be just because it's too tempting; i.e., maybe it's only because somebody drew a line somewhere that we're coding in Python instead of K. -- http://mail.python.org/mailman/listinfo/python-list
classes riddle
Can somebody clear this up for me? -- Class B(A): def __init__(self, a) A.__init__(a) self.a = a a = A() ba = B(a) bc = B(a) bd = B(a) -- I'm not sure what A.__init__ here does. I would think its __init__ is designed specifically to run once for any given object.. so i'm not sure what happens. and if A calls self.blah(), which instance of B which overrides blah gets called? -- http://mail.python.org/mailman/listinfo/python-list
Re: The rap against while True: loops
On Mon, Oct 19, 2009 at 1:55 PM, inhahe inh...@gmail.com wrote: On Sat, Oct 10, 2009 at 6:34 PM, Mensanator mensana...@aol.com wrote: On Oct 10, 5:02�pm, kj no.em...@please.post wrote: In 01ccc46d-5ea9-4dfe-ba22-699c6b859...@v36g2000yqv.googlegroups.com Mensanator mensana...@aol.com writes: In fact, if it were up to me, I would have made the fundamental looping construct something like repeat: � � � ... � � � if whatever(): � � � � � �break � � � ... So, the second set of '...' doesn't get executed. When I use while not done: ... if n==1: done = True ... the loop will actually complete (which is what I want) instead of aborting, like yours does. I just don't want the loop to execute again. Of course, this is why you would use while not done instead of while True or repeat in that situation, so i'm not sure what your contention is. Now, if I did a break before writing to the file, I would have to do all kinds of clean-up code outside the loop, code that would be run only if the exit were abnormal. This is why I propose an until keyword. until n == 1: ... i know some people don't like to add keywords unnecessarily, but i really like to be able to express programs in a way that reflects what we actually mean, when there's a simple way this could be provided and it's a common use case. i recognize the problem with my solution is that n might not even be defined until somewhere in the loop after until n == 1 is evaluated. this makes it a little weird, but it's not strictly a problem since the interpreter doesn't actually have to evaluate n == 1 until the tail end of the loop. and made all the other looping constructs as syntatic sugar for this one. Luckily, it's not up to you. condescending and manipulative, as it merely begs the question of luckily for whom -- him, or you kj -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
trouble with regex?
Can someone tell me why this doesn't work? colorre = re.compile ('(' '^' '|' '(?:' '\x0b(?:10|11|12|13|14|15|0\\d|\\d)' '(?:' ',(?:10|11|12|13|14|15|0\\d|\\d)' ')?' ')' ')(.*?)') I'm trying to extract mirc color codes. this works: colorre = re.compile ('\x0b(?:10|11|12|13|14|15|0\\d|\\d)' '(?:' ',(?:10|11|12|13|14|15|0\\d|\\d)' ')?' ) but I wanted to modify it so that it returns me groups of (color code, text after the code), except for the first text at the beginning of the string before any color code, for which it should return ('', text). that's what the first paste above is trying to do, but it doesn't work. here are some results: colorre.findall('a\x0b1,1') [('', ''), ('\x0b1,1', '')] colorre.findall('a\x0b1,1b') [('', ''), ('\x0b1,1', '')] colorre.findall('ab') [('', '')] colorre.findall('\x0b1,1') [('', '')] colorre.findall('\x0b1,1a') [('', '')] i can easily work with the string that does work and just use group starting and ending positions, but i'm curious as to why i can't get it working teh way i want :/ -- http://mail.python.org/mailman/listinfo/python-list
Python+Pyjamas+V8=ftw
I don't know how much the community knows about this - i haven't been participating much of late - but here's something amazing. Apparently javascript is just as dynamic as python, because someone made a python-to-javascript converter in just 1200 line (pyjamas). Meanwhile google's new javascript engine (v8) blew all the others out the water, raising the bar - and now safari and firefox already have already risen to that bar with their own jit js engines. The exciting thing is that python code converted to javascript runs on v8 10 times faster (http://www.advogato.org/article/985.html). Thus google's strategy in making the JIT compiler represents what Python could (and should) be. Python should either adapt v8, Tamarin (http://en.wikipedia.org/wiki/Tamarin_(JavaScript_engine), or similar to make its own JIT, or take their basic principles (http://www.youtube.com/watch?v=lZnaaUoHPhs) and recreate them for its own JIT from scratch. Until then, we can always install v8/tamarin/tracemonkey/squirrelfish and easily make a front-end that automatically uses pyjamas to convert python script to JS and runs it. Perhaps pyjamas needs some improvement to fully implement Python - the homepage isn't very clear on how exactly the JS implementation mirrors the Python implementation. Also I suppose it doesn't support Python 3.0 and would have to be changed to support that. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Yield statement
Alex Bryan [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Okay, so i don't really understand the Yield thing and i know it is useful. I've read a few things about it but it is all programming jargon and so basically it is hard for me to understand. So can anyone give me a description or link me to a site that has a good definition and/or examples of it? If you could I would really appreciate it. Really short answer: def f(): yield 1 yield 2 yield 3 for x in f(): print x, # should print 1 2 3 def f(): for x in xrange(10): yield x for x in f(): print x, # should print 0 1 2 3 4 5 6 7 8 9 note that this won't work; def f(): for x in xrange(10): for y in xrange(10): yield (x,y) yield just doesn't work right with multiple levels of loops. i had to discover that the hard way. -- http://mail.python.org/mailman/listinfo/python-list
How to import filenames with special characters?
How would I import a python file whose name contains characters like .'s or !'s? Is there really _no_ way to do that? I have to use plain jane letters and numbers for everything? -- http://mail.python.org/mailman/listinfo/python-list
Re: question
Gandalf [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On May 30, 12:14 am, John Henderson [EMAIL PROTECTED] wrote: Gandalf wrote: how do i write this code in order for python to understand it and print me the x variable x=1 def (): x++ if x 1: print wrong else : print x () Example: x=1 def (x): x += 1 if x 1: return wrong else : return x print (x) John mmm isn't their any global variable for functions? how about def (): y = x+1 if y 1: return wrong else: return y but if you really have to modify x outside of the scope of the function, well, i guess one possibility is to return a tuple, one element being a string that may or may not contain the word wrong and another being x, and then whatever's calling can change x in their own scope based on the return value. but other than that, the normal way to affect a variable beyond the scope of your function is to make a class and affect a class variable. although there is always the 'global' statement also. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with py2exe
i used py2exe with python 2.5 and it worked fine just the other day. py2exe-0.6.6.win32-py2.5.exe was the download filename. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dear Members of the group, py2exe does not seem to be integrating with 2.5 or later versions. I was trying to run it but requested only for 2.3. How can I run it? If any one can kindly help. Regards, Subhabrata Banerjee. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
Bruno Desthuilliers [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Brad a écrit : cm_gui wrote: Python is slow. It ain't C++, but it ain't a punch card either... somewhere in between. I find it suitable for lots of stuff. I use C++ when performance really matters tho... right tool for the job. Learn a good interpreted language (Pyhton) and a good compiled language (C or C++) LordHaveMercy(tm). Could you guys please learn what you're talking about? 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. That's like saying being spherical is not a property of planets, it's a property of an instanciation of a planet. Let alone that a) all known planets are spherical (all implementations of Python are not natively compiled (and you said for whatever definition)), and b) It's a far cry to imagine a planet coming into being that's not spherical (a language as dynamic as Python, or most other scripting languages, would be either extremely difficult or impossible to make a native compiler for). I guess I should also mention that Python isn't very practical (as in suitable, right tool for the job, and perfomance, as mentioned in the above post) without an implementation. So I don't think this distinction has any use other than to beat other people over the head with a bat. 2/ actually, all known Python implementations compile to byte-code. Which is then interpreted, but you're still technically right, because compiled can mean either compiled to bytecode or compiled to native code, despite what it actually did mean. Semantics FTW!! -- http://mail.python.org/mailman/listinfo/python-list
Re: call f(a, *b) with f(*a, **b) ?
Nick Craig-Wood [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] bukzor [EMAIL PROTECTED] wrote: That does, in fact work. Thanks! I'm a little sad that there's no builtin way to do it, owell. def f(a, *args): ... print a ... for b in args: print b ... import inspect a = [2,3] b = {'a':1} inspect.getargspec(f) (['a'], 'args', None, None) map(b.get, inspect.getargspec(f)[0]) [1] map(b.get, inspect.getargspec(f)[0]) + a [1, 2, 3] f(*map(b.get, inspect.getargspec(f)[0]) + a) 1 2 3 If I saw that in my code I'd be wanting to get rid of it as soon as possible! I'd re-write f() to have all named arguments then the problem becomes easy and the answer pythonic (simple dictionary manipulation)... So instead of f(a, *args) have f(a, list_of_args). The f(*args) syntax is tempting to use for a function which takes a variable number of arguments, but I usually find myself re-writing it to take a list because of exactly these sort of problems. In fact I'd be as bold to say that f(*args) is slightly un-pythonic and you should avoid as a user interface. It does have its uses when writing polymorphic code though. (I second that) the function should definitely be changed if possible. it's hard to say what the real constraints of the problem are, so I just answered his question as if that's what he actually needed (assuming the length of the list and number of named arguments would be variable). if we assume the constraints are that: 1.he has list, l 2.he has a dictionary, d 3.he wants the function to print the values in the dictionary according to a specific order of their keys as defined by the function, followed by the values of the list then: def f(d, l): order_of_keys = ['a'] for key in order_of_keys: print d[key] for element in l: print element #not tested -- http://mail.python.org/mailman/listinfo/python-list
Re: call f(a, *b) with f(*a, **b) ?
inhahe [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] if we assume the constraints are that: 1.he has list, l 2.he has a dictionary, d 3.he wants the function to print the values in the dictionary according to a specific order of their keys as defined by the function, followed by the values of the list It's also possible (even likely) that he knows outside of the function what order he wants the values in, and only used an (incidentally) unordered dict called kwargs because he thought that's the only way to pass to those parameters. in which case the function could be left untouched and the he would call it like this: args = [1,2,3] f(*args) or f(*[1,2,3]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
To be more specific, let's say I want to create a simple, 2D strategy game. It will have a board layout like chess or checkers and the player will move around the board. Let's say this is all I know, and perhaps I don't even know *this* for sure either. Is it possible to write the logic for such a game at this point? Maybe even this is possible. But here you are not only drawing the line between GUI and logic but also within the logic part itself because the board layout isn't (just) a GUI issue. If you have checkers, hexagons, or other shapes also has influence on the logic part, because you need slightly different algorithms for finding ways from tile `A` to tile `B`, or to decide when a piece is blocked by others, and how the rules to move pieces around look like. Just imagine how to modify chess rules to a board with hexagonal patterns. It would severely change the logic part. purelyacademicIf the GUI defines that it's a board layout like chess or checkers and the player will move around the board, it's hard to say what's left for the logic part to do. I can't think of any generalization for the fact that it's a 2D strategy game. You could have a 2-dimensional array, the size of which is determined by the GUI, but even motion on it would have to be defined by the GUI, in which case the GUI would simply be using the logic part for storing the array and accessing it via index values. And then there's no reason not to put the array inside the GUI. Although it would help if only your logic part could provide persistence. Also, the logic part could provide many useful functions that games are likely to use, but then it's more like a library than anything else. Secondly, it's unclear whether the fact that it's a 2D strategy game was included in what he might not know, and in that possible case, strictly speaking, he didn't define anything that the logic part *does* know, and it being an example, one could theorize that that logically implies the logic part of the program is null. Another example could be printing messages to the player. If I need to say You killed the monster!, is there a general way to write this, or do I need to specifically refer to GUI widgets and methods, etc. in order for it to be displayed properly? The observer pattern can be used here. The GUI has to register a callback function with your logic engine and every time you want to inform the player about something, your game logic calls that function with the message. It doesn't have to know if it will be rendered as graphic on screen, displayed as text in a terminal, or synthesized as sexy female computer voice. If the function name to register the callback function is hard-coded into the logic part and into the GUI, then so can the name of the callback function itself be, so that it doesn't need to be a callback, barring only the possibility of the callback function being changed from one instance to the next by the particular GUI, and even that can be done without a callback simply by reassigning the name, or in C++ you could cast a pointer to function within the hard-coded function and call it and and change that pointer when desired. Not that I know anything about MVC./purelyacademic -- http://mail.python.org/mailman/listinfo/python-list
Re: call f(a, *b) with f(*a, **b) ?
I wish this worked: def main(a,b,*argv): pass options['argv'] = argv main(**options) TypeError: main() got an unexpected keyword argument 'argv' - I was thinking about that exact same thing actually. Except that I was thinking you might want it like this, otherwise it could be ambiguous: def main(a,b,*argv): pass options['*argv'] = argv main(**options) Weird I know, to put the * operator inside the string. I suppose the necessity of doing that just shows why it wasn't implemented in the first place. But still, it would be neat... Also, of course, you could then do main(*argv=[2,3]) or rather main(*argv=[3,4],a=1,b=2) #in random order -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is math.pi slightly wrong?
Dutton, Sam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Thanks for all the answers and comments. math.pi is exactly equal to 884279719003555/281474976710656, which is the closest C double to the actual value of pi So much for poor old 22/7... Sam The biblically correct version: import math math.pi = 3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
Paul Rubin http://[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] inhahe [EMAIL PROTECTED] writes: planets are spherical (all implementations of Python are not natively compiled (and you said for whatever definition)), and b) It's a far cry to imagine a planet coming into being that's not spherical (a language as dynamic as Python, or most other scripting languages, would be either extremely difficult or impossible to make a native compiler for). There are native Python compilers, see psyco and pypy. That does complicate the question since there are 4 levels of executing code interpreted bytecode-compiled-interpreted jit-complied natively compiled i've tried psyco a few times and never noticed much of a speed increase. if any. and then on the other hand, .net is supposed to be almost as fast as C because of its JIT. but the whole issue of the speed of .net seems to be enshrouded in mystery, so who knows. -- http://mail.python.org/mailman/listinfo/python-list
Re: persistent deque version 4
inhahe [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] 4. can someone tell me if the way i'm using the decorator is sane? i've never used decorators before. it just seems ridiculous to a) define a lambda that just throws away the parameter, and b) define a meaningless function to pass to that lambda. I thought about the fact that a decorator is merely syntactic sugar, so it shouldn't have any closure magic that I can't make myself, and I realized that I could have done it the following way: def makefunc(func): def func2(instance, *args): result = func(instance, *args) instance.save() return result return func2 for name, func in deque.__dict__.items(): if (not name.startswith(_)) or name in ('__delitem__', '__setitem__'): setattr(pdeque, name, makefunc(func)) -- http://mail.python.org/mailman/listinfo/python-list
Re: conventions/requirements for 'is' vs '==', 'not vs '!=', etc
Ma: Symbolic identity is a mathematical relation Mb: Symbols are acausal m: Matter is causal C: Symbolic identity is not defined on matter. What is defined on matter then? You're saying all symbolism is not defined on matter. Much of our thinking about the world itself is symbolic. How do we 'define on matter' without thinking about it? Definition is another symbolic thinking thing we do. What does it mean to 'define on matter'? If you were to paint symbol/matter like the mind/body problem interpreted on dualism (not to beg the question, but just to say if you're saying they're different substances) then some people would ask, how does one thing interact with the other? You could say that symbols don't exist and inferring symbols is just a way of thinking of the world, but since we think in symbols, thinking becomes something that doesn't exist and is inferred from a way of thinking about the world, which doesn't exist and is inferred from a way of thinking about the world, etc. I don't think you can say that thought-symbolism is a different question from mathematical symbolism because Aristotle inferred a is a directly from the way we think about the world. cf: a is a True Perhaps symbols and symbolic identity are defined as algorithms which happen in the real world to come to a conclusion. It raises the question of how causal an algorithm is. But if you call an algorithm 'a way of doing something' then it's much more down-to-Earth. But it raises the question of how we define the boundaries of whether doing something is 'doing that thing' (since an algorithm is strictly formal and mathematically deterministic), given that you never step in the same river twice, since you then have to define the boundaries of determining whether doing something falls within the boundaries or not, ad infinitum. I don't have a conclusion. Suffice it to say it obviously works out somehow. I'm just wondering about what 'defined on matter' means. -- http://mail.python.org/mailman/listinfo/python-list
Re: conventions/requirements for 'is' vs '==', 'not vs '!=', etc
inhahe [EMAIL PROTECTED] wrote in message news:... Ma: Symbolic identity is a mathematical relation Mb: Symbols are acausal m: Matter is causal C: Symbolic identity is not defined on matter. I do think though that a computer languages claiming operations on 'identity', as vis a vis 'equivalence', is completely contrived, as in, it's just an arbitary distinction about the way in which we're going to compare bits. -- http://mail.python.org/mailman/listinfo/python-list
Re: conventions/requirements for 'is' vs '==', 'not vs '!=', etc
inhahe [EMAIL PROTECTED] wrote in message news:... inhahe [EMAIL PROTECTED] wrote in message news:... Ma: Symbolic identity is a mathematical relation Mb: Symbols are acausal m: Matter is causal C: Symbolic identity is not defined on matter. I do think though that a computer languages claiming operations on 'identity', as vis a vis 'equivalence', is completely contrived, as in, it's just an arbitary distinction about the way in which we're going to compare bits. Although I suppose it counts for something that if a is b, in Python, then the data referenced (at the end of the chain) by those two names occupies the same physical transistors in the RAM module, although that's still a level removed in that the so-called identity would change with time as the electrical condition in the transistors changes. But as far as the transistors being physically the same goes, a is b actually closely corresponds to vernacular identity by way of reference vs. referent in the theory of linguistics. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is math.pi slightly wrong?
Dutton, Sam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) Is this a precision issue, or from the underlying C, or something else? How is math.pi calculated? I searched for this on the web and in this group and couldn't find anything -- but humble apologies if this has been asked before/elsewhere. Sam Dutton it's gotta be a precision issue. floating point numbers are stored on computers in binary. you can't necessarily change the last digit from 1 to 2 just by changing the last bits. try converting a value after the decimal point to the same value after a decimal point in binary. there's no telling how many bits it'll take. and sometimes even, what isn't a repeating decimal in one base is in another base. i see these precision issues raised all the time. why is my value resulting in 3.611? the answer is because you can't store 3.61 in binary. (i don't know specifically about that number, just an example) (i know you can, if you use some sort of binary representation of decimal digits... but that's not how it's usually done. it's stored pretty much like in scientific notation but in base 2.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is math.pi slightly wrong?
Dutton, Sam [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) Another way of saying it is: 3.1415926535897932 is of course an approximation. It's the closest approximation to pi given X digits in base 10. In base 2 the closest approximation to pi given Y digits is different. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
I don't get what the issue is between sites that use Python and being slow, if there is one, because there's a website online that shows the results of a dozen or so benchmarks when comparing any two languages. Python beats PHP in almost all the benchmarks. (it also beats almost all the other languages (they're all scripting languages) in most of the benchmarks, lua being the only exception i remember.) cm_gui [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Python is slow.Almost all of the web applications written in Python are slow. Zope/Plone is slow, sloow, so very slooow. Even Google Apps is not faster. Neither is Youtube. Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster than Python. Okay, they probably use caching or some code compilation -- but Google Apps and those Zope sites probably also use caching. I've yet to see a web application written in Python which is really fast. -- http://mail.python.org/mailman/listinfo/python-list
Re: import X vs from x import *
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] import Tkinter from Tkinter import * i have a program where if i comment out either of those import- statements i get an error. i thought they meant the same thing and from was supposed to be just to imort just a specific function and the * imports everything in the module. but aparently the above statements have diffrent meaning and i cant figure it out fromt he tutorials. the first statement imports tkinter but everything inside of tkinter in stored in the tkinter namespace, in other words if tkinter has a class tk, then tk would be accessed as tkinter.tk. for example import tkinter blah = tkinter.tk() if you do from tkinter import *, then everything in tkinter is imported at the top level, so it would be from tkinter import * blah = tk() -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning to 'try' block after catching an exception
Might have a stack overflow issue, if it retries too many times? alex23 [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On May 22, 6:15 pm, Karlo Lozovina [EMAIL PROTECTED] wrote: Because when you expect exception to occur on something like 0.01% of cases, and you have 4 or 5 exceptions and the code to test for each conditions that cause exceptions is quite long and burried deep inside some other code it's much better to do it this way ;). Too bad there's no syntactic sugar for doing this kind of try-except loop. I'm surprised your unit tests let it get to such a state... ;) How about something like this? retry, total_fail = False, False try: some_function() except SomeException: some_function2() some_function3() retry = True finally: if retry: try: some_function() except SomeException: total_fail = True Using 'finally' seems more explicit about it being part of the exception handling than using a loop construct. Actually, this is even more direct: try: some_function() except SomeException: some_function2() some_function3() try: some_function() except SomeException: raise SomeError -- http://mail.python.org/mailman/listinfo/python-list
Re: Producing multiple items in a list comprehension
Joel Koltner [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Is there an easy way to get a list comprehension to produce a flat list of, say, [x,2*x] for each input argument? E.g., I'd like to do something like: [ [x,2*x] for x in range(4) ] ...and receive [ 0,0,1,2,2,4,3,6] ...but of course you really get a list of lists: [[0, 0], [1, 2], [2, 4], [3, 6]] I'm aware I can use any of the standard flatten bits of code to turn this back into what I want, but I was hoping there's some way to avoid the lists of lists generation in the first place? A slightly similar problem: If I want to merge, say, list1=[1,2,3] with list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with zip to do so? Thanks, ---Joel i figured out a solution sum([x,2*x] for x in range(4)],[]) #not tested sum(zip(list1,list2),()) #not tested (you did say you knew of ways to flatten, but i dunno if you knew of that way or not) as an aside, i wish that sum didn't have to take the second parameter. it's kind of superfluous. it can just use the first item as the initial value instead of 0 when no initial value is specified. it would be a little complex to do without putting a conditional in your main loop and slowing it down, but it could be done. -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
I don't like php. I tried it once and I had it sort a list, but the list was apparently too long for its sorting function because it just sorted the first so-many elements of it and left the rest in order, and didn't generate any error. I like a language that's actually determined by what you tell it to do. I hear it has a lot of security issues too. I'm not sure that php *runs* faster than python, having seen benchmarks, but it certainly loads faster. Maybe not so much of a difference once python25.dll is already in the cache though (speaking from a windows perspective). because when i load a program it can take a while but it's pretty quick if i'd just loaded one recently. but you don't necessarily have to load python for each page rendering anyway. I like the Python language a lot better than php. but I just really like Python. php mixes html and code out-of-the-box (sort of.. i guess it's more like a reversal of which one is explicit)... if you use Python you should look into a 'templating engine' like mako. i use cheetah, but mako is supposed to be better. i think Python is the easiest language to learn, with the possible exception of qbasic (just because making multidimensional arrays in python isnt that obvious, although maybe it is using numpy, i've never tried it). Python isn't as easy as basic if you use/have to read the more advanced features, but those aren't even available in basic. so I find it a comfortable learning curve. -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading __getitem__
it seems like you can't do it exactly the way you're trying but you could do this def __getitem__(*args): if len(args) 1 and args[1]: return self.get(args[0]) * 5 return self.get(args[0]) then you would use it like print foo['a'] print foo['a',True] or even print foo['a',crazy] if you wanted. or crazy = True print foo['a',crazy] Andreas Matthias [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The following code doesn't run but I hope you get what I am trying to do. class my_dict (dict): def __getitem__ (self, key, crazy = False): if crazy == True: return 5 * self.get(key) else: return self.get(key) foo = my_dict() foo['a'] = 123 print foo['a'] print foo['a', crazy = True] Is it somehow possible to overload __getitem__ with an additional argument? Are there other possibilities to achiev this? Or is the only solution to this to write a normal function call `def my_get (self, key, crazy=False)'? Ciao Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading __getitem__
inhahe [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] crazy = True print foo['a',crazy] just to clarify, you could use it like: crazy = I'm crazy #this only has to be done once print foo['a'] #not crazy print foo['a',crazy] #crazy (this may be totally unPythonic, i don't know.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading __getitem__
actually i ddin't think about the fact that you're overloading dict, which can already take multiple values in getitem so how about class crazy: pass and then in your dict class: def __getitem__(*args): if args[-1] is crazy: return self.get(args[:-1])*5 else: return self.get(args) and then print foo[1,2] #not crazy print foo[1,2,crazy] #crazy I *think* that would work Andreas Matthias [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The following code doesn't run but I hope you get what I am trying to do. class my_dict (dict): def __getitem__ (self, key, crazy = False): if crazy == True: return 5 * self.get(key) else: return self.get(key) foo = my_dict() foo['a'] = 123 print foo['a'] print foo['a', crazy = True] Is it somehow possible to overload __getitem__ with an additional argument? Are there other possibilities to achiev this? Or is the only solution to this to write a normal function call `def my_get (self, key, crazy=False)'? Ciao Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading __getitem__
Apparently, args already is a tuple, so this should be: def __getitem__(self, args): Is this documented somewhere? I couldn't find it anywhere. Don't know, I just assumed it would take multiple arguments because I knew I had seen the form d[1,2] before, which incidentally is equivalent to d[(1,2)] so I guess it makes sense that args is a tuple. -- http://mail.python.org/mailman/listinfo/python-list
Re: call f(a, *b) with f(*a, **b) ?
bukzor [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This question seems easy but I can't figure it out. Lets say there's a function: def f(a, *args): print a for b in args: print b and elsewhere in your program you have a list and a dict like this: args = [2, 3] kwargs = {'a':1} I'd like to get f() to print something like the following, but I can't figure out how. 1 2 I think there's no 'standard' way to do this. but: import inspect f(*map(kwargs.get, inspect.getargspec(f)[0])+args) i don't know if it works because i'm afraid to try it. if it doesn't the solution is something similar to that. -- http://mail.python.org/mailman/listinfo/python-list
Re: call f(a, *b) with f(*a, **b) ?
1 2 actually, you don't want it to print 3 also? if not, then you would do f(*map(kwargs.get, inspect.getargspec(f)[0])+args[:1]) import inspect f(*map(kwargs.get, inspect.getargspec(f)[0])+args) -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
PHP can do that. There are also a number of templating engines available. The nice thing about PHP is you have a choice. i just meant that php is sort of invented to combine html and code, so if you use python instead you should use a templating engine. but i suppose it's useful for php too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing Space and - from a string
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Shakir, I have thousands of records in MS Access database table, which records I am fetching using python script. One of the columns having string like '8 58-2155-58' Desired output: '858215558' I want to remove any spaces between string and any dashes between strings. I could do it in access manually but want to do from python script Try this: input = '8 58-2155-58' output = ''.join( [ c for c in input if c not in ' -' ] ) output '858215558' Malcolm how about output = ''.join(input.replace('-',' ').split()) or output = input.replace('-','').replace(' ','') -- http://mail.python.org/mailman/listinfo/python-list
Re: persistent deque
i don't know how i would get around the problem, though, because i'd have to know how to access the deque object that my class stores when i do deque.__init__ in my constructor, so that i could pickle it and my class variables separately. i decided i could just pickle deque(self), which should return a regular deque object with the data from self, and then in the load routine make a pdeque object from it. that, of couse, gives me another error. 'collections.deque' object has no attribute 'write'. from the line 'self.write = file.write', which is in pickle.py pickling list(self) doesnt work either. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running programs under a python program...
maybe you could instead of killing the program stop the loop that starts new processes and start one that runs until the last process ends? also, if you killed the program but stdout was still set to fd and stderr was still set to subprocesses.STDOUT, what would happen when those two objects disappeared? wouldn't the processes crash or something? i dunno much about this though, maybe there's some way [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] So I have a python program that runs a bunch of other programsit then loops forever, occasionally executing other programs. To run each of these programs my python code executes: subprocess.Popen(command_line, shell=True, stdout=fd, stderr=subprocess.STDOUT) where command_line is an appropriate command line. :) Now my problem is when I abort this program it kills off all the child processes I've started. In this case I don't want that. How can I stop the child processes from dieing when I kill off the parent? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: about python modules
i always just put most of my python files in the c:\python25 directory. including ones i want to import as modules, since they import from there. otherwise you can put the file in c:\python25\lib\site-packages srinivas [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] hi friends i am new to python programming. i am using Python 2.5 and IDLE as editor. i have developed some functions in python those will be calling frequently in my main method . now i want to know how to import my functions folder to python in sucha way that the functions in functions folder should work like python library modules . i have python in folder C:\python25\.. and functions folder D:\programs\Functions\ pls help me friends how to do that. -- http://mail.python.org/mailman/listinfo/python-list
Re: C-like assignment expression?
one of the few things i miss from C is being able to use assignment in expressions. that's the only thing, really. also there's no switch/case, you have to use a dictionary of functions instead, although i rarely need that, usually i just use elif. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On May 21, 1:47 pm, Hrvoje Niksic [EMAIL PROTECTED] wrote: Although that solution is pretty, it is not the canonical solution because it doesn't cover the important case of if bodies needing to access common variables in the enclosing scope. (This will be easier in Python 3 with 'nonlocal', though.) The snippet posted by Diez is IMHO closer to a canonical solution to this FAQ. Hello everybody, thanks for the various answers. I'm actually pretty puzzled because I expected to see some obvious solution that I just hadn't found before. In general I find Python more elegant and syntactically richer than C (that's where I come from), so I didn't expect the solutions to be a lot more verbose and/or ugly (no offense) than the original idea which would have worked if Python's assignment statement would double as expression, as in C. Thanks again, robert PS: Since I'm testing only three REs, and I only need the match results from one of them, I just re-evaluate that one. -- http://mail.python.org/mailman/listinfo/python-list