Re: code in a module is executed twice (cyclic import problems) ?
ryles wrote: >> I always thought code in a module was only executed once, >> but doesn't seem to be true. >> >> I'm using Python 2.5. >> >> And this is the example: >> >> == A.py == >> My_List = [] >> >> == B.py == >> from A import * >> My_List.append ( 3 ) >> print 'B', My_List >> import C >> >> == C.py == >> from A import * >> from B import * >> print 'C', My_List >> >> Now when you start with B.py as the main program, >> this is the resulting output: >> >> B [3] >> B [3, 3] >> C [3, 3] >> >> Why is the B.py executed twice ? B.py is the entry point of the program and it is known internally as __main__. There is no record of a B.py. If you really must import objects from the main module you can do it like this. from __main__ import * -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: the usage of 'yield' keyword
Peng Yu wrote: > http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt > > The explanation of yield is not clear to me, as I don't know what a > generator is. I see the following example using 'yield'. Could > somebody explain how 'yield' works in this example? Thank you! > > def brange(limit): > i = 0 > while i < limit: > yield i > i += 1 Let's make this as simple as possible. >>> def g(x): ...yield x ... >>> p = g(4) >>> type(p) >>> type(type(p)) So there you have it. Generator is an instance of 'type', hence a new-style class, even though it is returned by a simple looking function. >>> p.next() 4 What were you expecting? >>> type(g) g is a function that returns a generator. The yield statement does two things. It states what is to be returned by the generator's next() method and it also defines g as a function that returns a generator. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a unicode string to a file ?
Stef Mientki wrote: > hello, > > By writing the following unicode string (I hope it can be send on this > mailing list) > > Bücken > > to a file > > fh.write ( line ) > > I get the following error: > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in > position 9: ordinal not in range(128) > > How should I write such a string to a file ? Your code fails because the unicode string denoted by the name, line, cannot be converted to ASCII, which python silently tries to do. Instead, use a compatible character encoding. Note the explicit conversion. fh.write(line.encode('utf-8')) Alternatively, you can write sixteen bit unicode directly to a file: import codecs f = codecs.open('unicodetest.txt', mode='w', encoding='utf-16') f.write(u'Hello world\n') f.close() -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: md5 strange error
Tim Golden wrote: > catalinf...@gmail.com wrote: >> I have this error , what happen ? >> >> Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38) >> [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import md5 >>>>> pass = md5.new() >> File "", line 1 >> pass = md5.new() >> ^ >> SyntaxError: invalid syntax > > pass is a keyword, as in: > > def f (): > pass > Correct form when you want to use a keyword for a variable is to precede it with and underscore. _pass = md5.new() -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Items inheriting attributes from its container?
Kreso wrote: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container > instances. However, I would like it so that the items contained in the > particular instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' > > The example appended below does that, but with the restriction that > container attributes must be set in the instantiation phase. This is > actually fine for me at the moment because my objects are "read only", but > I would like to hear about better solutions, with more flexibility, > please. > > > #-8< > class Player: > """Class for items""" > > def __init__(self, playerdata, team): > self.data = playerdata > for key in team.__dict__: > setattr(self, key, team.__dict__[key]) > return > > > class Team(list): > """Class for containers""" > > def __init__(self, teamdata, playerdata): > for key in teamdata: > setattr(self, key, teamdata[key]) > for item in playerdata: > self.append(Player(item, self)) > return > > > lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} > lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] > > lakers = Team(lakersdata, lakersplayers) > > # This is fine: > p1 = lakers[1] > print p1.kitcolor > > # However the following doesn't work: > lakers.kitcolor = 'blue' > print p1.kitcolor > > #-8<---- I hope this gives you some good ideas. http://en.wikipedia.org/wiki/Join_(SQL) I suspect you will be finding a use for the special __getattr__ method, which is called when an attribute is not found. This can be used to search on your set of joined objects. Your list of joined objects should be a set() to prevent duplicates. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Is it a bug?
Gleb Belov wrote: > Hey everyone! I'm quite new to Python and equally new to newsgroups in > general, so apologies if this makes no sense. > > Basically, I was just exploring Python "arrays" on my own, since I > come from C++. What I did was: >>>> words = ["Hi!", "What's up?", "Bye!"] >>>> print words > ['Hi!', "What's up?", 'Bye!'] > > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? For the first element: >>> words[0] > 2) I just noticed that the first and the last words in the output are > enclosed in single quotes, and the middle one is enclosed in double > quotes. Is it a bug? If not, why does the output work that way? The output is valid python code. To represent with single quotes for the second item, there would have to be a \ escape character for the apostrophe. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
Philip Semanchuk wrote: > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > >> Hello! I'm working on an exercise wherein I have to write a Guess The >> Number game, but it's the computer who's guessing MY number. I can get >> it to work, but there's one obvious problem: the computer generates >> random numbers until one of them corresponds to my number, but it will >> often generate one number (eg. 4) numerous times, meaning it doesn't >> know that this number is invalid. What I mean is, it will sometimes >> use 37 tries to guess a number out of 1 - 9, which makes no sense, >> since it should only take 9 tries, at most. I was trying to find a way >> to make a dynamic list of all the numbers the computer generates in >> the loop and then make it re-generate the number if the previous >> number is present in the list, so it doesn't keep on generating 4 (as >> an example). I don't know if that makes sense... Basically, we humans >> know that once something is incorrect, there's no point in trying to >> use it as the answer next time, because we already know it's >> incorrect. How do I go about coding this in Python? I'm still quite >> new to the language so any help will be appreciated... > > One cheap way to do it (not necessarily efficient) is to make a list > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > put them in random order and then run through the guesses one at a time. import random import time l = range(1, 10) while l: print l.pop(random.randint(0, len(l) - 1)) time.sleep(2) -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
You are trying to run code in a class that does not exist yet. def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": fact(5)}) Demo = Demo() d = Demo() print d._classvar# prints 120 print d.fact(7) # prints 5040 print Demo # prints -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with arrays
Dave Angel wrote: > With this change the best solution changes from a random shuffle to a > binary search. Which is not what the OP asked for. Anyway, I think whatever solution is chosen it's probably best written as a generator. The new pushback syntax may prove useful. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
kj wrote: > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. So why didn't you delete it after you were done with it? Class Demo(object): def fact(x): ... _classvar = fact(5) del fact() -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: How to unencode a string
jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. Would also like to handle special characters like '",(){} > [] etc/ import urllib print urllib.unquote("Word1%20Word2%20Word3") -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Class implements Interface?
Emanuele D'Arrigo wrote: > Apologies, my fault, I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. http://docs.python.org/library/abc.html In particular, pay attention to the term virtual subclass and also note in the second code example the use of __subclasshook__ to define virtual subclass membership by the presence (or not) of class attributes. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help with Python scoping rules
kj wrote: > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x How is this a problem? There is no ambiguity between the global scope and the local from within foo. >From within foo C is accessed from the global scope having not found it as a local. Once you have C C.x is just one step away. Variable self is local to function foo since it was passed in as a parameter from the method which wraps it. Variable self refers to a class instance which contains a dictionary. Variable x is absent from the instance dictionary so the class self.__class__ is referenced, again from local scope to find x. If it wasn't found there the superclasses would have been searched before throwing an attribute error. It seems to me, you are confusing instance creation with class creation. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Select column from a list
hoffik wrote: > > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the > first row again! I can't see why. rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] cols = zip(*rows) To just get the second column: zip(*rows)[1] -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: File Handling Problem
joy99 wrote: > Dear Group, > > I have a file. The file has multiple lines. I want to get the line > number of any one of the strings. > Once I get that I like to increment the line number and see the string > of the immediate next line or any following line as output. The > problem as I see is nicely handled in list, > > like list_one=["god","earth","sky","cloud","rain"] > list_one[0]="god" > list_one[2]="sky" > > but can it be for string and file? It's easy to read a file into a list. f = open("myfile.txt", "r") list_one = f.read().splitlines() f.close() -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: Running Sum script
Jul wrote: > hello, > > I have a .txt file that is in this format -- > > 12625 > 17000 > 12000 > 14500 > 17000 > 12000 > 17000 > 14500 > 14500 > 12000 > ...and so on... > > i need to create a python script that will open this file and have a > running sum until the end of file. Untested: with open("numbers.txt", "r") as f: print sum(int(x) for x in f) -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list
Re: run-time inclusion of files
travis+ml-pyt...@subspacefield.org wrote: > I'm interested in three seperate problems: > > 1) being able to import a file that isn't in the standard module include > path sys.path.insert(0, "/path/to/module" module = __import__("module") del sys.path[0] Ideally this goes into a function, possibly with os.path.split to break apart absolute paths. > 2) being able to import a file whose name is specified in a python string sys = __import__("sys") > 3) being able to reload the file if it changes on disk sys = reload(sys) # sys must have been imported already Maybe use in conjunction with python-inotify and or Gamin for change detection. -- Stephen Fairchild -- http://mail.python.org/mailman/listinfo/python-list