Re: Why the file mode of .pyc files has x?
On 26Sep2009 10:24, Peng Yu wrote: | > [st...@sylar test]$ ls -l | > total 16 | > -rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py | > -rw-rw-r-- 1 steve steve 94 2009-09-26 23:08 test.pyc | > | > Have you checked the umask of your system? | | Here are my test case. If the .py file has the 'x' mode, the | corresponding .pyc file also has the 'x' mode after the .py file is | imported. Yes, I see this too. | pe...@selenium:~/test/python/pyc_mode$ umask | 0077 | pe...@selenium:~/test/python/pyc_mode$ ll | total 8 | -rw--- 1 pengy lilab 29 2009-09-26 10:10:45 main.py | -rwx-- 1 pengy lilab 106 2009-09-26 10:19:17 test.py [...] | pe...@selenium:~/test/python/pyc_mode$ python main.py | in_test_func | pe...@selenium:~/test/python/pyc_mode$ ll | total 12 | -rw--- 1 pengy lilab 29 2009-09-26 10:10:45 main.py | -rwx-- 1 pengy lilab 106 2009-09-26 10:19:17 test.py | -rwx-- 1 pengy lilab 339 2009-09-26 10:20:39 test.pyc This happens for me with python 2.6 x86_64 on gentoo. You're not alone. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Reaching consensus in a group often is confused with finding the right answer. - Norman Maier -- http://mail.python.org/mailman/listinfo/python-list
Help required
Hi, I dont know it is the right place to post this question. I need help to change one search code line . can you help me please. here is my search method code: search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext) if search: ret=search.group() else: ret='not defined' return ret here i am searching for "#acl InternationalGroup" in the pageText and when it true is then give me search group. I want to change this for following requirement: I want to search for "#acl InternationalGroup" and "CatInternational" for both in the pageText. when "#acl InternationalGroup" is not there but only "CatInternational" is there. then return me search group. I shall be thankful to you for any help. Best Regards, Waqas _ Drag n’ drop—Get easy photo sharing with Windows Live™ Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx-- http://mail.python.org/mailman/listinfo/python-list
removing a post
hello could you remove this old post, off topic and spam http://www.mail-archive.com/python-list@python.org/msg175722.html thank you _ We are your photos. Share us now with Windows Live Photos. http://go.microsoft.com/?linkid=9666047-- http://mail.python.org/mailman/listinfo/python-list
Re: Twisted PB: returning result as soon as ready
On 25 Sep, 01:25 pm, jacopo.pe...@gmail.com wrote: In the following chunk of code the CLIENT receives both the results from 1Ccompute 1D at the same time (i.e. when the second one has finished). This way it cannot start 1CelaborateResult 1D on the first result while the SERVER is still running the second 1Ccompute 1D. How could I get the first result as soon as ready and therefore parallelize things? thanks, Jacopo SERVER: fibo=Fibonacci() fact=pb.PBServerFactory(fibo) reactor.listenTCP(port, fact) reactor.run() CLIENT: fact=pb.PBClientFactory() reactor.connectTCP(host, port, fact) d=fact.getRootObject() n1=1 d.addCallback(lambda obj: obj.callRemote("compute", n1)) d.addCallback(elaborateResult) d2=fact.getRootObject() n2=1 d2.addCallback(lambda obj: obj.callRemote("compute", n2)) d2.addCallback(elaborateResult) reactor.run() "elaborateResult" will be called the first time as soon as the Deferred returned by the first "compute" call fires. This will happen as soon as the client receives the response from the server. If you're seeing the first call of "elaborateResult" not happen until after the server has responded to the second "compute" call's Deferred fires, then it's probably because the two Deferreds are firing at almost exactly the same time, which means the server is returning the results at almost exactly the same time. Considering your questions in another thread, my suspicion is that your Fibonacci calculator is blocking the reactor with its operation, and so even though it finishes doing the first calculation long before it finishes the second, it cannot actually *send* the result of the first calculation because the second calculation blocks it from doing so. Once the second calculation completes, nothing is blocking the reactor and both results are sent to the client. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting changes to a dict
Steven D'Aprano wrote: > Is there a fast way to see that a dict has been modified? I don't care > what the modifications are, I just want to know if it has been > changed, where "changed" means a key has been added, or deleted, or a > value has been set. (Modifications to mutable values aren't > important.) ZODB has PersistentDict which does this, but ZODB may or may not be appropriate to your particular application (and I have no idea how easily you can extract PersistentDict without also having a ZODB backend). See http://www.fprimex.com/guides/programming/python-using-zodb -- http://mail.python.org/mailman/listinfo/python-list
Re: Business issues regarding adapting Python
Nash wrote: I think normal market rules will apply to Pakistan too, if your desired trade has not the quantity you wish, the price per item should get higher. Net result should be that more quantity will be available due to increased interest. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' -- http://mail.python.org/mailman/listinfo/python-list
On screen keyboard application
Has anyone done already an on screen keyboard applicatioin like the native windows one. I am supossed to make one for a tuchscreen project for my dad's business. It's not a problem about the gui. I guess I will use wx but if I have to use something different it will be no problem. My problem is how not to lose the focus on any application that is active when I trigger an event on the keyboard gui. but also how to transfer the data. my first guess is that i will have to use pywin32, or something like that, or maybe I will have to move to ironpython. Has anyone some idea or sugesstion? -- http://mail.python.org/mailman/listinfo/python-list
Re: Bash shell to Python shell?
Chris Rebert wrote: > On Sun, Sep 27, 2009 at 8:13 PM, edwithad wrote: >> I am sure you have not read a question this basic in some time, but I am >> curious. Using Linux I open a terminal window and type: python. >> >> Does Bash Shell go away and to become a Python Shell, or is it still a Bash >> Shell with Python running inside? Thanks in advance. > > The latter. Press Ctrl+D or enter exit() or quit() to exit Python and > return to bash. > Or, if you prefer the bash shell to be replaced with the python, just type: exec python -- --- | Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk | --- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - (code is short & simple)
Chris Rebert a écrit : On Sun, Sep 27, 2009 at 8:53 PM, pylearner wrote: --- Traceback (most recent call last): File "", line 1, in toss_winner() File "C:/Python26/toss_winner.py", line 7, in toss_winner coin_toss = coin_toss() UnboundLocalError: local variable 'coin_toss' referenced before assignment --- # toss_winner.py from coin_toss import coin_toss def toss_winner(): coin_toss = coin_toss() When Python sees this assignment to coin_toss as it compiles the toss_winner() function, it marks coin_toss as a local variable and will not consult global scope when looking it up at runtime (snip) To fix the problem, rename the variable so its name differs from that of the coin_toss() function. (snip) As an additional note: in Python, everything is an object - including modules, classes, and, yes, functions -, so there's no distinct namespace for functions or classes. If you try to execute the "coin_toss = coin_toss()" statement at the top level (or declare name 'coin_toss' global prior using it in the toss_winner function), you wouldn't get an UnboundLocalError, but after the very first execution of the statement you would probably get a TypeError on subsquent attempts to call coin_toss: >>> def coin_toss(): ... print "coin_toss called" ... return 42 ... >>> coin_toss >>> coin_toss = coin_toss() coin_toss called >>> coin_toss 42 >>> coin_toss() Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable >>> HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: variable scope
Joel Juvenal Rivera Rivera a écrit : Yeah i forgot the self an try the code then i see an error that it was not defines _uno__a so that's where i define the global and see that behavior. (snip) Joel Juvenal Rivera Rivera wrote: Hi i was playing around with my code the i realize of this ### _uno__a = 1 class uno(): __a = 2 def __init__(self): print __a uno() ### and prints 1 Looks like a bug to me. I Think you should fill a ticket... -- http://mail.python.org/mailman/listinfo/python-list
Re: Most "active" coroutine library project?
On Saturday, 26 September 2009 16:55:30 Grant Edwards wrote: > On 2009-09-26, Dave Angel wrote: > > Actually even 64k looked pretty good, compared to the 1.5k of > > RAM and 2k of PROM for one of my projects, a navigation system > > for shipboard use. > > I've worked on projects as recently as the past year that had > only a couple hundred bytes of RAM, and most of it was reserved > for a message buffer. There is little reason to do that nowadays - one can buy a single cycle 8032 running at 30 MHz with 16/32/64k of programming flash and ik of RAM, as well as some bytes of eeprom for around US$10-00. - in one off quantities. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: variable scope
On Sep 28, 9:37 am, Bruno Desthuilliers wrote: > Joel Juvenal Rivera Rivera a écrit : > > > > > Yeah i forgot the self an try the code then i see > > an error that it was not defines _uno__a so that's > > where i define the global and see that behavior. > > (snip) > >> Joel Juvenal Rivera Rivera wrote: > >>> Hi i was playing around with my code the i realize of this > > >>> ### > >>> _uno__a = 1 > >>> class uno(): > >>> __a = 2 > >>> def __init__(self): > >>> print __a > >>> uno() > >>> ### > >>> and prints 1 > > Looks like a bug to me. I Think you should fill a ticket... I don't think it's a bug. Unless I'm missing something, it's the 'names in class scope are not accessible' gotcha, described and justified in the 'Discussion' section of PEP 227 http://www.python.org/dev/peps/pep-0227/ and somewhat more briefly in the reference manual: http://docs.python.org/reference/executionmodel.html#naming-and-binding The double underscores and name mangling are a red herring: you can get the same effect with: b = 1 class uno(object): b = 2 def __init__(self): print b uno() -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Business issues regarding adapting Python
Ha-ha-ha (sorry, can't resist). Here is at Moscow/Russia I have had a tought time finding a Python-related programming job. Positions both very rare (comparing with Java/C++ - maybe 1/100) and not pays well. And about 99% of them are web+Django. -- http://mail.python.org/mailman/listinfo/python-list
epydoc xml output?
Hi, I am using epydoc for my code documentation and I am curious whether there exist a possibility to produce the output in xml format. Reason for that is that I want to convert it to WordML and get it into our private documentation system. Unfortunately, the documentation does not mention xml, but says that epydoc is modular. In the epydoc.docwriter.html documentation, there an example $book.title$ $book.count_pages()$ ... is mentioned that looks like xml -- but I could get more information about that. So, what is the best was to get some structured xml from an reStructuredText/epydoc formatted API documentation? Best regards Ole -- http://mail.python.org/mailman/listinfo/python-list
Passing tuples of tuples to sqlite
Hi I have tuples in the format shown below: (u('2','3','4'),u('5','6','7')u('20','21','22')) but they are not being accepted into sqlite - due I think to the excessive quote marks which are confusing the issue when converting to a string to send it to sqlite. Can someone advise me on how I should format the strings so the whole tuple of tuples will be accepted in the sqlite insert query? Thanks Lol McBride -- http://mail.python.org/mailman/listinfo/python-list
Want to call a method only once for unittest.TestCase--but not sure how?
Hello fellow python hackers, I'm not an expert when it comes to Python and I'm totally stuck in a situation. All of our unit tests are written using built-in 'unittest' module. We've a requirement where we want to run a method only once for our unit tests. Some background: all of our tests are sub-classes of unittest.TestCase module just like following (copy pasting from idle) class Calculator(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add(self): print 'adder' print '---' def test_multiply(self): print 'multiplier' print '---' def test_divide(self): print '===' print 'Divide test' print '===' Our requirement is that for every unit test class we want to run a method only once. Method setUp() won't help because it will be called before every test method. I've tried using the following def __init__(self): unittest.TestCase.__init__(self) but it throws the following error E:\PyPy\Practice>python runner.py Traceback (most recent call last): suite = unittest.defaultTestLoader.loadTestsFromNames (['Tests.Calculator.Te stCase']) File "C:\Python25\lib\unittest.py", line 565, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Python25\lib\unittest.py", line 547, in loadTestsFromName return self.loadTestsFromTestCase(obj) File "C:\Python25\lib\unittest.py", line 507, in loadTestsFromTestCase return self.suiteClass(map(testCaseClass, testCaseNames)) TypeError: __init__() takes exactly 1 argument (2 given) So I'm completely stumped as to how to create a method that will only be called only once for Calculator class. Can you please suggest any ideas? Any help will be highly appreciated. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: very weird python bug..
On Thursday 24 September 2009 02:01:52 pm Christian Heimes wrote: > Sampsa Riikonen wrote: > > => If I start the program in directory "paska2", everythings OK, but if > > the directory name happens to be "python", the importation of the modules > > goes nuts! > > What's inside the python/ subdirectory? Do you happen to have a file > called struct.py inside it? yes I did! :-o Now its fixed. Thanks! Cheers, Sampsa -- http://mail.python.org/mailman/listinfo/python-list
Re: Business issues regarding adapting Python
Nash wrote: Hello everyone, I'm a big time python fan and it has helped me write code fast and push it out quickly. We have a medium sized telecom product written 90% in Python and 10% in Java. The problem is, in the place where we work (Pakistan), we can't find Python developers. I asked HR to send me figures on how many people do we have available who have worked with C++, Java, PHP and Python with 2-3 years of experience. They did a search on available candidates on Pakistan's biggest jobsite and this is what they sent: Language: Available Candidates in Pakistan (Available Candidates in our city) Java: 2020 (750) C++: 1540 (650) PHP: 630 (310) Python: 25 (4) Almost no-one shows up with Python experience when we put out a job opening and now it is becoming a real hurdle. Despite our liking and cost savings with the language, we are thinking about shifting to Java. 1. Have any of you faced a similar issue? How did you resolve it? 2. Do you think it makes sense to hire good programmers and train them on Python? 3. If we do train people in Python for say a month; are we just creating a team of mediocre programmers? Someone who has worked with Python for over an year is much different than someone who has worked with Python for only a month. 4. Any suggestions or idea? Related posts, articles etc would certainly help! I know that going Java will probably mean a 3x increase in the number of people that we have and require time for Python component replacement with Java ones. But for Business Continuity sake, management doesn't mind. Thanks a lot everyone! My 2 cents: We're about 5 people working with python on a quite complex application. No one of us had ever heard about python before starting on this project. And now, I'm so grateful to the guy who decided to use python, because everything is working perfectly well. Python is just an amazing easy-to-learn yet powerful language. I now use it whenever I can. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: python profiling for a XML parser program
MacRules wrote: > I have a python program doing XML data prasing and write the result to 2 > data files; which will be loaded to MySQL. > [...] > Is there a python profiler just like for C program? > And tell me which functions or modules take a long time. In case you want to do this because you noticed performance problems with the XML handling code, you might want to take a look at cElementTree (comes with Py2.5) and/or lxml (separate package). They are the fastest XML packages for Python, mostly compatible and very easy to use. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLObject 0.11.1
Hi, Oleg Broytmann wrote: > I'm pleased to announce version 0.11.1, a minor bugfix release of 0.11 branch > of SQLObject. Have you considered making announcements about (minor) releases on the dedicated Python announce list? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: lxml and xmlsec
Roland Hedberg wrote: > Anyone know if it is possible to use xmlsec together with lxml ? I remember reading on the lxml mailing list that someone uses both together. You might want to ask over there. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing tuples of tuples to sqlite
I have tuples in the format shown below: (u('2','3','4'),u('5','6','7')u('20','21','22')) Um, this is not valid Python which might explain the errors you're getting. Are you sure you don't mean to write: ((u'2', u'3', u'4'), (u'5', u'6', u'7')...) because "u" prefixing a tuple is invalid. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Want to call a method only once for unittest.TestCase--but not sure how?
On Sep 28, 12:45 pm, Oltmans wrote: > Hello fellow python hackers, > > I'm not an expert when it comes to Python and I'm totally stuck in a > situation. All of our unit tests are written using built-in 'unittest' > module. We've a requirement where we want to run a method only once > for our unit tests. Some background: all of our tests are sub-classes > of unittest.TestCase module just like following (copy pasting from > idle) > > class Calculator(unittest.TestCase): > > def setUp(self): pass > def tearDown(self): pass > > def test_add(self): > > print 'adder' > print '---' > > def test_multiply(self): > print 'multiplier' > print '---' > > def test_divide(self): > print '===' > print 'Divide test' > print '===' > > Our requirement is that for every unit test class we want to run a > method only once. Method setUp() won't help because it will be called > before every test method. I've tried using the following > > def __init__(self): > unittest.TestCase.__init__(self) > > but it throws the following error > > E:\PyPy\Practice>python runner.py > > Traceback (most recent call last): > suite = unittest.defaultTestLoader.loadTestsFromNames > (['Tests.Calculator.Te > stCase']) > File "C:\Python25\lib\unittest.py", line 565, in loadTestsFromNames > suites = [self.loadTestsFromName(name, module) for name in names] > File "C:\Python25\lib\unittest.py", line 547, in loadTestsFromName > return self.loadTestsFromTestCase(obj) > File "C:\Python25\lib\unittest.py", line 507, in > loadTestsFromTestCase > return self.suiteClass(map(testCaseClass, testCaseNames)) > TypeError: __init__() takes exactly 1 argument (2 given) > > So I'm completely stumped as to how to create a method that will only > be called only once for Calculator class. Can you please suggest any > ideas? Any help will be highly appreciated. Thanks in advance. The constructor of unittest.TestCase takes an optional test name as argument, and in the failing code it is called with such an argument, so when you are subclassing you have to keep the same interface: >>> class Calculator(unittest.TestCase): def __init__(self, name='runTest') : unittest.TestCase.__init__(self, name) # your staff here Note that __init__ gets called one time for test *instance*, not one time for test class. If you want the latest, you could define classmethods that you call explicitely at the beginning of your test code: class Calculator(unittets.TestCase): @classmethod def initialize(cls, ...): # your staff here def test(...): # or wherever your test code starts code Calculator.initialize() # other test class initializations # run your tests HTH Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - code is short & simple
On Sep 28, 6:07 am, pylearner wrote: > System Specs: > > Python version = 2.6.1 > IDLE > Computer = Win-XP, SP2 (current with all windows updates) > > ---- > > Greetings: > > I have written code for two things: 1) simulate a coin toss, and 2) > assign the toss result to a winner. Code for the simulated coin toss > is in a file named "coin_toss.py." Code for the assignment of the > toss result is in a file named "toss_winner.py." Each file has one > simple function: 1) coin_toss(), and 2) toss_winner(), respectively. > (The code for each file is listed below.) > > Problem: > > I am getting an error when I run "toss_winner.py." > > Error Message: > > Traceback (most recent call last): > File "", line 1, in > toss_winner() > File "C:/Python26/toss_winner.py", line 7, in toss_winner > coin_toss = coin_toss() > UnboundLocalError: local variable 'coin_toss' referenced before > assignment > > Question #1: > > After reviewing the code below, does anybody know why I am getting > this error? > > Explanation: > > As I understand, the first statement of the toss_winner() function > body -- i.e. "coin_toss = coin_toss()" -- causes four things to > happen: 1) the coin_toss() function is called, 2) the coin_toss() > function is executed, 3) the coin_toss() function returns the value of > its local "coin_toss" variable, and 4) the returned value of the "coin > toss" variable that is local to the coin_toss() function is assigned > to the "coin toss" variable that is local to the toss_winner() > function. > > Given this understanding, it seems I should NOT be getting a > "referenced before assignment" error, involving the "coin_toss" local > variable of "toss_winner()." > > Note: > > I am new to programming and Python. I'm currently self-studying > "Python Programming: An Intro to Computer Science" by Zelle. > > Thanks! > > --- > > # toss_winner.py > > from coin_toss import coin_toss > > def toss_winner(): > > coin_toss = coin_toss() > > if coin_toss == "Heads": > toss_winner = "Player A" > print 'From "toss_winner" function >>', > print "Toss Winner = " + str(toss_winner) > > else: > toss_winner = "Player B" > print 'From "toss_winner" function >>', > print "Toss Winner = " + str(toss_winner) > > return toss_winner > > --- > > # coin_toss.py > > from random import random > > def coin_toss(): > > random_number = random() > > if random_number < .5: > > coin_toss = "Heads" > > print 'From "coin_toss" function >>', > print "Toss result = " + str(coin_toss) > > else: > > coin_toss = "Tails" > > print 'From "coin_toss" function >>', > print "Toss result = " + str(coin_toss) > > return coin_toss You should not use the same name (e.g. coin_toss ) for the function and the variable. Change one of the two, and things will go better. Ciao -- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing tuples of tuples to sqlite
On 28 Sep, 11:35, xera121 wrote: > Hi > I have tuples in the format shown below: > > (u('2','3','4'),u('5','6','7')u('20','21','22')) > > but they are not being accepted into sqlite - due I think to the > excessive quote marks which are confusing the issue when converting to > a string to send it to sqlite. > Can someone advise me on how I should format the strings so the whole > tuple of tuples will be accepted in the sqlite insert query? > > Thanks > > Lol McBride After receiving an email I realised that the way I have presented the tuple unicode formatting is incorrect. I will post proper code when I get access to my machine later to day. Lol Mc -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the file mode of .pyc files has x?
On Mon, 28 Sep 2009 17:01:40 +1000, Cameron Simpson wrote: > On 26Sep2009 10:24, Peng Yu wrote: | > > [st...@sylar test]$ ls -l > | > total 16 > | > -rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py | > -rw-rw-r-- > 1 steve steve 94 2009-09-26 23:08 test.pyc | > > | > Have you checked the umask of your system? | > | Here are my test case. If the .py file has the 'x' mode, the | > corresponding .pyc file also has the 'x' mode after the .py file is | > imported. > > Yes, I see this too. Is this a problem? Taking a wild guess, I'd imagine that the .pyc file gets its permissions copied from the .py file. I don't see that as a major issue. A buglet, rather than a bug, at worst. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: llvm vs. parrot
On Sun, 2009-04-12 at 06:18 -0700, Fuzzyman wrote: > On Apr 11, 12:16 am, Paul Watson wrote: > > Is Parrot out of favor these days? It appears that Google is going to > > use llvm. > > > > http://code.google.com/p/unladen-swallow/ > > Has Parrot ever been in favour? > > Actually they're quite different things. > > Michael > -- > http://www.ironpythoninaction.com/ Are you saying they are "quite different" because llvm gets compiled into native code and Parrot bytecode is still interpreted? At the intermediate form, they seem quite similar. Why do you say not? -- http://mail.python.org/mailman/listinfo/python-list
Re: nested structure with "internal references"
Hendrik van Rooyen writes: > On Friday, 25 September 2009 19:11:06 Torsten Mohr wrote: > >> I'd like to use a nested structure in memory that consists >> of dict()s and list()s, list entries can be dict()s, other list()s, >> dict entries can be list()s or other dict()s. >> >> The lists and dicts can also contain int, float, string, ... > > This sounds terribly convoluted. > What are you trying to do? > >> >> But i'd also like to have something like a "reference" to another >> entry. > > Everything and its brother in Python is an object, and things like lists and > dicts reference objects automagically. > >> I'd like to refer to another entry and not copy that entry, i need to >> know later that this is a reference to another entry, i need to find >> also access that entry then. > > Depending on how I read this, it is either trivial or impossible: > > A name is bound to an object by assignment. > An object can have many names bound to it. > A name can, at different times, refer to different objects. > An object does not know which names are bound to it, or in what sequence it > was done. > > So you can go from name to object, but not the other way around. > You can use the same name in a loop to refer to different objects, and in > each > iteration, use the name to store a reference to the current object in a list > or dict. > >> Is something like this possible in Python? > > Not too sure what you are trying to do. > >> The references only need to refer to entries in this structure. >> The lists may change at runtime (entries removed / added), so >> storing the index may not help. > > You could start off with a list of lists of lists, to any level of nesting > that you want. This will give you a structure like a tree with branches and > twigs and leaves, but I am not sure if this is what you want or need, or if a > flat structure like third normal form would suffice, or if you need a > relational database. > > - Hendrik I'm not really sure what he wants either, but it sounds suspiciously like a linked list. In regards to the OP, though not a true linked-list, Python objects can be built with classes that describe essentially the same functionality. Just be careful about keeping references to large in-memory objects (see weakref) and try to avoid circular references in your mappings. Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: [Image-SIG] Some issue with easy_install and PIL/Imaging
On Fri, Sep 11, 2009 at 3:49 PM, Chris Withers wrote: > Klein Stéphane wrote: >> >> Resume : >> 1. first question : why PIL package in "pypi" don't work ? > > Because Fred Lundh have his package distributions unfortunate names that > setuptools doesn't like... It used to support this, but no longer does. To me, that says more about the state of setuptools than it does about the state of PIL, which has been using the same naming convention for 15 years. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: Twisted PB: returning result as soon as ready
On 06:06 am, jacopo.pe...@gmail.com wrote: Jean-Paul, thanks a lot for your patient. I have read most of a the 1CThe Twisted Documentation 1D which I think is very good for Deferred and ok for PB but it is really lacking on the Reactor. In my case it looks like this is key to achieve what I have in mind. I've also just received 1CTwisted network programming essential 1D but I don't expect too much from this book. Would you be able to suggest me a reference to understand the Reactors? I need to be aware of when this is blocked and how to avoid it. I have a very simple objective in mind. I want to distribute some processing to different severs and collect and process results from a client as soon as they are ready. To achieve true parallelism it looks more complex than expected. It would probably be best to move to the twisted-python mailing list. There are a lot more people there who can help out. Jean-Pal -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting changes to a dict
Steven D'Aprano wrote: I'm pretty sure the answer to this is No, but I thought I'd ask just in case... Is there a fast way to see that a dict has been modified? ... Of course I can subclass dict to do this, but if there's an existing way, that would be better. def mutating(method): def replacement(self, *args, **kwargs): try: return method(self, *args, **kwargs) finally: self.serial += 1 replacement.__name__ = method.__name__ return replacement class SerializedDictionary(dict): def __init__(self, *arg, **kwargs): self.serial = 0 super(SerializedDictionary).__init__(self, *arg, **kwargs) __setitem__ = mutating(dict.__setitem__) __delitem__ = mutating(dict.__delitem__) clear = mutating(dict.clear) pop = mutating(dict.pop) popitem = mutating(dict.popitem) setdefault = mutating(dict.setdefault) update = mutating(dict.update) d = SerializedDictionary(whatever) Then just use dict.serial to see if there has been a change. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Want to call a method only once for unittest.TestCase--but not sure how?
Oltmans wrote: ... All of our unit tests are written using built-in 'unittest' module. We've a requirement where we want to run a method only once for our unit tests > So I'm completely stumped as to how to create a method that will only > be called only once for Calculator class. Can you please suggest any > ideas? Any help will be highly appreciated. Thanks in advance. Just inherit your classes from something like (untested): class FunkyTestCase(unittest.TestCase): needs_initial = True def initialize(self): self.__class__.needs_initial = False def setUp(self): if self.needs_initial: self.initialize() And write your test classes like: class Bump(FunkyTestCase): def initialize(self): super(Bump, self).initialize() print 'One time Action' ... --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
GetPaid module that supports "deferred" payments?
Are any of the GetPaid modules able to handle "deferred" payments? As in, the money to be taken is placed "on hold" in the customer's account and can be "released" to the vendor at a later date. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing tuples of tuples to sqlite
On 28 Sep, 13:52, lolmc wrote: > On 28 Sep, 11:35, xera121 wrote: > > > Hi > > I have tuples in the format shown below: > > > (u('2','3','4'),u('5','6','7')u('20','21','22')) > > > but they are not being accepted into sqlite - due I think to the > > excessive quote marks which are confusing the issue when converting to > > a string to send it to sqlite. > > Can someone advise me on how I should format the strings so the whole > > tuple of tuples will be accepted in the sqlite insert query? > > > Thanks > > > Lol McBride > > After receiving an email I realised that the way I have presented the > tuple unicode formatting is incorrect. I will post proper code when I > get access to my machine later to day. > > Lol Mc Did some SSh and vnc majic and I've got the proper formatting: [(u'(7, 28, 36)', u'(35, 47, 49)', u'(25, 34, 46)', u'(2, 5, 40)', u'(7, 24, 35)', u'(8, 17, 20)', u'(24, 33, 37)', u'(5, 8, 19)')] So what i want to do is put the above into a primary key field so that I know when duplicates have occurred and I only add unique data into the field.When I have copied the string of the query into sqlitemanger and tried to execute it ther it says ther is an error in the SQL query at ',' - which is not too helpful as I am not sure if it is the first , or 3rd or last , which is causing the problem! I have a feeling though that it is the quote mark after the unicode delimiter which is the issue but I'm not 100% sure - can anyone shed light on this and offer a solution? Thanks Lol Mc -- http://mail.python.org/mailman/listinfo/python-list
create a class instance from C API?
Hello How to programmatically create a class instance of a given Python class? For example to create a new list there is the PyObject *PyList_New() but suppose the user already defined a class: class X: pass How to create an instance of it from my C extension module? Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - (code is short & simple)
On Sun, Sep 27, 2009 at 10:39 PM, New User wrote: > Hi Chris, > > Thank you for the reply and info! > > Re: "from coin_toss import coin_toss" > > My understanding is that this line makes the coin_toss() function in the > coin_toss.py file available to the toss_winner() function. Is that what > your explanation on this point meant (i.e. "... and sets the > local variable coin_toss to the value of coin_toss in the module coin_toss > ")? > That is the effect of the statement, however there are cases when the from coin_toss import coin_toss may result in a different value in the module. This is because: from coin_toss import coin_toss effectively does: import coin_toss coin_toss = coin_toss.coin_toss While this normally works as intended, it can have some unexpected effects. Take, for example: -ALPHA.PY- from gamma import test import beta import gamma test = 2 gamma.test = 3 print gamma.test print test print beta.test print beta.gamma.test -BETA.PY from gamma import test import gamma GAMMA.PY--- test = 1 With this setup, you'll get the output: >>> import Test.alpha 3 2 1 3 If, however, you change gamma to read: test = ['1'] and the lines in alpha: test = 2 gamma.test = 3 to read: test.append('2') gamma.test.append('3') you'll get: >>> import Test.alpha ['1', '2', '3'] ['1', '2', '3'] ['1', '2', '3'] ['1', '2', '3'] As this shows, the "from MODULE import VALUE" method rebinds the varible from another module in the local scope, and thus does: import MODULE VALUE = MODULE.VALUE del MODULE This means that for some types, the value in MODULE and the value in the local scope may not be the same and other times they may be the same. For your purposes, you'll notice no real difference. However this is something to keep in mind. > > Re: "... within a function, a different namespace exists ", and "... you > may want to look into the global keyword ." > > Ok, I will read up on these. Thank you for the tips! > > Martin > > P..S. I didn't see your reply to my post in the comp.lang.python Google > Groups. I assume you emailed your reply directly to me. I also assume > you're not looking for my response in comp.lang.python Google Groups. This > is my first time posting, so I'm not sure what the "posting-reply" > conventions are. > It should have shown up on the python list - I just forgot to remove you from it (I used G-Mail's reply all). In general, unless the reply is off-topic or personal, it should be replied to on-list. This allows more people to both see the answer and to help further explain the answer. > > --- On *Mon, 9/28/09, Chris Kaynor * wrote: > > > From: Chris Kaynor > Subject: Re: UnboundLocalError - (code is short & simple) > To: "pylearner" > Cc: python-list@python.org > Date: Monday, September 28, 2009, 4:17 AM > > > Lets look at what is happening on a few of the lines here: > > First: > from coin_toss import coin_toss > > imports the module coin_toss and sets the local variable coin_toss to the > value of coin_toss in the module coin_toss. > > > Second: > coin_toss = coin_toss() > > calls the function bound to the name coin_toss and assigns the result to > coin_toss. Now this appears to be what you want (and run outside a function > it would work as you intend, the first time). However, within a function, a > different namespace exists, and Python sees that you are assigning to > coin_toss, and thus uses the local version of that variable everywhere else > within the function. As such, Python is attempting to call the > local variable coin_toss, which has not yet been assigned too. > > > > While not really the "correct" solution, you may want to look into the > global keyword for more information about your problem. > > > > Chris > > > On Sun, Sep 27, 2009 at 8:53 PM, pylearner > http://mc/compose?to=for_pyt...@yahoo.com> > > wrote: > >> Python version = 2.6.1 >> IDLE >> Computer = Win-XP, SP2 (current with all windows updates) >> >> --- >> >> Greetings: >> >> I have written code for two things: 1) simulate a coin toss, and 2) >> assign the toss result to a winner. Code for the simulated coin toss >> is in a file named "coin_toss.py." Code for the assignment of the >> toss result is in a file named "toss_winner.py." Each file has one >> simple function: 1) coin_toss(), and 2) toss_winner(), respectively. >> The code for each file is listed below. >> >> Problem: >> >> I am getting an error when I run "toss_winner.py." The error message >> is listed below. >> >> Question #1: >> >> Why am I getting this error? >> >> Explanation: >> >> As I understand it, the first statement of the toss_winner() function >> body -- i.e. "coin_toss = coin_toss()" -- causes four things to >> happen: 1) the coin_toss() function is called, 2) the coin_toss() >> function is executed, 3) the coin_toss() function returns the value of >> its local "coin_toss" variable, and 4) the returned
Re: [off-topic] Pessimal (was: Detecting changes to a dict)
On Mon, Sep 28, 2009 at 9:53 AM, John Posner wrote: > > If you can enumerate the language of possible inputs you could >> generate a unique binary representation. Against a language of size >> l that would only take you O(l*n) to build the repr for a dict >> and for certain repr sizes the comparison could be O(1), making >> the entire operation O(l*n+l*m) vs O(n*m). >> >> >> > Geremy, I can't comment on the *content* of your observation on > performance, but ... > > This sentence reminds me of the mid-1980s, when I was learning C in order > to program the very first font cartridge for the HP LaserJet printer. The > escape sequences seemed to consist entirely of ones and small ells and zeros > and capital ohs -- apparently designed for maximal confusion. Was it around > that time that the word "pessimal" was coined? > > -John 1) I honestly wouldn't know, seeing as how I wasn't alive ;). 2) After a brief tube hunt, I found that the word "pessimal" is originally from biology and appears to be somewhat more ancient than HP printers, although judging by the amount of dust I've seen on their insides I wouldn't place any large sums of money on that. 3) Apologies if the nomenclature was confusing, I tend to use l rather than the more standard |L| to denote the size of a language L. To rephrase, using S instead of l: Given an efficiently enumerable language L of size S, a unique binary representation of any sentence in L of size N can be generated in at most O(L*N) time. Because binary strings of reasonable bitlengths can be compared in a single machine operation, for most practical purposes we can simply say that equality testing will be O(1). As a result, the total time of generation and comparison for *two* sentences of size N (remember that we're not concerned about two sentences of unequal length) will be O(L*2N), and is likely to be quite fast in practice. Further optimizations- especially revolving around Bloom filters if a small margin of error is acceptable and S is large- are probably possible. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: create a class instance from C API?
On Sep 28, 8:19 am, "lallous" wrote: > Hello > > How to programmatically create a class instance of a given Python class? > > For example to create a new list there is the PyObject *PyList_New() but > suppose the user already defined a class: > > class X: pass > > How to create an instance of it from my C extension module? Same way you'd do it in Python: call it. Use PyObject_Call or any of it's convenient variants. Example (leaving off all the error-checking stuff): mod = PyImport_ImportModule(modname); cls = PyObject_GetAttrStr(mod,classname); inst = PyObject_CallFunctionObjArgs(cls,NULL); Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: [off-topic] Pessimal (was: Detecting changes to a dict)
Aaagh! Did it without thinking. Should be O(S*N) and O(S*2N). On Sep 28, 2009 12:09 PM, "geremy condra" wrote: On Mon, Sep 28, 2009 at 9:53 AM, John Posner wrote: > > >> If you can enumera... 1) I honestly wouldn't know, seeing as how I wasn't alive ;). 2) After a brief tube hunt, I found that the word "pessimal" is originally from biology and appears to be somewhat more ancient than HP printers, although judging by the amount of dust I've seen on their insides I wouldn't place any large sums of money on that. 3) Apologies if the nomenclature was confusing, I tend to use l rather than the more standard |L| to denote the size of a language L. To rephrase, using S instead of l: Given an efficiently enumerable language L of size S, a unique binary representation of any sentence in L of size N can be generated in at most O(L*N) time. Because binary strings of reasonable bitlengths can be compared in a single machine operation, for most practical purposes we can simply say that equality testing will be O(1). As a result, the total time of generation and comparison for *two* sentences of size N (remember that we're not concerned about two sentences of unequal length) will be O(L*2N), and is likely to be quite fast in practice. Further optimizations- especially revolving around Bloom filters if a small margin of error is acceptable and S is large- are probably possible. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
multiprocessing, SyncManager, dict() of Locks possible?
I'm trying to work out a multiple readers, one writer scenerio with a bunch of objects. Basically "foo" objects are shared across processes. Each foo object has a .lock variable, which holds a Mutex. In creation, I'd like to call the SyncManager, get the dict() object which hold object_ids->lock mappings (so we can create a lock per object only once)... Creating the lock map happens like this: if not object_locks.has_key(object_id): new_lock = manager.Lock() manager.object_locks.update({ object_id: new_lock}) Everything seems fine, except, on retrieval of the SyncManager.get_object_locks().get(object_id) I get a Unserializable message: ('#RETURN', ) I had thought the multiprocessing Lock was serializable and shared. Any other alternatives versus a global lock around all object writes? -- http://mail.python.org/mailman/listinfo/python-list
Using String for new List name
I am new to Python but I have studied hard and written a fairly big (to me) script/program. I have solved all of my problems by Googling but this one has got me stumped. I want to check a string for a substring and if it exists I want to create a new, empty list using that substring as the name of the list. For example: Let's say file1 has line1 through line100 as the first word in each line. for X in open("file1"): Do a test. If true: Y = re.split(" ", X) Z = Y[0] # This is a string, maybe it is "Line42" Z = [] # This doesn't work, I want a new, empty list created called Line42 not Z. Is there any way to do this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
2009/9/28 Scott : > I am new to Python but I have studied hard and written a fairly big > (to me) script/program. I have solved all of my problems by Googling > but this one has got me stumped. > > I want to check a string for a substring and if it exists I want to > create a new, empty list using that substring as the name of the list. > For example: What do you mean by "as the name of the list"? You cannot alter the name "Z" in the source code to be the content of the file, unless you do some serious magic ;) > > Let's say file1 has line1 through line100 as the first word in each > line. > > for X in open("file1"): > Do a test. > If true: > Y = re.split(" ", X) > Z = Y[0] # This is a string, maybe it is "Line42" > Z = [] # This doesn't work, I want a new, empty > list created called Line42 not Z. > > Is there any way to do this? > -- > http://mail.python.org/mailman/listinfo/python-list > -- twitter.com/olofb olofb.wordpress.com olofb.wordpress.com/tag/english -- http://mail.python.org/mailman/listinfo/python-list
Pool module -- does map pre-assign tasks to processes?
I would like to use the Pool module, but my tasks take sometimes unpredictably different time to complete. The simplest way to write the code would be to put all task descriptions in an array, then call p = Pool(8) p.map(f, a) But I don't want to preassign process 0 with elements a[0], a[8], a [16], process 1 with elements a[1], a[9], a[17], and so forth. Rather, I would like all tasks to be put into a queue, and I would like the processes to each time grab the next task to be done, and do it. This would ensure fairly equal loading. My question is: does the map() method of Pool pre-assign which task gets done by each process, or is this done at runtime, on a get-first- task-to-be-done basis? Many thanks, Luca -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Scott wrote: > for X in open("file1"): > Do a test. > If true: > Y = re.split(" ", X) > Z = Y[0] # This is a string, maybe it is "Line42" > Z = [] # This doesn't work, I want a new, empty > list created called Line42 not Z. > > Is there any way to do this? > Use a dictionary. Also use meaningful variable names, don't use regular expressions unless you actually get some benefit from using them, and always close the file when you've finished with it. values = {} with open("file1") as f: for line in f: fields = line.split(None, 1) values[fields[0]] = [] -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Scott wrote: I am new to Python but I have studied hard and written a fairly big (to me) script/program. I have solved all of my problems by Googling but this one has got me stumped. I want to check a string for a substring and if it exists I want to create a new, empty list using that substring as the name of the list. For example: Let's say file1 has line1 through line100 as the first word in each line. for X in open("file1"): Do a test. If true: Y = re.split(" ", X) Z = Y[0] # This is a string, maybe it is "Line42" Z = [] # This doesn't work, I want a new, empty list created called Line42 not Z. Is there any way to do this? Assuming you made this work, and had a new variable called "Line42", how would you know it was called "Line42" in the rest of your program? What you could do is create a dict and have the key set to the new name, e.g.: new_names = {} for X in open("file1"); Do a test. if True: Y = X.split(" ") new_names[Y[0]] = [] then in the rest of your program you can refer to the keys in new_names: for var in new_names: item = new_names[var] do_something_with(item) Hope this helps! ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Thank you fine folks for getting back with your answers! So down the road I do dictname[line42].append("new stuff"). (or [var] if I'm looping through the dict) This is cool and should do the trick! -Scott Freemire disclosure - Ok, I'm new to *any* language. I've been teaching myself for about 3 months with "Learning Python, 3rd Edition" and I think it's going well! Of course I picked something way too complicated for a first try. Thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
2009/9/28 Scott : > Thank you fine folks for getting back with your answers! > > So down the road I do dictname[line42].append("new stuff"). (or [var] > if I'm looping through the dict) > > This is cool and should do the trick! > > -Scott Freemire > disclosure - Ok, I'm new to *any* language. I've been teaching myself > for about 3 months with "Learning Python, 3rd Edition" and I think > it's going well! Of course I picked something way too complicated for > a first try. Thanks again! Good luck! > -- > http://mail.python.org/mailman/listinfo/python-list > -- twitter.com/olofb olofb.wordpress.com olofb.wordpress.com/tag/english -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run python script in emacs
On Sun, 27 Sep 2009 19:44:07 -0700, devilkin wrote: > and does the python-mode support auto-complete? No. -- http://mail.python.org/mailman/listinfo/python-list
Re: IMGCrush (New Python image optimizing tool)
On Sep 5, 4:30 pm, a...@pythoncraft.com (Aahz) wrote: > In article > , > > kiithsa...@gmail.com wrote: > > >Requires ImageMagick and Python (coded in python 2.x, I'm running 2.6 > >but it might run on older python as well) > > Why are you using ImageMagick instead of PIL? > -- > Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ > > "Look, it's your affair if you want to play with five people, but don't > go calling it doubles." --John Cleese anticipates Usenet Mainly because it started as an ImageMagick based bash script :p. But ImageMagicks ability to load just about any format helps. Also, from what I see in PIL docs, it doesn't seem to allow to set as many format specific saving options (especially various rarely used PNG options), which is extremely important for IMGCrush. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Scott wrote: Thank you fine folks for getting back with your answers! So down the road I do dictname[line42].append("new stuff"). (or [var] if I'm looping through the dict) This is cool and should do the trick! -Scott Freemire disclosure - Ok, I'm new to *any* language. I've been teaching myself for about 3 months with "Learning Python, 3rd Edition" and I think it's going well! Of course I picked something way too complicated for a first try. Thanks again! That should actually be dictname["line42"].append("new stuff"). Notice the quotes around line42. Good luck! Python is a fine language, I hope you like it. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
SQLObject
I'm new to using SQLObject, and having some problems with getting it to recognise my current MySQL database. I've set up my connection fine, but it won't recognise the names of the columns (presumably because they're not written using the default naming convention?). For example, one of my columns is an acronym, so is 3 uppercase letters. I've tried the following: class Table1(sqlobject.SQLObject): _connection = conn _fromDatabase = True class sqlmeta: table = 'Table1' idName = 'Table1ID' BOB = StringCol() print Table1.get(1) this gives the result Unknown column 'bo_b' in 'field list' So, specifically a few questions: I've seen the attribute in class sqlmeta of 'columns' - will this find my column names automatically, or do I still need to input them manually? If the latter..: I assume I set the names of each column in the instance of sqlmeta (like I have done with the table name) - how do I do this?! Do I do this before or after I've told SQLObject that the BOB column is a String column? Is there a published list of the default naming convention that SQLObject follows? I couldn't find it on the website. Thanks in advance for any help anyone is able to give. Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Scott wrote: Thank you fine folks for getting back with your answers! So down the road I do dictname[line42].append("new stuff"). The keys are strings, so dictname['line42'].append("new stuff") or for key in dictname.keys(): ... dictname[key] tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
> That should actually be dictname["line42"].append("new stuff"). Notice > the quotes around line42. > > Good luck! Python is a fine language, I hope you like it. > > ~Ethan~ Doh. I sent it before my type, fail, fix cycle had taken place. Got it. Thanks again all! -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
Scott wrote: Thank you fine folks for getting back with your answers! So down the road I do dictname[line42].append("new stuff"). (or [var] if I'm looping through the dict) Nope, you still haven't gotten it. Of course, I really don't know where you're going wrong, since you didn't use the same symbols as any of the responses you had gotten. I suspect that you meant dictname[] to be the dictionary that Duncan called values[]. On that assumption, in order to append, you'd want something like: values["line42"].append("new stuff") or values[var].append("new stuff") if you happen to have a variable called var with a value of "line42". You will need to get a firm grasp on the distinctions between symbol names, literals, and values. And although Python lets you blur these in some pretty bizarre ways, you haven't a chance of understanding those unless you learn how to play by the rules first. I'd suggest your first goal should be to come up with better naming conventions. And when asking questions here, try for more meaningful data than "Line42" to make your point. Suppose a text file called "customers.txt" has on each line a name and some data. We want to initialize an (empty) list for each of those customers, and refer to it by the customer's name. At first glance we might seem to want to initialize a variable for each customer, but our program doesn't know any of the names ahead of time, so it's much better to have some form of collection. We choose a dictionary. transactions = {} with open("customers.txt") as infile: for line in infile: fields = line.split() customername = fields[0]#customer is first thing on the line transactions[customername] = [] #this is where we'll put the transactions at some later point, for this customer Now, if our program happens to have a special case for a single customer, we might have in our program something like: transactions["mayor"].append("boots") But more likely, we'll be in a loop, working through another file: . for line in otherfile: fields = line.split() customername = fields[0] transaction = fields[1] transactions[customername].append(transaction)#append one transaction or interacting: name = raw_input("Customer name") trans = raw_input("transaction for that customer") transactions[name].append(trans) -- http://mail.python.org/mailman/listinfo/python-list
Re: Some issue with easy_install and PIL/Imaging
Fredrik Lundh a écrit : On Fri, Sep 11, 2009 at 3:49 PM, Chris Withers wrote: Klein Stéphane wrote: Resume : 1. first question : why PIL package in "pypi" don't work ? Because Fred Lundh have his package distributions unfortunate names that setuptools doesn't like... It used to support this, but no longer does. To me, that says more about the state of setuptools than it does about the state of PIL, which has been using the same naming convention for 15 years. Ok, and what can we do ? Is a setuptools issue ? Can distribute (http://bitbucket.org/tarek/distribute/wiki/Home setuptools fork) fix this issue easily ? Regards, Stephane -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - (code is short & simple)
Thank you for the elaboration, Chris! I don't have the background to follow your example code. However, between your summary of the code, and the code examples themselves, I have enough info to get a glimpse of what you're explaining. Also, I can use the info as a foundation for further study on the matter. Thanks too for the feedback about the "list." I'm using a combination of yahoo email (to and from the mailing list) and Google Groups, until I figure out which works best. Using a Usenet newsreader client is not an option for me at this point. Martin --- On Mon, 9/28/09, Chris Kaynor wrote: From: Chris Kaynor Subject: Re: UnboundLocalError - (code is short & simple) To: python-list@python.org Date: Monday, September 28, 2009, 4:00 PM On Sun, Sep 27, 2009 at 10:39 PM, New User wrote: Hi Chris, Thank you for the reply and info! Re: "from coin_toss import coin_toss" My understanding is that this line makes the coin_toss() function in the coin_toss.py file available to the toss_winner() function. Is that what your explanation on this point meant (i.e. "... and sets the local variable coin_toss to the value of coin_toss in the module coin_toss")? That is the effect of the statement, however there are cases when the from coin_toss import coin_toss may result in a different value in the module. This is because: from coin_toss import coin_tosseffectively does:import coin_tosscoin_toss = coin_toss.coin_toss While this normally works as intended, it can have some unexpected effects. Take, for example: -ALPHA.PY-from gamma import testimport betaimport gamma test = 2gamma.test = 3print gamma.testprint test print beta.testprint beta.gamma.test -BETA.PYfrom gamma import testimport gamma GAMMA.PY--- test = 1 With this setup, you'll get the output:>>> import Test.alpha321 3 If, however, you change gamma to read:test = ['1'] and the lines in alpha: test = 2gamma.test = 3 to read: test.append('2')gamma.test.append('3') you'll get: >>> import Test.alpha['1', '2', '3']['1', '2', '3']['1', '2', '3']['1', '2', >>> '3'] As this shows, the "from MODULE import VALUE" method rebinds the varible from another module in the local scope, and thus does:import MODULE VALUE = MODULE.VALUEdel MODULE This means that for some types, the value in MODULE and the value in the local scope may not be the same and other times they may be the same. For your purposes, you'll notice no real difference. However this is something to keep in mind. Re: "... within a function, a different namespace exists ", and "... you may want to look into the global keyword ." Ok, I will read up on these. Thank you for the tips! Martin P..S. I didn't see your reply to my post in the comp.lang.python Google Groups. I assume you emailed your reply directly to me. I also assume you're not looking for my response in comp.lang.python Google Groups. This is my first time posting, so I'm not sure what the "posting-reply" conventions are. It should have shown up on the python list - I just forgot to remove you from it (I used G-Mail's reply all). In general, unless the reply is off-topic or personal, it should be replied to on-list. This allows more people to both see the answer and to help further explain the answer. --- On Mon, 9/28/09, Chris Kaynor wrote: From: Chris Kaynor Subject: Re: UnboundLocalError - (code is short & simple) To: "pylearner" Cc: python-list@python.org Date: Monday, September 28, 2009, 4:17 AM Lets look at what is happening on a few of the lines here: First:from coin_toss import coin_toss imports the module coin_toss and sets the local variable coin_toss to the value of coin_toss in the module coin_toss. Second: coin_toss = coin_toss() calls the function bound to the name coin_toss and assigns the result to coin_toss. Now this appears to be what you want (and run outside a function it would work as you intend, the first time). However, within a function, a different namespace exists, and Python sees that you are assigning to coin_toss, and thus uses the local version of that variable everywhere else within the function. As such, Python is attempting to call the local variable coin_toss, which has not yet been assigned too. While not really the "correct" solution, you may want to look into the global keyword for more information about your problem. Chris On Sun, Sep 27, 2009 at 8:53 PM, pylearner wrote: Python version = 2.6.1 IDLE Computer = Win-XP, SP2 (current with all windows updates) --- Greetings: I have written code for two things: 1) simulate a coin toss, and 2) assign the toss result to a winner. Code for the simulated coin toss is in a file named "coin_toss.py." Code for the assignment of the toss result is in a file named "toss_winner.py." Each file has one simple function: 1) coin_toss(), and 2) toss_wi
Re: Most "active" coroutine library project?
On Sep 25, 2:07 pm, Grant Edwards wrote: > On 2009-09-25, Jason Tackaberry wrote: > > > And I maintain that requiring yield doesn't make it any less a > > coroutine. > > > Maybe we can call this an aesthetic difference of opinion? > > Certainly. > > You've a very valid point that "transparent" can also mean > "invisible", and stuff happening "invisibly" can be a source of > bugs. All the invisible stuff going on in Perl and C++ has > always caused headaches for me. There are some key advantages to this transparency, especially in the case of libraries built on libraries. For example, all the networking libraries that ship in the Python standard lib are based on the sockets library. They assume the blocking implementation, but then add HTTPS, cookie handling, SMTP, and all sorts of higher-level network protocols. I want to use non-blocking network I/O for (concurrency) performance. I don't want to re-write an SMTP lib - my language ships with one. However, it is not possible for someone to write a non-blocking socket that is a drop-in replacement for the blocking one in the std lib. Thus, it is not possible for me to use _any_ of the well-written libraries that are already part of Python's standard library. They don't have yields sprinkled throughout, so they can't work with a non- blocking, co-routine implemented socket. And they certainly aren't written against the non-blocking I/O APIs. Thus, the efforts by lots of people to write entire network libraries that, basically, re-implement the Python standard library, but change the implementation of 7 methods (bind, listen, accept, connect, send, recv, close). They end up having to duplicate tens of thousands of LoC, just to change 7 methods. That's where transparency would be nice - to enable that separation of concerns. -- http://mail.python.org/mailman/listinfo/python-list
Re: Repeated output when logging exceptions
In <6bce12c3-f2d9-450c-89ee-afa4f21d5...@h30g2000vbr.googlegroups.com> Vinay Sajip writes: > The logging package allows you to add tracebacks to your logs by using > the exception() method, which logs an ERROR with a traceback and is > specifically intended for use from within exception handlers. All that > stuff with temporary files seems completely unnecessary, even with Python > 2.3. I didn't know about the exception() method. Thanks! > In general, avoid adding handlers more than once - which you are > almost guaranteed to not avoid if you do this kind of processing in a > constructor. If you write your applications without using the > exceptionLogger class (not really needed, since logging exceptions > with tracebacks is part and parcel of the logging package's > functionality since its introduction with Python 2.3), what > functionality do you lose? I'm trying to encapsulate all the setup work that must be done before any actual logging occurs: setting the debugging level, choosing the output filename, declaring a format string, adding the handler, etc. If I didn't do all that in a class, where would I do it? -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run python script in emacs
I do all my python coding in emacs. It's awesome. Here's how I do it: *Create windmove bindings* This is important - it maps *Meta-i,j,k,l* to move your window focus up, left, down, right. It's used in conjunction with *C-x 3* (split window vertically) and *C-x 2* (split window horizontally). So this is how you divide emacs into quadrants and then move around them: * C-x 3 C-x 2 M-l M-x 2* You'll now find yourself in the upper right quadrant. Getting to the lower left just takes three keystrokes: *M-kj*. Getting back is *M-li*. Highly efficient. Put this in your .emacs file: (global-set-key "\M-j" 'windmove-left) (global-set-key "\M-l" 'windmove-right) (global-set-key "\M-i" 'windmove-up) (global-set-key "\M-k" 'windmove-down) *Create a python buffer* The easiest way to get a python buffer is to create a python file and then open it. I use emacs exclusively in no window mode (-nw) since the gui is so ugly and highlighted code looks so much better on a black background. * touch my_python_file.py emacs -nw my_python_file.py* # you're automatically put in python-mode You can also just open emacs -nw and create a new buffer like so: *emacs -nw C-x b my_python_file.py C-x C-s my_python_file.py M-x python-mode* *Create a python shell that is linked to your buffer* This is where we really get to show off the power of emacs. After you've got a single window split emacs horizontally (*C-x 3*). Now you've got two copies of your my_python_file.py buffer visible, one on the left, one on the right. We're going to stick a python shell on the right with *C-c !*. Now your cursor is on the right, in your python shell and your python buffer is on the left Let's move back to the python buffer with *M-j* and now let's write a small bit of code. I want to demonstrate how powerful/useful/efficient this new mode is by showing you how to execute only* part* of a for loop. while True: print "hi" break print "bye" This is obviously some silly code, It's going to print hi once, and then it's going to stop, and it's never going to print bye. You can test this out by running py-execute-buffer, which is linked to *C-c C-c*. You should see the word hi printed in the output of your shell, and your focus is also in this shell. Use *M-j* to get back to the python code. Now we're just going to execute two lines of this code: While True: print "hi" - an infinite loop. *M-Shift-<*# takes you back to the beginning of the buffer *Ctrl-Spacebar* # tells emacs to start highlighting *Ctrl-n n* # tells emacs to move the cursor down two lines, and emacs highlights both of those lines as well. *Ctrl-c |*# tells emacs to run the highlighted code only. Uh-oh, you just ran an infinite loop. 'hi' is being printed in your shell a zillion times a second. Let's stop it: * M-l* # move over to the shell *C-c C-c* # tells emacs to stop the code execution - KeyboardInterrupt Ok we're good. If you want, you can repeat the above steps, except just execute the print "bye" part of the for loop: * M-j * # move back to our python ocde *M-Shift-<* # move back to start of buffer *Ctrl-n n n* # move to the print "bye" line *Ctrl-Spacebar * # start highlighting *Ctrl-e* # move cursor to the end of the line, highlighting that line *Ctrl-c |* # run this line of code *The major benefits of this style of coding - efficiency* After you get a handle on these keyboard shortcuts - and there really aren't that many - you will be a highly efficient python hacker because of your enhanced ability to debug. You can open up large python files and execute the computationally intensive parts of them selectively, and then continue coding up the file without having to rerun that code. You can hack on multiple files at the same time in the same shell. You can modify the state (e.g., variables) of your code execution by going into your shell, and modifying or deleting it. You can kill your shell (*C-x k enter*) and start a new one. And if you end up needing a real debugger you can install pydb, which comes with a handy-dandy emacs mode: http://bashdb.sourceforge.net/pydb/ On Sat, Sep 26, 2009 at 9:54 AM, devilkin wrote: > I'm just starting learning python, and coding in emacs. I usually > split emacs window into two, coding in one, and run script in the > other, which is not very convenient. anyone can help me with it? is > there any tricks like emacs short cut? > > also please recommand some emacs plug-ins for python programming, i'm > also beginner in emacs.currently i'm only using python.el. Are any > plugins supply code folding and autocomplete? > > BTW, I'm not a english native speaker, any grammer mistakes, please > correct them. :) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundLocalError - (code is short & simple)
Thanks for the light you shed on the "namespace" issue, and for the additional info and code example. I'll be studying more about the info you shared. Also, I tried out your code example, to get firsthand experience with it. Cheers, Martin --- On Mon, 9/28/09, Bruno Desthuilliers wrote: From: Bruno Desthuilliers Subject: Re: UnboundLocalError - (code is short & simple) To: python-list@python.org Date: Monday, September 28, 2009, 8:24 AM Chris Rebert a écrit : > On Sun, Sep 27, 2009 at 8:53 PM, pylearner wrote: > >> --- >> >> Traceback (most recent call last): >> File "", line 1, in >> toss_winner() >> File "C:/Python26/toss_winner.py", line 7, in toss_winner >> coin_toss = coin_toss() >> UnboundLocalError: local variable 'coin_toss' referenced before >> assignment >> >> --- >> >> # toss_winner.py >> >> from coin_toss import coin_toss >> >> def toss_winner(): >> >> coin_toss = coin_toss() > > When Python sees this assignment to coin_toss as it compiles the > toss_winner() function, it marks coin_toss as a local variable and > will not consult global scope when looking it up at runtime (snip) > To fix the problem, rename the variable so its name differs from that > of the coin_toss() function. (snip) As an additional note: in Python, everything is an object - including modules, classes, and, yes, functions -, so there's no distinct namespace for functions or classes. If you try to execute the "coin_toss = coin_toss()" statement at the top level (or declare name 'coin_toss' global prior using it in the toss_winner function), you wouldn't get an UnboundLocalError, but after the very first execution of the statement you would probably get a TypeError on subsquent attempts to call coin_toss: >>> def coin_toss(): print "coin_toss called" return 42 >>> coin_toss >>> coin_toss = coin_toss() coin_toss called >>> coin_toss 42 >>> coin_toss() Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable >>> HTH -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Multidimensional arrays/lists
Simon Forman wrote: On Sun, Sep 27, 2009 at 12:40 PM, Someone Something wrote: I'm trying to write a little tic-tac-toe program I need a array/list such that I can represent the tic tac toe board with an x axis and y axis and i can access each square to find out whether there is an X or an O. I have absolutely no idea how to do this in python and I really, really, don't want to do this is C. -- http://mail.python.org/mailman/listinfo/python-list You can use tuples as keys in a dict R = range(3) board = {} # Initialize the board. for x in R: for y in R: board[x, y] = 'O' def board_to_string(b): return '\n'.join( ' | '.join(b[x, y] for x in R) for y in R ) print board_to_string(board) O | O | O O | O | O O | O | O board[0, 1] = 'X' print board_to_string(board) O | O | O X | O | O O | O | O You might not want to start out with 'O' already being everywhere, though. ;-) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Python win32 ActiveX scripting input box question
I am trying to assign the user input into a variable. I am using Python as an ActiveX scripting language in a host that allows for activex scripting. I am able to create an input box with the following >> import win32ui >> from pywin.mfc.dialog import Dialog >> d = Dialog(win32ui.IDD_SIMPLE_INPUT) >> d.CreateWindow() This will create an input box dialog (there are other ways to create an input box with Python Win32, but this seems to be the only one that works in an activex scripting host). I just CAN NOT figure out how to: 1. Assign the user input in the input box into a variable that I can use in my script. 2. I also, can not figure out how to change the Title of the dialog (I can change the Caption but not the Title), and 3. The size (specially the height) of the input box dialog. Any pointers/clues would be highly appreciated. Kevin -- http://mail.python.org/mailman/listinfo/python-list
Re: Multidimensional arrays/lists
On Mon, Sep 28, 2009 at 3:27 PM, Ethan Furman wrote: > Simon Forman wrote: >> >> On Sun, Sep 27, 2009 at 12:40 PM, Someone Something >> wrote: >> >>> I'm trying to write a little tic-tac-toe program I need a array/list such >>> that I can represent the tic tac toe board with an x axis and y axis and >>> i >>> can access each square to find out whether there is an X or an O. I have >>> absolutely no idea how to do this in python and I really, really, don't >>> want >>> to do this is C. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> You can use tuples as keys in a dict >> >> R = range(3) >> >> board = {} >> >> # Initialize the board. >> for x in R: >> for y in R: >> board[x, y] = 'O' >> >> >> def board_to_string(b): >> return '\n'.join( >> ' | '.join(b[x, y] for x in R) >> for y in R >> ) >> >> >> > print board_to_string(board) >> >> O | O | O >> O | O | O >> O | O | O >> >> > board[0, 1] = 'X' > print board_to_string(board) >> >> O | O | O >> X | O | O >> O | O | O > > You might not want to start out with 'O' already being everywhere, though. > ;-) > > ~Ethan~ D'oh! I really do need to get more sleep. ;P ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Repeated output when logging exceptions
On Mon, Sep 28, 2009 at 4:38 PM, John Gordon wrote: > In <6bce12c3-f2d9-450c-89ee-afa4f21d5...@h30g2000vbr.googlegroups.com> Vinay > Sajip writes: > >> The logging package allows you to add tracebacks to your logs by using >> the exception() method, which logs an ERROR with a traceback and is >> specifically intended for use from within exception handlers. All that >> stuff with temporary files seems completely unnecessary, even with Python >> 2.3. > > I didn't know about the exception() method. Thanks! > >> In general, avoid adding handlers more than once - which you are >> almost guaranteed to not avoid if you do this kind of processing in a >> constructor. If you write your applications without using the >> exceptionLogger class (not really needed, since logging exceptions >> with tracebacks is part and parcel of the logging package's >> functionality since its introduction with Python 2.3), what >> functionality do you lose? > > I'm trying to encapsulate all the setup work that must be done before any > actual logging occurs: setting the debugging level, choosing the output > filename, declaring a format string, adding the handler, etc. > > If I didn't do all that in a class, where would I do it? Put it in a module. :] > -- > John Gordon A is for Amy, who fell down the stairs > gor...@panix.com B is for Basil, assaulted by bears > -- Edward Gorey, "The Gashlycrumb Tinies" > -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLObject
> I'm new to using SQLObject, and having some problems with getting it > to recognise my current MySQL database. > > I've set up my connection fine, but it won't recognise the names of > the columns (presumably because they're not written using the default > naming convention?). For example, one of my columns is an acronym, so > is 3 uppercase letters. I've tried the following: > > class Table1(sqlobject.SQLObject): > _connection = conn > _fromDatabase = True > > class sqlmeta: > table = 'Table1' > idName = 'Table1ID' > > BOB = StringCol() > > print Table1.get(1) > > this gives the result > > Unknown column 'bo_b' in 'field list' > > So, specifically a few questions: > > I've seen the attribute in class sqlmeta of 'columns' - will this find > my column names automatically, or do I still need to input them > manually? If the latter..: > > I assume I set the names of each column in the instance of sqlmeta > (like I have done with the table name) - how do I do this?! Do I do > this before or after I've told SQLObject that the BOB column is a > String column? > > Is there a published list of the default naming convention that > SQLObject follows? I couldn't find it on the website. The current maintainer of sqlobject is Oleg Broytmann and he frequently answers support questions on the sqlobject mailing list so it's best to ask questions such as these over there: https://lists.sourceforge.net/lists/listinfo/sqlobject-discuss HTH, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
is there some error crashing reporting
like MadExcept for Delphi http://www.madshi.net/madExceptDescription.htm which catches any error, send an email with the error report and complete system analysis to the author, and continues the program (if possible) thanks, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Using String for new List name
On Sep 28, 2:00 pm, Dave Angel wrote: > Scott wrote: > > Thank you fine folks for getting back with your answers! > > > So down the road I do dictname[line42].append("new stuff"). (or [var] > > if I'm looping through the dict) > > Nope, you still haven't gotten it. Of course, I really don't know where > you're going wrong, since you didn't use the same symbols as any of the > responses you had gotten. > > I suspect that you meant dictname[] to be the dictionary that Duncan > called values[]. On that assumption, in order to append, you'd want > something like: > > values["line42"].append("new stuff") > or > values[var].append("new stuff") if you happen to have a variable called > var with a value of "line42". > > You will need to get a firm grasp on the distinctions between symbol > names, literals, and values. And although Python lets you blur these in > some pretty bizarre ways, you haven't a chance of understanding those > unless you learn how to play by the rules first. I'd suggest your first > goal should be to come up with better naming conventions. And when > asking questions here, try for more meaningful data than "Line42" to > make your point. > > Suppose a text file called "customers.txt" has on each line a name and > some data. We want to initialize an (empty) list for each of those > customers, and refer to it by the customer's name. At first glance we > might seem to want to initialize a variable for each customer, but our > program doesn't know any of the names ahead of time, so it's much better > to have some form of collection. We choose a dictionary. > > transactions = {} > with open("customers.txt") as infile: > for line in infile: > fields = line.split() > customername = fields[0] #customer is first thing on > the line > transactions[customername] = [] #this is where we'll put > the transactions at some later point, for this customer > > Now, if our program happens to have a special case for a single > customer, we might have in our program something like: > > transactions["mayor"].append("boots") > > But more likely, we'll be in a loop, working through another file: > > . > for line in otherfile: > fields = line.split() > customername = fields[0] > transaction = fields[1] > > transactions[customername].append(transaction) #append > one transaction > > or interacting: > name = raw_input("Customer name") > trans = raw_input("transaction for that customer") > transactions[name].append(trans) Dave, I'm amazed at everyone's willingness to share and teach! I will sure do the same once I have the experience. I think that one of the problems here is that I tried to make my initial question as bone simple as possible. When I first tried to explain what I was doing I was getting up to 2 pages and I thought "I bet these folks don't need to read my program. They probably just need to know the one bit I'm looking for." So I deleted it all and reduced it to the 10 line example that I posted. It was then suggested that I eschew using regular expressions when not required because I used Y = re.split(" ", X) in my example. In my program it is actually aclLs = re.split("\s|:|/", aclS) which I think requires a regex. I just didn't want anyone to waste their time parsing the regex when it was not really germane to my actual question. The same applies to the suggestion for using meaningful variables. In the above aclLs represents (to me) "access control list List-Split" and aclS represents "access control list String." Again, I thought X and Y, like foo and bar or spam and eggs would do for a simple example. Of course I then went and forgot the quotes around "line42" and really looked confused. I was so excited to have an answer that I typed the reply without thinking it through. Not good. Don't worry though, I take no offense. I understand and welcome the advice. I don't have anyone to work with and this post is my first interaction with any person who knows programming and Python. I am but a network engineer (Cisco, Lan/Wan, firewalls, security, monitoring (this is the connection), etc.) who has never programmed. I will work on clearer communications in future posts. I'm happy for a chance to share what I am actually trying to accomplish here. I have a firewall with a static list of access-control-list (ACL) rules (about 500 rules). I also have a directory with one week of syslog output from the firewall. About 100 text files that are each about 10 to 30 MB in size. My quest, if you will, is to create a list of syslog entries, each representing a successful network connection, with each syslog entry listed under the access-list rule that allowed it. Since ACL rules can be written with a range of granularity, i.e. loose or tight, with or without Port Number, etc., their order is important. A firewall scans the rules in order, using the first succ
module path?
hello, is there a way to determine the file location of a loaded module? assuming it is not built in. import settings print settings produces: i would like to get to this path somehow other than by parsing the string representation of the module. is there a property on types.ModuleType? i could not find anything... thanks konstantin -- http://mail.python.org/mailman/listinfo/python-list
Re: Business issues regarding adapting Python
On Sep 27, 12:13 am, Nash wrote: > Hello everyone, > > I'm a big time python fan and it has helped me write code fast and > push it out quickly. We have a medium sized telecom product written > 90% in Python and 10% in Java. The problem is, in the place where we > work (Pakistan), we can't find Python developers. I asked HR to send > me figures on how many people do we have available who have worked > with C++, Java, PHP and Python with 2-3 years of experience. They did > a search on available candidates on Pakistan's biggest jobsite and > this is what they sent: > > Language: Available Candidates in Pakistan (Available Candidates in > our city) > Java: 2020 (750) > C++: 1540 (650) > PHP: 630 (310) > Python: 25 (4) > > Almost no-one shows up with Python experience when we put out a job > opening and now it is becoming a real hurdle. Despite our liking and > cost savings with the language, we are thinking about shifting to > Java. > > 1. Have any of you faced a similar issue? How did you resolve it? > 2. Do you think it makes sense to hire good programmers and train them > on Python? > 3. If we do train people in Python for say a month; are we just > creating a team of mediocre programmers? Someone who has worked with > Python for over an year is much different than someone who has worked > with Python for only a month. > 4. Any suggestions or idea? Related posts, articles etc would > certainly help! > > I know that going Java will probably mean a 3x increase in the number > of people that we have and require time for Python component > replacement with Java ones. But for Business Continuity sake, > management doesn't mind. > > Thanks a lot everyone! If I were the one looking for developers, I wouldn't search for people with Python experience. IMO, any good developer can rapidly learn to be a good Python developer. In contrast, ISTM that it takes at least 6 months to become a good Java developer and a couple years to become a decent C++ programmer. Python is distinct because it is not that hard to learn. So, if I were hiring, I would focus on general programming skills and knowledge of the problem domain. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: module path?
On Mon, 28 Sep 2009 16:41:36 -0700, akonsu wrote: > hello, > > is there a way to determine the file location of a loaded module? > assuming it is not built in. > > import settings > print settings > > produces: > > i would like to get to this path somehow other than by parsing the > string representation of the module. is there a property on > types.ModuleType? i could not find anything... Did you look at dir(settings) for a list of method and attribute names? Look at module.__file__. But be careful because some modules are "built in", that is, they don't actually exist as a separate file and are part of the Python compiler. E.g.: >>> import sys >>> sys.__file__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__file__' >>> sys -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Business issues regarding adapting Python
Vladimir Ignatov wrote: Ha-ha-ha (sorry, can't resist). Here is at Moscow/Russia I have had a tought time finding a Python-related programming job. Positions both very rare (comparing with Java/C++ - maybe 1/100) and not pays well. And about 99% of them are web+Django. To who/what are you replying? -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' -- http://mail.python.org/mailman/listinfo/python-list
Re: module path?
On Sep 28, 7:51 pm, Steven D'Aprano wrote: > On Mon, 28 Sep 2009 16:41:36 -0700, akonsu wrote: > > hello, > > > is there a way to determine the file location of a loaded module? > > assuming it is not built in. > > > import settings > > print settings > > > produces: > > > i would like to get to this path somehow other than by parsing the > > string representation of the module. is there a property on > > types.ModuleType? i could not find anything... > > Did you look at dir(settings) for a list of method and attribute names? > > Look at module.__file__. But be careful because some modules are "built > in", that is, they don't actually exist as a separate file and are part > of the Python compiler. E.g.: > > >>> import sys > >>> sys.__file__ > > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '__file__'>>> sys > > > > -- > Steven thanks! i did not know about dir() method. konstantin -- http://mail.python.org/mailman/listinfo/python-list
Re: module path?
akonsu wrote: hello, is there a way to determine the file location of a loaded module? assuming it is not built in. import settings print settings produces: i would like to get to this path somehow other than by parsing the string representation of the module. is there a property on types.ModuleType? i could not find anything... thanks konstantin The property is called __file__ So in this case,filename = settings.__file__ -- http://mail.python.org/mailman/listinfo/python-list
Global array in python
How can i declare a global array in python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Global array in python
On Mon, Sep 28, 2009 at 5:48 PM, Rudolf wrote: > How can i declare a global array in python? Python has no concept of declarations. And it doesn't have arrays, it has dynamically-resizing lists. Some examples: one_empty_list = [] a_list_of 5 zeroes = [0]*5 Might I recommend you read the Python tutorial? I will help you in your programming class. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the file mode of .pyc files has x?
On Mon, Sep 28, 2009 at 12:43 AM, greg wrote: > Peng Yu wrote: >> >> -rw--- 1 pengy lilab 29 2009-09-26 10:10:45 main.py >> -rwx-- 1 pengy lilab 106 2009-09-26 10:19:17 test.py >> -rwx-- 1 pengy lilab 339 2009-09-26 10:20:39 test.pyc > > Doesn't happen for me with 2.5 on Darwin. > > What python/OS are you using? python 2.6.2 and CentOS -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the file mode of .pyc files has x?
On Mon, Sep 28, 2009 at 8:22 AM, Steven D'Aprano wrote: > On Mon, 28 Sep 2009 17:01:40 +1000, Cameron Simpson wrote: > >> On 26Sep2009 10:24, Peng Yu wrote: | > >> [st...@sylar test]$ ls -l >> | > total 16 >> | > -rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py | > -rw-rw-r-- >> 1 steve steve 94 2009-09-26 23:08 test.pyc | > >> | > Have you checked the umask of your system? | >> | Here are my test case. If the .py file has the 'x' mode, the | >> corresponding .pyc file also has the 'x' mode after the .py file is | >> imported. >> >> Yes, I see this too. > > Is this a problem? > > Taking a wild guess, I'd imagine that the .pyc file gets its permissions > copied from the .py file. I don't see that as a major issue. A buglet, > rather than a bug, at worst. Although this is a small issue, I still think that it is annoying. If it can be fixed in the future version of python, that will be great. Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: How to refer to class name and function name in a python program?
On Sun, Sep 20, 2009 at 12:43 PM, Benjamin Kaplan wrote: > On Sun, Sep 20, 2009 at 12:43 PM, Peng Yu wrote: >> On Sun, Sep 20, 2009 at 11:32 AM, Vijayendra Bapte >> wrote: >>> On Sep 20, 8:38 pm, Peng Yu wrote: Hi, I have the following code. I want to change the function body of __repr__ to something like return 'In %s::%s' % ($class_name, $function_name) I'm wondering what I should write for $class_name and $function_name in python. Regards, Peng class A: def __init__(self): pass def __repr__(self): return 'In A::__repr__' a = A() print a >>> >>> Using decorator: >>> >>> >>> def echo(func): >>> def _echo(self, *args, **kw): >>> return "In %s.%s" % (self.__class__.__name__, func.func_name) >>> >>> return _echo >>> >>> class A: >>> >>> �...@echo >>> def __repr__(self): >>> pass >>> >>> a = A() >>> print a >> >> What does @echo mean? >> >> Regards, >> Peng > > It's a decorator, which wraps the function with another function it's > the equivalent of calling > > def __repr__(self) : > pass > > __repr__ = echo(__repr__) I looked at the table of content of python tutorial at http://docs.python.org/tutorial/ But I don't see which section discuss this concept. If it is there, would you please let me know which section I should read. Or this concept is discussed somewhere else? Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: Global array in python
On Sep 28, 8:04 pm, Chris Rebert wrote: > On Mon, Sep 28, 2009 at 5:48 PM, Rudolf wrote: > > How can i declare a global array in python? > > Python has no concept of declarations. > And it doesn't have arrays, it has dynamically-resizing lists. What version are you using, i must have py4000 alpha? >>> import array >>> a = array.array('i') >>> a.append(1) >>> a array('i', [1]) hmm? ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: can i use the browser to show the result of python
On Sep 27, 12:24 pm, Dave Angel wrote: > Hacken wrote: > > On Sep 25, 6:27 pm, Dave Angel wrote: > > >> Hacken wrote: > > >>> I have write some python script > > >>> i want to use browser(IE or FF) to call it, an show the returns! > > >>> how to? > > >> You don't say much about your environment, nor the nature of your > >> script. So my response will be very generic. > > >> If your script writes a valid html/xml/xhtml format to stdout, then you > >> could put the script onto a web server with cgi enabled, and mark it > >> executable. Then you could enter the URL for that cgi file into your > >> browser, and see that generated web page. > > >> Interesting additional gotchas: You need rights to upload (ftp) to such > >> a server. The server needs to have an appropriate Python available, and > >> configured to permit cgi access for files with the .py extension. > >> Further, if the server is Unix, your file must be in Unix text format, > >> with a shebang line that matches the location of the appropriate version > >> of python on that particular server. > > >> DaveA > > > Thanks. > > > but,i do not want to setup a webserver, i think that is so big for > > other user. > > > i just want write my programes in python, and i use Browser to show my > > GUI, > > > can i do that?and how to? > > > thanks,waitting.. > > What I described is all I've done firsthand. But more is possible. And > I've worked on fancier setups, but somebody else did the plumbing. > > As Stephen points out, you can use webbrowser module to launch a > browser. So you could write python code to create a web page(s), write > it to a file, then launch the browser using the "file://.." > protocol. That'd be fine for displaying pages that are generated > entirely before launching the browser. But if you want the python > program to get feedback from the browser (which is usually what's meant > by using the browser for a GUI), you're going to have to simulate a > webserver. > > That can be done on a single machine using the "localhost" shortcut. I > don't know how to do it, but there is a sample in the 2.6 release of > Python, at least in the Windows version. You run it from the Start > menu->Python2.6->module docs. > > The source for the main server is in > c:\Python26\Tools\Scripts\pydocgui.pyw. (though all it does is import > pydoc.py and call it.) Now that particular program's purpose is to > generate and display docs for the python files on the system, but > presumably it's a starting place. > > Now, this is the first I've looked at this file, but at line 1967 is a > function serve(), which is commented as the web browser interface. The > function serve() probably has much of what you're interested. In > particular, it contains a few class definitions, including DocServer and > DocHandler, which send data back and forth to the browser, over the > localhost connection. > > It looks like it gets its core code from BaseHTTPServer module. > > At line 2058 is a function gui(), which is a small tkinter program that > just displays a few buttons and such. That's not what you're asking about. > > Hopefully somebody else has actually used some of this stuff, and can > elaborate. > > DaveA- Hide quoted text - > > - Show quoted text - Thaks both u guys I find a way to do my work ,but i found a basic webserver is really necessary. First,i use webbrowser,Steven recommend,to call the browser open a html file,my gui,in this html file i make a form and submit a GET request with the paraments i need second, i use BaseHTTPServer, to handle the GET request,parse the request get the paraments i need, and use these parament to finish my logic thrid, use BaseHTTPServer make a response to the browser with a formated html file with my result. It's not complex like i think,because the BaseHTTPServer is not complex Thanks DaveA,a webserver,like you said,is a necessary,&Steven, your webbrowser. -- http://mail.python.org/mailman/listinfo/python-list
How to jump out of nested 'for'-loops?
Hi, I want some command to jump out of nested loop. I'm wondering what is the most convenient way to do so in python. for i in range(10): print "i = ", i for j in range(10): if i*10 + j == 50: print i*10 + j break # I want to jump out of the loops. Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
"Pipeline" Generator presentation - where?
I remember reading (a few times) a presentation about using generators to create "pipelines" The idea was to create very specific and small generator functions, and then combine them together to get larger results. The example used was to parse log files contained in gzipped log files among other things. I'd love to read it again, but I can't find it! Can somebody please point me to it? TIA. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: How to jump out of nested 'for'-loops?
: > I want some command to jump out of nested loop. I'm wondering what is > the most convenient way to do so in python. http://www.google.com/search?q=python+nested+break -[]z. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to jump out of nested 'for'-loops?
On Sep 28, 10:09 pm, Peng Yu wrote: > Hi, > > I want some command to jump out of nested loop. I'm wondering what is > the most convenient way to do so in python. > > for i in range(10): > print "i = ", i > for j in range(10): > if i*10 + j == 50: > print i*10 + j > break # I want to jump out of the loops. > > Regards, > Peng if your code is in a function/method just use return -- http://mail.python.org/mailman/listinfo/python-list
Re: How to jump out of nested 'for'-loops?
On Sep 28, 8:09 pm, Peng Yu wrote: > Hi, > > I want some command to jump out of nested loop. I'm wondering what is > the most convenient way to do so in python. > > for i in range(10): > print "i = ", i > for j in range(10): > if i*10 + j == 50: > print i*10 + j > break # I want to jump out of the loops. > > Regards, > Peng Can you please give the people who answered your question a simple "thank you"?? ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: How to jump out of nested 'for'-loops?
On Mon, 28 Sep 2009 22:09:37 -0500 Peng Yu wrote: > I want some command to jump out of nested loop. I'm wondering what is > the most convenient way to do so in python. Forget about jumping out of a loop. Put your loop into a function and simply return. Much cleaner and clearer. > for i in range(10): > print "i = ", i > for j in range(10): > if i*10 + j == 50: > print i*10 + j > break # I want to jump out of the loops. def myfunc(li, lim, mul): for i in li: print "i = ", i for j in range(10): if i*mul + j == lim: return i*mul + j print myfunc(range(10), 50, 10) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Using pySNMP
I realize this is not the pySNMP mailing list. However, can someone tell me if pySNMP uses human readable forms of mibs, such as Net-SNMP does, or does it use only the oid's? Thanks Mitch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to jump out of nested 'for'-loops?
Peng Yu wrote: > I want some command to jump out of nested loop. I'm wondering what is > the most convenient way to do so in python. I'm sure I'm wasting my breath by saying this, but would it hurt you to actually check the list before posting? You're not the only person to ever have used Python, a lot of your questions have been answered repeatedly in the past. As it stands, this very question was discussed here no more than 2-3 days ago: http://groups.google.com/group/comp.lang.python/browse_frm/thread/9145497c04ad5c1b# As has been mentioned repeatedly, your apparent inability to think for yourself combined with the lack of acknowledgement to those who do help you is rapidly burning through your social credit here. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Pipeline" Generator presentation - where?
Sean DiZazzo wrote: I remember reading (a few times) a presentation about using generators to create "pipelines" The idea was to create very specific and small generator functions, and then combine them together to get larger results. The example used was to parse log files contained in gzipped log files among other things. I'd love to read it again, but I can't find it! Can somebody please point me to it? TIA. ~Sean It's probably this presentation by David Beazley you are thinking about: http://www.dabeaz.com/generators/ If you like that, here is another of his presentations about creating coroutines from generators: http://www.dabeaz.com/coroutines Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: "Pipeline" Generator presentation - where?
Sean DiZazzo wrote: > I remember reading (a few times) a presentation about using generators > to create "pipelines" The idea was to create very specific and small > generator functions, and then combine them together to get larger > results. The example used was to parse log files contained in gzipped > log files among other things. > > I'd love to read it again, but I can't find it! Can somebody please > point me to it? TIA. Hey Sean, I think you're refering to David Beazley's already-classic "Generator Tricks for System Programmers": http://www.dabeaz.com/generators/ His "A Curious Course on Coroutines and Concurrency" is also highly recommended (there's a link from that page). Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Pipeline" Generator presentation - where?
On Sep 28, 9:12 pm, alex23 wrote: > Sean DiZazzo wrote: > > I remember reading (a few times) a presentation about using generators > > to create "pipelines" The idea was to create very specific and small > > generator functions, and then combine them together to get larger > > results. The example used was to parse log files contained in gzipped > > log files among other things. > > > I'd love to read it again, but I can't find it! Can somebody please > > point me to it? TIA. > > Hey Sean, > > I think you're refering to David Beazley's already-classic "Generator > Tricks for System Programmers":http://www.dabeaz.com/generators/ > > His "A Curious Course on Coroutines and Concurrency" is also highly > recommended (there's a link from that page). > > Hope this helps. Thanks to you both! Thats it. I've finally begun to use generators more frequently in my code, and I think it's a perfect time to actually type out the examples and absorb. Can't wait to read the coroutines presentation as well. It's something I've never seen. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Global array in python
2009/9/29 rantingrick : > On Sep 28, 8:04 pm, Chris Rebert wrote: >> On Mon, Sep 28, 2009 at 5:48 PM, Rudolf wrote: >> > How can i declare a global array in python? >> >> Python has no concept of declarations. >> And it doesn't have arrays, it has dynamically-resizing lists. > > What version are you using, i must have py4000 alpha? > import array a = array.array('i') a.append(1) a > array('i', [1]) > > hmm? ;-) Heh. I must remember to never state "python does not have X" - it almost always has X, I just don't know where yet ;) > -- > http://mail.python.org/mailman/listinfo/python-list > -- twitter.com/olofb olofb.wordpress.com olofb.wordpress.com/tag/english -- http://mail.python.org/mailman/listinfo/python-list
Re: Global array in python
On Mon, Sep 28, 2009 at 6:55 PM, rantingrick wrote: > On Sep 28, 8:04 pm, Chris Rebert wrote: >> On Mon, Sep 28, 2009 at 5:48 PM, Rudolf wrote: >> > How can i declare a global array in python? >> >> Python has no concept of declarations. >> And it doesn't have arrays, it has dynamically-resizing lists. > > What version are you using, i must have py4000 alpha? > import array a = array.array('i') a.append(1) a > array('i', [1]) > > hmm? ;-) I should have qualified that statement... :) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why the file mode of .pyc files has x?
Peng Yu wrote: What python/OS are you using? python 2.6.2 and CentOS Just tried 2.6 on Darwin, and it does happen. So looks like 2.6 has been changed to inherit the permission bits from the .py. Makes sense, except that the x bits should really be turned off. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
os.listdir unwanted behaviour
Hello, I am writing code that cycles through files in a directory and for each file it writes out another file with info in it. It appears that as I am iterating through the list returned by os.listdir it is being updated with the new files that are being added to the directory. This occurs even if I reassign the list to another variable. Here is my code: fileList = os.listdir(temporaryDirectory) for curFile in fileList: # print the file list to see if it is indeed growing print FileList fp = file(os.path.join(temporaryDirectory, "." + curFile), 'w') # write stuff fp.close() Here is the output: ['a', 'b', 'c'] ['a', 'b', 'c', '.a'] ['a', 'b', 'c', '.a', '.b'] ['a', 'b', 'c', '.a', '.b', '.c'] So the list is growing and eventually curFile iterates through the list of files that were created. I don't want this to happen and it seems like a bug because the fileList variable should be static, i.e. not updated after being assigned. Even if I assign fileList to another variable this still happens. Any ideas? Chris. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.listdir unwanted behaviour
On Mon, Sep 28, 2009 at 11:03 PM, Chris Adamson wrote: > Hello, > > I am writing code that cycles through files in a directory and for each file > it writes out another file with info in it. It appears that as I am > iterating through the list returned by os.listdir it is being updated with > the new files that are being added to the directory. This occurs even if I > reassign the list to another variable. > > Here is my code: > > fileList = os.listdir(temporaryDirectory) > > for curFile in fileList: > # print the file list to see if it is indeed growing > print FileList > fp = file(os.path.join(temporaryDirectory, "." + curFile), 'w') > # write stuff > fp.close() > > Here is the output: > > ['a', 'b', 'c'] > ['a', 'b', 'c', '.a'] > ['a', 'b', 'c', '.a', '.b'] > ['a', 'b', 'c', '.a', '.b', '.c'] > > So the list is growing and eventually curFile iterates through the list of > files that were created. I don't want this to happen and it seems like a bug > because the fileList variable should be static, i.e. not updated after being > assigned. > Even if I assign fileList to another variable this still happens. Any ideas? Copy the list instead? Python uses call-by-object, so assignment to a variable doesn't cause copying, you must do so explicitly: fileList = os.listdir(temporaryDirectory)[:] Although this behavior (bug?) you're running into definitely seems like ought to be mentioned in the docs. File a bug perhaps? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Repeated output when logging exceptions
On Sep 28, 9:38 pm, John Gordon wrote: > > If I didn't do all that in a class, where would I do it? > You could, for example, use the basicConfig() function to do it all for you. import logging logging.basicConfig(filename='/path/to/my/log',level=logging.DEBUG) logging.debug('This message should go to the log file') Here's the documentation link for simple examples: http://docs.python.org/library/logging.html#simple-examples Here's the link for basicConfig: http://docs.python.org/library/logging.html#logging.basicConfig Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list