title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
calculate exponential moving average in python
488,670
14
2009-01-28T18:01:44Z
488,700
8
2009-01-28T18:12:07Z
[ "python", "signal-processing", "average", "digital-filter" ]
I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this? I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place. So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates? ``` from datetime import date days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)] IQ = [110, 105, 90] ``` (there's probably a better way to structure the data, any advice would be appreciated)
I did a bit of googling and I found the following sample code (http://osdir.com/ml/python.matplotlib.general/2005-04/msg00044.html): ``` def ema(s, n): """ returns an n period exponential moving average for the time series s s is a list ordered from oldest (index 0) to most recent (index -1) n is an integer returns a numeric array of the exponential moving average """ s = array(s) ema = [] j = 1 #get n sma first and calculate the next n period ema sma = sum(s[:n]) / n multiplier = 2 / float(1 + n) ema.append(sma) #EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev) ema.append(( (s[n] - sma) * multiplier) + sma) #now calculate the rest of the values for i in s[n+1:]: tmp = ( (i - ema[j]) * multiplier) + ema[j] j = j + 1 ema.append(tmp) return ema ```
calculate exponential moving average in python
488,670
14
2009-01-28T18:01:44Z
488,941
15
2009-01-28T19:15:34Z
[ "python", "signal-processing", "average", "digital-filter" ]
I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this? I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place. So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates? ``` from datetime import date days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)] IQ = [110, 105, 90] ``` (there's probably a better way to structure the data, any advice would be appreciated)
EDIT: It seems that [`mov_average_expw()`](http://www.scipy.org/scipy/scikits/browser/trunk/timeseries/scikits/timeseries/lib/moving_funcs.py) function from [scikits.timeseries.lib.moving\_funcs](http://pytseries.sourceforge.net/lib/moving_funcs.html) submodule from [SciKits](http://scikits.appspot.com/) (add-on toolkits that complement [SciPy](http://scipy.org/)) better suits the wording of your question. --- To calculate an [exponential smoothing](http://en.wikipedia.org/wiki/Exponential_smoothing) of your data with a smoothing factor `alpha` (it is `(1 - alpha)` in Wikipedia's terms): ``` >>> alpha = 0.5 >>> assert 0 < alpha <= 1.0 >>> av = sum(alpha**n.days * iq ... for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq), ... sorted(zip(days, IQ), key=lambda p: p[0], reverse=True))) 95.0 ``` The above is not pretty, so let's refactor it a bit: ``` from collections import namedtuple from operator import itemgetter def smooth(iq_data, alpha=1, today=None): """Perform exponential smoothing with factor `alpha`. Time period is a day. Each time period the value of `iq` drops `alpha` times. The most recent data is the most valuable one. """ assert 0 < alpha <= 1 if alpha == 1: # no smoothing return sum(map(itemgetter(1), iq_data)) if today is None: today = max(map(itemgetter(0), iq_data)) return sum(alpha**((today - date).days) * iq for date, iq in iq_data) IQData = namedtuple("IQData", "date iq") if __name__ == "__main__": from datetime import date days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)] IQ = [110, 105, 90] iqdata = list(map(IQData, days, IQ)) print("\n".join(map(str, iqdata))) print(smooth(iqdata, alpha=0.5)) ``` Example: ``` $ python26 smooth.py IQData(date=datetime.date(2008, 1, 1), iq=110) IQData(date=datetime.date(2008, 1, 2), iq=105) IQData(date=datetime.date(2008, 1, 7), iq=90) 95.0 ```
Given an rpm package name, query the yum database for updates
489,113
5
2009-01-28T20:12:07Z
490,314
7
2009-01-29T02:36:40Z
[ "python", "rpm", "yum" ]
I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible? Is writing a wrapper for 'yum list package-name' the only way to do this?
<http://fpaste.org/paste/2453> and there are many examples of the yum api and some guides to getting started with it here: <http://yum.baseurl.org/#DeveloperDocumentationExamples>
Python super() raises TypeError
489,269
98
2009-01-28T20:47:10Z
489,278
121
2009-01-28T20:48:26Z
[ "python", "super" ]
In Python 2.5.2, the following code raises a TypeError: ``` >>> class X: ... def a(self): ... print "a" ... >>> class Y(X): ... def a(self): ... super(Y,self).a() ... print "b" ... >>> c = Y() >>> c.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in a TypeError: super() argument 1 must be type, not classobj ``` If I replace the `class X` with `class X(object)`, it will work. What's the explanation for this?
The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.
Python super() raises TypeError
489,269
98
2009-01-28T20:47:10Z
500,110
13
2009-02-01T03:23:05Z
[ "python", "super" ]
In Python 2.5.2, the following code raises a TypeError: ``` >>> class X: ... def a(self): ... print "a" ... >>> class Y(X): ... def a(self): ... super(Y,self).a() ... print "b" ... >>> c = Y() >>> c.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in a TypeError: super() argument 1 must be type, not classobj ``` If I replace the `class X` with `class X(object)`, it will work. What's the explanation for this?
In addition, don't use super() unless you have to. It's not the general-purpose "right thing" to do with new-style classes that you might suspect. There are times when you're expecting multiple inheritance and you might possibly want it, but until you know the hairy details of the MRO, best leave it alone and stick to: ``` X.a(self) ```
Why am I getting the following error in Python "ImportError: No module named py"?
489,497
11
2009-01-28T21:37:27Z
489,503
26
2009-01-28T21:39:36Z
[ "python" ]
I'm a Python newbie, so bear with me :) I created a file called test.py with the contents as follows: ``` test.py import sys print sys.platform print 2 ** 100 ``` I then ran `import test.py` file in the interpreter to follow an example in my book. When I do this, I get the output with the import error on the end. ``` win32 1267650600228229401496703205376 Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named py ``` Why do I get this error and how do I fix it? Thanks!
Instead of: ``` import test.py ``` simply write: ``` import test ``` This assumes test.py is in the same directory as the file that imports it.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,032
9
2009-01-29T00:24:06Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve. Your best bet is have a separate process that coordinates read/write access to that file.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,102
25
2009-01-29T01:01:50Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
There is a cross-platform file locking module here: [Portalocker](https://pypi.python.org/pypi/portalocker) Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible. If you can shoehorn your problem into a database, you could use SQLite. It supports concurrent access and handles its own locking.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
490,919
7
2009-01-29T08:46:38Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Locking is platform and device specific, but generally, you have a few options: 1. use flock(), or equivilent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored. 2. Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not copy - move is an atomic operation in Linux -- check your OS), and you check for the existence of the lock file. 3. Use a directory as a "lock". This is necessary if you're writing to NFS, since NFS doesn't support flock(). 4. There's also the possibility of using shared memory between the processes, but I've never tried that; its very os-specific. For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue. If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above). Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
498,505
65
2009-01-31T08:30:04Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
Alright, so I ended up going with the code I wrote [here, on my website](http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/) ([also available on GitHub](https://github.com/dmfrey/FileLock)). I can use it in the following fashion: ``` from filelock import FileLock with FileLock("myfile.txt"): # work with the file as it is now locked print("Lock acquired.") ```
Locking a file in Python
489,861
81
2009-01-28T23:20:03Z
3,343,885
15
2010-07-27T13:04:47Z
[ "python", "file-locking" ]
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
I prefer **[lockfile](https://github.com/smontanaro/pylockfile)** — Platform-independent file locking
Convert list of ints to one number?
489,999
29
2009-01-29T00:16:23Z
490,020
92
2009-01-29T00:21:26Z
[ "python" ]
I have a list of integers that I would like to convert to one number like: ``` numList = [1, 2, 3] num = magic(numList) print num, type(num) >>> 123, <type 'int'> ``` What is the best way to implement the *magic* function? **EDIT** I did find [this](http://bytes.com/groups/python/722951-int-str-list-elements), but it seems like there has to be a better way.
``` # Over-explaining a bit: def magic(numList): # [1,2,3] s = map(str, numList) # ['1','2','3'] s = ''.join(s) # '123' s = int(s) # 123 return s # How I'd probably write it: def magic(numList): s = ''.join(map(str, numList)) return int(s) # As a one-liner num = int(''.join(map(str,numList))) # Functionally: s = reduce(lambda x,y: x+str(y), numList, '') num = int(s) # Using some oft-forgotten built-ins: s = filter(str.isdigit, repr(numList)) num = int(s) ```
Convert list of ints to one number?
489,999
29
2009-01-29T00:16:23Z
490,031
31
2009-01-29T00:23:42Z
[ "python" ]
I have a list of integers that I would like to convert to one number like: ``` numList = [1, 2, 3] num = magic(numList) print num, type(num) >>> 123, <type 'int'> ``` What is the best way to implement the *magic* function? **EDIT** I did find [this](http://bytes.com/groups/python/722951-int-str-list-elements), but it seems like there has to be a better way.
Two solutions: ``` >>> nums = [1, 2, 3] >>> magic = lambda nums: int(''.join(str(i) for i in nums)) # Generator exp. >>> magic(nums) 123 >>> magic = lambda nums: sum(digit * 10 ** (len(nums) - 1 - i) # Summation ... for i, digit in enumerate(nums)) >>> magic(nums) 123 ``` The `map`-oriented solution actually comes out ahead on my box -- you definitely should not use `sum` for things that might be large numbers: ![Timeit Comparison](http://lh3.ggpht.com/_t58Xs7CN35o/SYETlAnN6NI/AAAAAAAABSg/KJetpOdJcKw/s400/image.png) ``` import collections import random import timeit import matplotlib.pyplot as pyplot MICROSECONDS_PER_SECOND = 1E6 FUNS = [] def test_fun(fun): FUNS.append(fun) return fun @test_fun def with_map(nums): return int(''.join(map(str, nums))) @test_fun def with_interpolation(nums): return int(''.join('%d' % num for num in nums)) @test_fun def with_genexp(nums): return int(''.join(str(num) for num in nums)) @test_fun def with_sum(nums): return sum(digit * 10 ** (len(nums) - 1 - i) for i, digit in enumerate(nums)) @test_fun def with_reduce(nums): return int(reduce(lambda x, y: x + str(y), nums, '')) @test_fun def with_builtins(nums): return int(filter(str.isdigit, repr(nums))) @test_fun def with_accumulator(nums): tot = 0 for num in nums: tot *= 10 tot += num return tot def time_test(digit_count, test_count=10000): """ :return: Map from func name to (normalized) microseconds per pass. """ print 'Digit count:', digit_count nums = [random.randrange(1, 10) for i in xrange(digit_count)] stmt = 'to_int(%r)' % nums result_by_method = {} for fun in FUNS: setup = 'from %s import %s as to_int' % (__name__, fun.func_name) t = timeit.Timer(stmt, setup) per_pass = t.timeit(number=test_count) / test_count per_pass *= MICROSECONDS_PER_SECOND print '%20s: %.2f usec/pass' % (fun.func_name, per_pass) result_by_method[fun.func_name] = per_pass return result_by_method if __name__ == '__main__': pass_times_by_method = collections.defaultdict(list) assert_results = [fun([1, 2, 3]) for fun in FUNS] assert all(result == 123 for result in assert_results) digit_counts = range(1, 100, 2) for digit_count in digit_counts: for method, result in time_test(digit_count).iteritems(): pass_times_by_method[method].append(result) for method, pass_times in pass_times_by_method.iteritems(): pyplot.plot(digit_counts, pass_times, label=method) pyplot.legend(loc='upper left') pyplot.xlabel('Number of Digits') pyplot.ylabel('Microseconds') pyplot.show() ```
split a multi-page pdf file into multiple pdf files with python?
490,195
20
2009-01-29T01:35:48Z
490,203
46
2009-01-29T01:38:47Z
[ "python", "pdf" ]
I'd like to take a multi-page pdf file and create separate pdf files per page. I've downloaded [reportlab](http://www.reportlab.org/index.html) and have browsed the documentation, but it seems aimed at pdf generation, I haven't yet seen anything about processing pdf's themselves. Is there an easy way to do this in python?
pyPdf can handle this nicely (c.f. <http://pybrary.net/pyPdf/> ) ``` from pyPdf import PdfFileWriter, PdfFileReader inputpdf = PdfFileReader(open("document.pdf", "rb")) for i in xrange(inputpdf.numPages): output = PdfFileWriter() output.addPage(inputpdf.getPage(i)) with open("document-page%s.pdf" % i, "wb") as outputStream: output.write(outputStream) ``` etc.
What is the most pythonic way to make a bound method act like a function?
490,429
3
2009-01-29T03:55:06Z
490,437
8
2009-01-29T03:58:53Z
[ "python", "function", "methods", "closures" ]
I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct 'self' argument, so I'm wondering how to turn a method into a function that knows what 'self' it belongs to. There are a couple of ways that I can think of to do this, including using a lambda and a closure. I've included some examples of this below, but I'm wondering if there is a standard mechanism for achieving the same effect. ``` class A(object): def hello(self, salutation): print('%s, my name is %s' % (salutation, str(self))) def bind_hello1(self): return lambda x: self.hello(x) def bind_hello2(self): def hello2(*args): self.hello(*args) return hello2 >>> a1, a2 = A(), A() >>> a1.hello('Greetings'); a2.hello('Greetings') Greetings, my name is <__main__.A object at 0x71570> Greetings, my name is <__main__.A object at 0x71590> >>> f1, f2 = a1.bind_hello1(), a2.bind_hello1() >>> f1('Salutations'); f2('Salutations') Salutations, my name is <__main__.A object at 0x71570> Salutations, my name is <__main__.A object at 0x71590> >>> f1, f2 = a1.bind_hello2(), a2.bind_hello2() >>> f1('Aloha'); f2('Aloha') Aloha, my name is <__main__.A object at 0x71570> Aloha, my name is <__main__.A object at 0x71590> ```
Will passing in the method bound to a instance work? If so, you don't have to do anything special. ``` In [2]: class C(object): ...: def method(self, a, b, c): ...: print a, b, c ...: ...: In [3]: def api_function(a_func): ...: a_func("One Fish", "Two Fish", "Blue Fish") ...: ...: In [4]: c = C() In [5]: api_function(c.method) One Fish Two Fish Blue Fish ```
django-cart or Satchmo?
490,439
23
2009-01-29T04:00:49Z
490,534
26
2009-01-29T05:04:35Z
[ "python", "django", "e-commerce", "satchmo" ]
I'm looking to implement a very basic shopping cart. [Satchmo](http://www.satchmoproject.com/) seems to install a **lot** of applications and extra stuff that I don't need. I've heard others mention [django-cart](http://code.google.com/p/django-cart/). Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?
Well if you want to use django-cart you should view it as a starting point for developing your own. The last commit (r4) for the project was November 2006. By comparison, the last commit (r1922) to Satchmo was a couple of hours ago. With Satchmo you get code that is under active development and actually used by real e-commerce sites. If you develop your own you're running the risk of alienating customers and losing money. If you use Satchmo you can spend more time developing/improving other areas of your site. I bet you can already guess my recommendation :) As for the apps and other stuff in Satchmo I can tell you, from personal experience, that you don't need to include them all in your INSTALLED\_APPS setting. I don't remember exactly what I pared it down to, but there were only around 6-7 Satchmo apps in my INSTALLED\_APPS and they were all ones I needed. I think they've done even more modularization since then.
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
490,609
18
2009-01-29T05:51:21Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
Look in the Python [re documentation](http://docs.python.org/library/re.html) for lookaheads `(?=...)` and lookbehinds `(?<=...)` -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
490,616
105
2009-01-29T05:56:21Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
``` >>> import re >>> s = "start foo end" >>> s = re.sub("foo", "replaced", s) >>> s 'start replaced end' >>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s) >>> s 'start can use a callable for the replaced text too end' >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used. ```
Regex replace (in Python) - a simpler way?
490,597
42
2009-01-29T05:43:24Z
491,966
11
2009-01-29T15:11:48Z
[ "python", "regex" ]
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: ``` "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" ``` And then concatenate the `start` group with the new data for `replace` and then the `end` group. Is there a better method for this?
The short version is that you *cannot use* variable-width patterns in lookbehinds using Python's `re` module. There is no way to change this: ``` >>> import re >>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz") 'fooquuxbaz' >>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz") Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> re.sub("(?<=fo+)bar(?=baz)", "quux", string) File "C:\Development\Python25\lib\re.py", line 150, in sub return _compile(pattern, 0).sub(repl, string, count) File "C:\Development\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression error: look-behind requires fixed-width pattern ``` This means that you'll need to work around it, the simplest solution being very similar to what you're doing now: ``` >>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz") 'fooquuxbaz' >>> >>> # If you need to turn this into a callable function: >>> def replace(start, replace, end, replacement, search): return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search) ``` This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what [an expert has to say on the matter](http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript) (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.
No code completion and syntax highlighting in Pydev
491,053
12
2009-01-29T09:50:56Z
492,073
21
2009-01-29T15:32:20Z
[ "python", "ide" ]
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it? Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please. If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion
To enable code completion, go to Window > Preferences > Pydev > Editor > Code Completion, and check the 'Use Code Completion?' box, as well as the other boxes for what you want to complete on. It seems to take a second to load, the first time it has to complete something. Syntax coloring should just work by default. Right-click on the file in the package explorer, go to 'Open With', and make sure you're opening it with the Python Editor, and not the regular Text Editor. I don't know exactly what you mean by importing external modules. I have my source in a separate directory structure on disk; my PyDev projects contain folders linked to those. Code completion works for that, as well as other modules like 'os'. If you're having troubles, are the modules added to the PyDev's Python search path (not necessarily the same as the regular one)? I took a brief look at Komodo and Wingware a while back, so I can't answer the second part of your question. But ended up going with PyDev. I'm not a big fan of Eclipse, but PyDev works reasonably well for me.
No code completion and syntax highlighting in Pydev
491,053
12
2009-01-29T09:50:56Z
1,836,524
8
2009-12-02T23:07:53Z
[ "python", "ide" ]
I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it? Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please. If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion
The typical reason that code completion doesn't work under PyDev is that the libraries aren't in the PYTHONPATH. If you go into the Project Properties, and setup PyDev PYTHONPATH preferences to include the places where the code you are trying to complete lives, it will work just fine... Project > Properties > PyDev-PYTHONPAH > click 'Add source folder'
How can I pass a filename as a parameter into my module?
491,085
5
2009-01-29T10:04:13Z
491,189
14
2009-01-29T10:50:05Z
[ "python", "command-line", "parameters", "module" ]
I have the following code in .py file: ``` import re regex = re.compile( r"""ULLAT:\ (?P<ullat>-?[\d.]+).*? ULLON:\ (?P<ullon>-?[\d.]+).*? LRLAT:\ (?P<lrlat>-?[\d.]+)""", re.DOTALL|re.VERBOSE) ``` I have the data in .txt file as a sequence: ``` QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 ULLON: -97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5 QUADDATE: 20001001 ``` How can I use the Python -file to process the .txt -file? I guess that we need a parameter in the .py file, so that we can use a syntax like in terminal: ``` $ py-file file-to-be-processed ``` This question was raised by the post [here](http://stackoverflow.com/questions/489901/how-can-i-extract-x-y-and-z-coordinates-from-geographical-data-by-python/490347#490347).
You need to read the file in and then search the contents using the regular expression. The sys module contains a list, argv, which contains all the command line parameters. We pull out the second one (the first is the file name used to run the script), open the file, and then read in the contents. ``` import re import sys file_name = sys.argv[1] fp = open(file_name) contents = fp.read() regex = re.compile( r"""ULLAT:\ (?P-?[\d.]+).*? ULLON:\ (?P-?[\d.]+).*? LRLAT:\ (?P-?[\d.]+)""", re.DOTALL|re.VERBOSE) match = regex.search(contents) ``` See the [Python regular expression documentation](http://docs.python.org/library/re.html#id1) for details on what you can do with the match object. See [this part of the documentation](http://docs.python.org/library/re.html#search-vs-match) for why we need search rather than match when scanning the file. This code will allow you to use the syntax you specified in your question.
Python: Problem with local modules shadowing global modules
491,705
9
2009-01-29T14:04:51Z
491,813
8
2009-01-29T14:33:14Z
[ "python" ]
I've got a package set up like so: ``` packagename/ __init__.py numbers.py tools.py ...other stuff ``` Now inside `tools.py`, I'm trying to import the standard library module `fractions`. However, the `fractions` module itself imports the `numbers` module, which is supposed to be the one in the standard library. The problem is that it tries to import the `numbers` modules from *my* package instead (ie my `numbers.py` is shadowing the stdlib `numbers` module), and then complains about it, instead of importing the stdlib module. My question is, is there a workaround so that I can keep the current structure of my package, or is the only solution to rename my own offending module (`numbers.py`)?
[absolute and relative imports](http://www.python.org/dev/peps/pep-0328/) can be used since python2.5 (with `__future__` import) and seem to be what you're looking for.
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
491,967
69
2009-01-29T15:11:59Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').read() 'Capit\xc3\xa1n\n' ``` So I type in `Capit\xc3\xa1n` into my favorite editor, in file f2. then: ``` >>> open('f1').read() 'Capit\xc3\xa1n\n' >>> open('f2').read() 'Capit\\xc3\\xa1n\n' >>> open('f1').read().decode('utf8') u'Capit\xe1n\n' >>> open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' ``` What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions. **Edit**: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it? ``` >>> print simplejson.dumps(ss) '"Capit\u00e1n"' >>> print >> file('f3','w'), simplejson.dumps(ss) >>> simplejson.load(open('f3')) u'Capit\xe1n' ```
In the notation ``` u'Capit\xe1n\n' ``` the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write ``` Capit\xc3\xa1n ``` into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them: ``` >>> open('f2').read() 'Capit\\xc3\\xa1n\n' ``` You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3". Edit: As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it. If you actually have a string in this format you can use the `string_escape` codec to decode it into a normal string: ``` In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape') Capitán ``` The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written `\\xc3\\xa1` in the original string. If you want to have a unicode string you have to decode again with UTF-8. To your edit: you don't have UTF-8 in your file. To actually see how it would look like: ``` s = u'Capit\xe1n\n' sutf8 = s.encode('UTF-8') open('utf-8.out', 'w').write(sutf8) ``` Compare the content of the file `utf-8.out` to the content of the file you saved with your editor.
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
493,152
12
2009-01-29T20:01:27Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').read() 'Capit\xc3\xa1n\n' ``` So I type in `Capit\xc3\xa1n` into my favorite editor, in file f2. then: ``` >>> open('f1').read() 'Capit\xc3\xa1n\n' >>> open('f2').read() 'Capit\\xc3\\xa1n\n' >>> open('f1').read().decode('utf8') u'Capit\xe1n\n' >>> open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' ``` What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions. **Edit**: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it? ``` >>> print simplejson.dumps(ss) '"Capit\u00e1n"' >>> print >> file('f3','w'), simplejson.dumps(ss) >>> simplejson.load(open('f3')) u'Capit\xe1n' ```
So, I've found a solution for what I'm looking for, which is: ``` print open('f2').read().decode('string-escape').decode("utf-8") ``` There are some unusual codecs that are useful here. This particular reading allows one to take utf-8 representations from within python, copy them into an ascii file, and have them be read in to unicode. Under the "string-escape" decode, the slashes won't be doubled. This allows for the sort of round trip that I was imagining.
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
844,443
468
2009-05-10T00:45:58Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').read() 'Capit\xc3\xa1n\n' ``` So I type in `Capit\xc3\xa1n` into my favorite editor, in file f2. then: ``` >>> open('f1').read() 'Capit\xc3\xa1n\n' >>> open('f2').read() 'Capit\\xc3\\xa1n\n' >>> open('f1').read().decode('utf8') u'Capit\xe1n\n' >>> open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' ``` What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions. **Edit**: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it? ``` >>> print simplejson.dumps(ss) '"Capit\u00e1n"' >>> print >> file('f3','w'), simplejson.dumps(ss) >>> simplejson.load(open('f3')) u'Capit\xe1n' ```
Rather than mess with the encode, decode methods I find it easier to use the open method from the codecs module. ``` >>>import codecs >>>f = codecs.open("test", "r", "utf-8") ``` Then after calling f's read() function, an encoded unicode object is returned. ``` >>>f.read() u'Capit\xe1l\n\n' ``` If you know the encoding of a file, using the codecs package is going to be much less confusing. See <http://docs.python.org/library/codecs.html#codecs.open>
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
9,200,843
12
2012-02-08T20:24:46Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').read() 'Capit\xc3\xa1n\n' ``` So I type in `Capit\xc3\xa1n` into my favorite editor, in file f2. then: ``` >>> open('f1').read() 'Capit\xc3\xa1n\n' >>> open('f2').read() 'Capit\\xc3\\xa1n\n' >>> open('f1').read().decode('utf8') u'Capit\xe1n\n' >>> open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' ``` What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions. **Edit**: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it? ``` >>> print simplejson.dumps(ss) '"Capit\u00e1n"' >>> print >> file('f3','w'), simplejson.dumps(ss) >>> simplejson.load(open('f3')) u'Capit\xe1n' ```
``` # -*- encoding: utf-8 -*- # converting a unknown formatting file in utf-8 import codecs import commands file_location = "jumper.sub" file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location) file_stream = codecs.open(file_location, 'r', file_encoding) file_output = codecs.open(file_location+"b", 'w', 'utf-8') for l in file_stream: file_output.write(l) file_stream.close() file_output.close() ```
Unicode (utf8) reading and writing to files in python
491,921
189
2009-01-29T15:01:15Z
25,378,530
11
2014-08-19T08:09:28Z
[ "python", "unicode", "utf-8", "io" ]
I'm having some brain failure in understanding reading and writing text to a file (Python 2.4). ``` # the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) ``` > ("u'Capit\xe1n'", "'Capit\xc3\xa1n'") ``` print ss, ss8 print >> open('f1','w'), ss8 >>> file('f1').read() 'Capit\xc3\xa1n\n' ``` So I type in `Capit\xc3\xa1n` into my favorite editor, in file f2. then: ``` >>> open('f1').read() 'Capit\xc3\xa1n\n' >>> open('f2').read() 'Capit\\xc3\\xa1n\n' >>> open('f1').read().decode('utf8') u'Capit\xe1n\n' >>> open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' ``` What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions. **Edit**: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it? ``` >>> print simplejson.dumps(ss) '"Capit\u00e1n"' >>> print >> file('f3','w'), simplejson.dumps(ss) >>> simplejson.load(open('f3')) u'Capit\xe1n' ```
Actually this is worked for me for reading a file with utf-8 encodeing in Py 3.2 ``` import codecs f = codecs.open('file_name.txt', 'r', 'UTF-8') for line in f: print(line) ```
How do I use ctypes to set a library's extern function pointer to a Python callback function?
492,377
3
2009-01-29T16:31:41Z
492,640
9
2009-01-29T17:39:14Z
[ "python", "ctypes" ]
Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback. In this example library `liblibrary.so`, how do I set library\_hook to a Python function using ctypes? library.h: ``` typedef int exported_function_t(char**, int); extern exported_function_t *library_hook; ```
This is tricky in ctypes because ctypes function pointers do not implement the `.value` property used to set other pointers. Instead, cast your callback function and the extern function pointer to `void *` with the `c_void_p` function. After setting the function pointer as `void *` as shown, C can call your Python function, and you can retrieve the function as a function pointer and call it with normal ctypes calls. ``` from ctypes import * liblibrary = cdll.LoadLibrary('liblibrary.so') def py_library_hook(strings, n): return 0 # First argument to CFUNCTYPE is the return type: LIBRARY_HOOK_FUNC = CFUNCTYPE(c_int, POINTER(c_char_p), c_int) hook = LIBRARY_HOOK_FUNC(py_library_Hook) ptr = c_void_p.in_dll(liblibrary, 'library_hook') ptr.value = cast(hook, c_void_p).value ```
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,399
282
2009-01-29T16:37:18Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
EDIT: Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search&replace to replace all tabs with a few spaces. Try this: ``` import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",result return result print Factorial(10) ```
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,419
26
2009-01-29T16:41:15Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.) Note, it is recommended that you don't use tabs in Python code. See the [style guide](http://www.python.org/dev/peps/pep-0008/). You should configure Notepad++ to insert spaces for tabs.
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
492,437
12
2009-01-29T16:45:19Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
Whenever I've encountered this error, it's because I've somehow mixed up tabs and spaces in my editor.
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
513,524
97
2009-02-04T21:50:28Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
To easily check for problems with tabs/spaces you can actually do this: ``` python -m tabnanny yourfile.py ``` or you can just set up your editor correctly of course :-)
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
17,091,012
7
2013-06-13T15:26:00Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
If you use Python's IDLE editor you can do as it suggests in one of similar error messages: 1) select all, e.g. Ctrl + A 2) Go to Format -> Untabify Region 3) Double check your indenting is still correct, save and rerun your program. I'm using Python 2.5.4
IndentationError: unindent does not match any outer indentation level
492,387
243
2009-01-29T16:34:46Z
23,540,812
86
2014-05-08T11:44:49Z
[ "python", "indentation" ]
When I compile the Python code below, I get > IndentationError: unindent does not match any outer indentation level --- ``` import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result ``` Why?
**IMPORTANT**: ***Spaces are the preferred method*** - see PEP008 [Indentation](https://www.python.org/dev/peps/pep-0008/#indentation) and [Tabs or Spaces?](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces). (Thanks to @Siha for this.) For `Sublime Text` users: Set `Sublime Text` to use tabs for indentation: `View` --> `Indentation` --> `Convert Indentation to Tabs` Uncheck the `Indent Using Spaces` option as well in the same sub-menu above. This will immediately resolve this issue.
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
492,711
120
2009-01-29T18:03:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: ``` # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" ``` Is there a better way to make piping work?
Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself. A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. ``` # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') ``` Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between. ``` import sys for line in sys.stdin: # Decode what you receive: line = line.decode('iso8859-1') # Work with Unicode internally: line = line.upper() # Encode what you send: line = line.encode('utf-8') sys.stdout.write(line) ``` Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
1,169,209
129
2009-07-23T02:05:58Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: ``` # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" ``` Is there a better way to make piping work?
First, regarding this solution: ``` # -*- coding: utf-8 -*- print u"åäö".encode('utf-8') ``` It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone. A better solution is to change **`sys.stdout`** at the start of your program, to encode with a selected encoding. Here is one solution I found on [Python: How is sys.stdout.encoding chosen?](http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/), in particular a comment by "toka": ``` import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) ```
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
4,027,726
81
2010-10-26T20:30:35Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: ``` # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" ``` Is there a better way to make piping work?
You may want to try changing the environment variable "PYTHONIOENCODING" to "utf\_8." I have written a [page on my ordeal with this problem](http://daveagp.wordpress.com/2010/10/26/what-a-character/). Tl;dr of the blog post: ``` import sys, locale, os print(sys.stdout.encoding) print(sys.stdout.isatty()) print(locale.getpreferredencoding()) print(sys.getfilesystemencoding()) print(os.environ["PYTHONIOENCODING"]) print(chr(246), chr(9786), chr(9787)) ``` gives you ``` utf_8 False ANSI_X3.4-1968 ascii utf_8 ö ☺ ☻ ```
Setting the correct encoding when piping stdout in Python
492,483
224
2009-01-29T16:57:59Z
6,362,647
38
2011-06-15T18:40:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this: ``` # -*- coding: utf-8 -*- print u"åäö" ``` will work fine when run normally, but fail with: > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128) when used in a pipe sequence. What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack: ``` # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" ``` Is there a better way to make piping work?
``` export PYTHONIOENCODING=utf-8 ``` do the job, but can't set it on python itself ... what we can do is verify if isn't setting and tell the user to set it before call script with : ``` if __name__ == '__main__': if (sys.stdout.encoding is None): print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." exit(1) ```
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
494,273
92
2009-01-30T02:14:04Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
You may use the [signal](http://docs.python.org/library/signal.html) package if you are running on UNIX: ``` In [1]: import signal # Register an handler for the timeout In [2]: def handler(signum, frame): ...: print "Forever is over!" ...: raise Exception("end of time") ...: # This function *may* run for an indetermined time... In [3]: def loop_forever(): ...: import time ...: while 1: ...: print "sec" ...: time.sleep(1) ...: ...: # Register the signal function handler In [4]: signal.signal(signal.SIGALRM, handler) Out[4]: 0 # Define a timeout for your function In [5]: signal.alarm(10) Out[5]: 0 In [6]: try: ...: loop_forever() ...: except Exception, exc: ...: print exc ....: sec sec sec sec sec sec sec sec Forever is over! end of time # Cancel the timer if the function returned before timeout # (ok, mine won't but yours maybe will :) In [7]: signal.alarm(0) Out[7]: 0 ``` 10 seconds after the call `alarm.alarm(10)`, the handler is called. This raises an exception that you can intercept from the regular Python code. This module doesn't play well with threads (but then, who does?) **Note that** since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function: ``` def loop_forever(): while 1: print 'sec' try: time.sleep(10) except: continue ```
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
13,821,695
26
2012-12-11T13:41:31Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread) ``` def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler) signal.alarm(timeout_duration) try: result = func(*args, **kwargs) except TimeoutError as exc: result = default finally: signal.alarm(0) return result ```
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
14,924,210
58
2013-02-17T18:00:10Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
You can use `multiprocessing.Process` to do exactly that. **Code** ``` import multiprocessing import time # bar def bar(): for i in range(100): print "Tick" time.sleep(1) if __name__ == '__main__': # Start bar as a process p = multiprocessing.Process(target=bar) p.start() # Wait for 10 seconds or until process finishes p.join(10) # If thread is still active if p.is_alive(): print "running... let's kill it..." # Terminate p.terminate() p.join() ```
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
31,667,005
10
2015-07-28T03:43:52Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
> # How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it? I posted a [gist](https://gist.github.com/aaronchall/6331661fe0185c30a0b4) that solves this question/problem with a decorator and a `threading.Timer`. Here it is with a breakdown. ## Imports and setups for compatibility It was tested with Python 2 and 3. It should also work under Unix/Linux and Windows. First the imports. These attempt to keep the code consistent regardless of the Python version: ``` from __future__ import print_function import sys import threading from time import sleep try: import thread except ImportError: import _thread as thread ``` Use version independent code: ``` try: range, _print = xrange, print def print(*args, **kwargs): flush = kwargs.pop('flush', False) _print(*args, **kwargs) if flush: kwargs.get('file', sys.stdout).flush() except NameError: pass ``` Now we have imported our functionality from the standard library. ## `exit_after` decorator Next we need a function to terminate the `main()` from the child thread: ``` def cdquit(fn_name): # print to stderr, unbuffered in Python 2. print('{0} took too long'.format(fn_name), file=sys.stderr) sys.stderr.flush() # Python 3 stderr is likely buffered. thread.interrupt_main() # raises KeyboardInterrupt ``` And here is the decorator itself: ``` def exit_after(s): ''' use as decorator to exit process if function takes longer than s seconds ''' def outer(fn): def inner(*args, **kwargs): timer = threading.Timer(s, cdquit, args=[fn.__name__]) timer.start() try: result = fn(*args, **kwargs) finally: timer.cancel() return result return inner return outer ``` ## Usage And here's the usage, modified from my gist, that directly answers your question about exiting after 5 seconds!: ``` @exit_after(5) def countdown(n): print('countdown started', flush=True) for i in range(n, -1, -1): print(i, end=', ', flush=True) sleep(1) print('countdown finished') ``` Demo: ``` >>> countdown(3) countdown started 3, 2, 1, 0, countdown finished >>> countdown(10) countdown started 10, 9, 8, 7, 6, countdown took too long Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 11, in inner File "<stdin>", line 6, in countdown KeyboardInterrupt ``` The second function call will not finish, instead the process should exit with a traceback! ## `KeyboardInterrupt` does not always stop a sleeping thread Note that sleep will not always be interrupted by a keyboard interrupt, on Python 2 on Windows, e.g.: ``` @exit_after(1) def sleep10(): sleep(10) print('slept 10 seconds') >>> sleep10() sleep10 took too long # Note that it hangs here about 9 more seconds Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 11, in inner File "<stdin>", line 3, in sleep10 KeyboardInterrupt ``` nor is it likely to interrupt code running in extensions unless it explicitly checks for `PyErr_CheckSignals()`, see [Cython, Python and KeyboardInterrupt ignored](http://stackoverflow.com/q/16769870/541136) > How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it **and does something else?** To catch it and do something else, you can catch the KeyboardInterrupt. ``` >>> try: ... countdown(10) ... except KeyboardInterrupt: ... print('do something else') ... countdown started 10, 9, 8, 7, 6, countdown took too long do something else ``` Credits: * [Morgan Thrapp](http://stackoverflow.com/users/3059812) for testing * [Sherlock85](http://stackoverflow.com/users/922130) for finding a bug * [J.F.Sebastian](http://stackoverflow.com/users/4279) for pointing out that, depending on platform and version, sleep isn't interrupted by `KeyboardInterrupt`.
Timeout on a function call
492,519
95
2009-01-29T17:08:29Z
35,139,284
14
2016-02-01T20:02:32Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
I'm calling a function in Python which I know may stall and force me to restart the script. How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?
I ran across this thread when searching for a timeout call on unit tests. I didn't find anything simple in the answers or 3rd party packages so I wrote the decorator below you can drop right into code: ``` import multiprocessing.pool import functools def timeout(max_timeout): """Timeout decorator, parameter in seconds.""" def timeout_decorator(item): """Wrap the original function.""" @functools.wraps(item) def func_wrapper(*args, **kwargs): """Closure for function.""" pool = multiprocessing.pool.ThreadPool(processes=1) async_result = pool.apply_async(item, args, kwargs) # raises a TimeoutError if execution exceeds max_timeout return async_result.get(max_timeout) return func_wrapper return timeout_decorator ``` Then it's as simple as this to timeout a test or any function you like: ``` @timeout(5.0) # if execution takes longer than 5 seconds, raise a TimeoutError def test_base_regression(self): ... ```
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
496,603
10
2009-01-30T18:27:24Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm using Python, so I'd like a Python library. To reiterate, I only want *one* string that will match the regex. Things like "." or ".\*" would make an infinite amount of strings match the regex, but I don't care about all options. I'm willing for this library to only work on a certain subset of regex.
I don't know of any module to do this. If you don't find anything like this in the Cookbook or PyPI, you could try rolling your own, using the (undocumented) re.sre\_parse module. This might help getting you started: ``` In [1]: import re In [2]: a = re.sre_parse.parse("[abc]+[def]*\d?z") In [3]: a Out[3]: [('max_repeat', (1, 65535, [('in', [('literal', 97), ('literal', 98), ('literal', 99)])])), ('max_repeat', (0, 65535, [('in', [('literal', 100), ('literal', 101), ('literal', 102)])])), ('max_repeat', (0, 1, [('in', [('category', 'category_digit')])])), ('literal', 122)] In [4]: eval(str(a)) Out[4]: [('max_repeat', (1, 65535, [('in', [('literal', 97), ('literal', 98), ('literal', 99)])])), ('max_repeat', (0, 65535, [('in', [('literal', 100), ('literal', 101), ('literal', 102)])])), ('max_repeat', (0, 1, [('in', [('category', 'category_digit')])])), ('literal', 122)] In [5]: a.dump() max_repeat 1 65535 in literal 97 literal 98 literal 99 max_repeat 0 65535 in literal 100 literal 101 literal 102 max_repeat 0 1 in category category_digit literal 122 ```
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
502,074
15
2009-02-02T02:59:15Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm using Python, so I'd like a Python library. To reiterate, I only want *one* string that will match the regex. Things like "." or ".\*" would make an infinite amount of strings match the regex, but I don't care about all options. I'm willing for this library to only work on a certain subset of regex.
Although I don't see much sense in this, here goes: ``` import re import string def traverse(tree): retval = '' for node in tree: if node[0] == 'any': retval += 'x' elif node[0] == 'at': pass elif node[0] in ['min_repeat', 'max_repeat']: retval += traverse(node[1][2]) * node[1][0] elif node[0] == 'in': if node[1][0][0] == 'negate': letters = list(string.ascii_letters) for part in node[1][1:]: if part[0] == 'literal': letters.remove(chr(part[1])) else: for letter in range(part[1][0], part[1][1]+1): letters.remove(chr(letter)) retval += letters[0] else: if node[1][0][0] == 'range': retval += chr(node[1][0][1][0]) else: retval += chr(node[1][0][1]) elif node[0] == 'not_literal': if node[1] == 120: retval += 'y' else: retval += 'x' elif node[0] == 'branch': retval += traverse(node[1][1][0]) elif node[0] == 'subpattern': retval += traverse(node[1][1]) elif node[0] == 'literal': retval += chr(node[1]) return retval print traverse(re.sre_parse.parse(regex).data) ``` I took everything from the [Regular Expression Syntax](http://docs.python.org/library/re.html#regular-expression-syntax) up to groups -- this seems like a reasonable subset -- and I ignored some details, like line endings. Error handling, etc. is left as an exercise to the reader. Of the 12 special characters in a regex, we can ignore 6 completely (2 even with the atom they apply to), 4.5 lead to a trivial replacement and 1.5 make us actually think. What comes out of this is not too terribly interesting, I think.
Reversing a regular expression in Python
492,716
33
2009-01-29T18:05:22Z
9,118,086
16
2012-02-02T18:45:41Z
[ "python", "regex" ]
I want to reverse a regular expression. I.e. given a regular expression, I want to produce *any* string that will match that regex. I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :) I'm using Python, so I'd like a Python library. To reiterate, I only want *one* string that will match the regex. Things like "." or ".\*" would make an infinite amount of strings match the regex, but I don't care about all options. I'm willing for this library to only work on a certain subset of regex.
Somebody else had a similar (duplicate?) question [here](http://stackoverflow.com/questions/4627464/generate-a-string-that-matches-a-regex-in-python), and I'd like to offer a little helper library for [generating random strings with Python](https://bitbucket.org/leapfrogdevelopment/rstr/) that I've been working on. It includes a method, `xeger()` that allows you to create a string from a regex: ``` >>> import rstr >>> rstr.xeger(r'[A-Z]\d[A-Z] \d[A-Z]\d') u'M5R 2W4' ``` Right now, it works with most basic regular expressions, but I'm sure it could be improved.
python: restarting a loop
492,860
9
2009-01-29T18:37:51Z
492,864
9
2009-01-29T18:38:57Z
[ "python", "loops" ]
i have: ``` for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop ``` But that doesn't seem to work. Is there a way to restart that loop? Thanks
Changing the index variable `i` from within the loop is unlikely to do what you expect. You may need to use a `while` loop instead, and control the incrementing of the loop variable yourself. Each time around the `for` loop, `i` is reassigned with the next value from `range()`. So something like: ``` i = 2 while i < n: if(something): do something else: do something else i = 2 # restart the loop continue i += 1 ``` In my example, the [`continue`](http://python.org/doc/2.5/ref/continue.html) statement jumps back up to the top of the loop, skipping the `i += 1` statement for that iteration. Otherwise, `i` is incremented as you would expect (same as the `for` loop).
python: restarting a loop
492,860
9
2009-01-29T18:37:51Z
492,877
17
2009-01-29T18:42:22Z
[ "python", "loops" ]
i have: ``` for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop ``` But that doesn't seem to work. Is there a way to restart that loop? Thanks
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer. perhaps a: ``` i=2 while i < n: if something: do something i += 1 else: do something else i = 2 #restart the loop ```
I don't understand slicing with negative bounds in Python. How is this supposed to work?
493,046
6
2009-01-29T19:31:48Z
493,057
18
2009-01-29T19:34:38Z
[ "python", "slice" ]
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter: ``` >>> s = 'spam' >>> s[:-1] 'spa' ``` Why does slicing with no beginning bound and a `'-1'` return every element except the last one? Is calling `s[0:-1]` logically the same as calling `s[:-1]`? They both return the same result. But I'm not sure what python is doing exactly. Any help would be greatly appreciated.
Yes, calling `s[0:-1]` is exactly the same as calling `s[:-1]`. Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side). so if you have a list as so: ``` myList = ['a', 'b', 'c', 'd', 'e'] print myList[-1] # prints 'e' ``` the print statement will print "e". Once you understand that (which you may already, it's not entirely clear if that's one of the things you're confused about or not) we can start talking about slicing. I'm going to assume you understand the basics of a slice along the lines of `myList[2:4]` (which will return `['c', 'd']`) and jump straight into the slicing notation where one side is left blank. As you suspected in your post, `myList[:index]` is exactly the same as `myList[0:index]`. This is also works the other way around, by the way... `myList[index:]` is the same as `myList[index:len(myList)]` and will return a list of all the elements from the list starting at `index` and going till the end (e.g. `print myList[2:]` will print `['c', 'd', 'e']`). As a third note, you can even do `print myList[:]` where *no* index is indicated, which will basically return a copy of the entire list (equivalent to `myList[0:len(myList)]`, returns ['a', 'b', 'c', 'd', 'e']). This might be useful if you think myList is going to change at some point but you want to keep a copy of it in its current state. If you're not already doing it I find just messing around in a Python interpreter a whole bunch a big help towards understanding these things. I recommend [IPython](http://ipython.scipy.org/moin/).
Is there a way to convert number words to Integers?
493,174
24
2009-01-29T20:07:43Z
493,788
56
2009-01-29T22:32:54Z
[ "python", "string", "text", "integer", "numbers" ]
I need to convert `one` into `1`, `two` into `2` and so on. Is there a way to do this with a library or a class or anything?
The majority of this code is to set up the numwords dict, which is only done on the first call. ``` def text2int(textnum, numwords={}): if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] scales = ["hundred", "thousand", "million", "billion", "trillion"] numwords["and"] = (1, 0) for idx, word in enumerate(units): numwords[word] = (1, idx) for idx, word in enumerate(tens): numwords[word] = (1, idx * 10) for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0) current = result = 0 for word in textnum.split(): if word not in numwords: raise Exception("Illegal word: " + word) scale, increment = numwords[word] current = current * scale + increment if scale > 100: result += current current = 0 return result + current print text2int("seven billion one hundred million thirty one thousand three hundred thirty seven") #7100031337 ```
In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
493,304
15
2009-01-29T20:38:21Z
493,454
9
2009-01-29T21:13:53Z
[ "python", "django", "manytomanyfield" ]
Given a situation in Django 1.0 where you have [extra data on a Many-to-Many relationship](http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany): ``` class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = models.CharField(max_length=40) players = models.ManyToManyField(Player, through='TeamPlayer', related_name='teams') class TeamPlayer(models.Model): player = models.ForeignKey(Player) team = models.ForeignKey(Team) captain = models.BooleanField() ``` The many-to-many relationship allows you to access the related data using attributes (the "players" attribute on the Team object or using the "teams" attribute on the Player object by way of its related name). When one of the objects is placed into a context for a template (e.g. a Team placed into a Context for rendering a template that generates the Team's roster), the related objects can be accessed (i.e. the players on the teams), but how can the extra data (e.g. 'captain') be accessed along with the related objects from the object in context (e.g.the Team) without adding additional data into the context? I know it is possible to query directly against the intermediary table to get the extra data. For example: ``` TeamPlayer.objects.get(player=790, team=168).captain ``` Or: ``` for x in TeamPlayer.objects.filter(team=168): if x.captain: print "%s (Captain)" % (x.player.name) else: print x.player.name ``` Doing this directly on the intermediary table, however requires me to place additional data in a template's context (the result of the query on TeamPlayer) which I am trying to avoid if such a thing is possible.
So, 15 minutes after asking the question, and I found my own answer. Using `dir(Team)`, I can see another generated attribute named `teamplayer_set` (it also exists on Player). ``` t = Team.objects.get(pk=168) for x in t.teamplayer_set.all(): if x.captain: print "%s (Captain)" % (x.player.name) else: print x.player.name ``` Not sure how I would customize that generated related\_name, but at least I know I can get to the data from the template without adding additional query results into the context.
Python: For each list element apply a function across the list
493,367
23
2009-01-29T20:53:15Z
493,423
40
2009-01-29T21:07:47Z
[ "python", "algorithm", "list", "list-comprehension" ]
Given `[1,2,3,4,5]`, how can I do something like ``` 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 ``` I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return `(1,5)`. So basically I would like to do something like for each element `i` in the list map some function across all elements in the list, taking `i` and `j` as parameters store the result in a master list, find the minimum value in the master list, and return the arguments `i`, `j`used to calculate this minimum value. In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.
You can do this using [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and [min()](http://docs.python.org/library/functions.html) (Python 3.0 code): ``` >>> nums = [1,2,3,4,5] >>> [(x,y) for x in nums for y in nums] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)] >>> min(_, key=lambda pair: pair[0]/pair[1]) (1, 5) ``` Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do `from __future__ import division` so that 1/5 correctly equals 0.2 instead of 0.
Python: For each list element apply a function across the list
493,367
23
2009-01-29T20:53:15Z
493,473
9
2009-01-29T21:17:20Z
[ "python", "algorithm", "list", "list-comprehension" ]
Given `[1,2,3,4,5]`, how can I do something like ``` 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 ``` I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return `(1,5)`. So basically I would like to do something like for each element `i` in the list map some function across all elements in the list, taking `i` and `j` as parameters store the result in a master list, find the minimum value in the master list, and return the arguments `i`, `j`used to calculate this minimum value. In my real problem I have a list objects/coordinates, and the function I am using takes two coordinates and calculates the euclidean distance. I'm trying to find minimum euclidean distance between any two points but I don't need a fancy algorithm.
If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list... ``` l = [1,2,3,4,5] def f(i,j): return i+j # Prints min value of f(i,j) along with i and j print min( (f(i,j),i,j) for i in l for j in l) ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,399
1,118
2009-01-29T21:01:43Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
## General way ``` import sys sys.stdout.write('.') ``` You may also need to call ``` sys.stdout.flush() ``` to ensure `stdout` is flushed immediately. ## Python 2.6+ From Python 2.6 you can import the `print` function from Python 3: ``` from __future__ import print_function ``` This allows you to use the Python 3 solution below. ## Python 3 In Python 3, the `print` statement has been changed into a function. In Python 3, you can instead do: ``` print('.', end="") ``` This also works in Python 2, provided that you've used `from __future__ import print_function`. If you are having trouble with buffering, you can flush the output by adding `flush=True` keyword argument: ``` print('.', end="", flush=True) ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,422
14
2009-01-29T21:07:36Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
The new (as of Python 3.0) print function has an optional end parameter that let's you modify the ending character. There's also sep for separator.
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
493,500
148
2009-01-29T21:24:58Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
*Note: The title of this question used to be something like "How to printf in python?"* Since people may come here looking for it based on the title, Python also supports printf-style substitution: ``` >>> strings = [ "one", "two", "three" ] >>> >>> for i in xrange(3): ... print "Item %d: %s" % (i, strings[i]) ... Item 0: one Item 1: two Item 2: three ``` And, you can handily multiply string values: ``` >>> print "." * 10 .......... ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
4,348,063
31
2010-12-03T17:16:00Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
This is not the answer to the question in the title, but it's the answer on how to print on the same line: ``` import sys for i in xrange(0,10): sys.stdout.write(".") sys.stdout.flush() ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
5,071,123
67
2011-02-21T20:50:30Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
Use the python3-style print function for python2.6+ *(will also break any existing keyworded print statements in the same file.)* ``` # for python2 to use the print() function, removing the print keyword from __future__ import print_function for x in xrange(10): print('.', end='') ``` To not ruin all your python2 print keywords, create a separate `printf.py` file ``` # printf.py from __future__ import print_function def printf(str, *args): print(str % args, end='') ``` Then, use it in your file ``` from printf import printf for x in xrange(10): printf('.') print 'done' #..........done ``` More examples showing printf style ``` printf('hello %s', 'world') printf('%i %f', 10, 3.14) #hello world10 3.140000 ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
11,685,717
166
2012-07-27T10:09:57Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
It should be as simple as described at this link by Guido Van Rossum: Re: How does one print without a c/r ? <http://www.python.org/search/hypermail/python-1992/0115.html> > Is it possible to print something but not automatically have a > carriage return appended to it ? Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline: ``` >>> for i in range(10): ... print i, ... else: ... print ... 0 1 2 3 4 5 6 7 8 9 >>> ```
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
24,685,004
13
2014-07-10T19:45:40Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
You can just add `,` in the end of `print` function so it won't print on new line.
How to print in Python without newline or space?
493,386
781
2009-01-29T20:58:25Z
30,881,087
7
2015-06-17T01:55:02Z
[ "python", "newline" ]
The question is in the title. I'd like to do in [python](/questions/tagged/python "show questions tagged 'python'") what I do in this example in [c](/questions/tagged/c "show questions tagged 'c'"): ``` #include <stdio.h> int main() { int i; for (i=0; i<10; i++) printf("."); return 0; } ``` Output: ``` .......... ``` In Python: ``` >>> for i in xrange(0,10): print '.' . . . . . . . . . . >>> for i in xrange(0,10): print '.', . . . . . . . . . . ``` In Python `print` will add a `\n` or a space, how can I avoid that? Now, it's just an example. Don't tell me I can first make a string then print it. I'd like to know how to "append" strings to the `stdout` (I don't know if it's worded correctly).
Using functools.partial to create a new function called printf ``` >>> import functools >>> printf = functools.partial(print, end="") >>> printf("Hello world\n") Hello world ``` Easy way to wrap a function with default parameters.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,831
170
2009-01-29T22:48:38Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Because the `join()` method is in the string class, instead of the list class? I agree it looks funny. See <http://www.faqs.org/docs/diveintopython/odbchelper_join.html>: > **Historical note.** When I first learned > Python, I expected join to be a method > of a list, which would take the > delimiter as an argument. Lots of > people feel the same way, and there’s > a story behind the join method. Prior > to Python 1.6, strings didn’t have all > these useful methods. There was a > separate string module which contained > all the string functions; each > function took a string as its first > argument. The functions were deemed > important enough to put onto the > strings themselves, which made sense > for functions like lower, upper, and > split. But many hard-core Python > programmers objected to the new join > method, arguing that it should be a > method of the list instead, or that it > shouldn’t move at all but simply stay > a part of the old string module (which > still has lots of useful stuff in it). > I use the new join method exclusively, > but you will see code written either > way, and if it really bothers you, you > can use the old string.join function > instead.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,842
672
2009-01-29T22:51:18Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
It's because any iterable can be joined, not just lists, but the result and the "joiner" are always strings. E.G: ``` import urllib2 print '\n############\n'.join( urllib2.urlopen('http://data.stackexchange.com/users/7095')) ```
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,843
10
2009-01-29T22:51:45Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Primarily because the result of a `someString.join()` is a string. The sequence (list or tuple or whatever) doesn't appear in the result, just a string. Because the result is a string, it makes sense as a method of a string.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
493,884
40
2009-01-29T23:03:45Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because: * it must work for different iterables too (tuples, generators, etc.) * it must have different behavior between different types of strings. There are actually two join methods (Python 3.0): ``` >>> b"".join <built-in method join of bytes object at 0x00A46800> >>> "".join <built-in method join of str object at 0x00A28D40> ``` If join was a method of a list, then it would have to inspect its arguments to decide which one of them to call. And you can't join byte and str together, so the way they have it now makes sense.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
494,320
15
2009-01-30T02:43:51Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
Think of it as the natural orthogonal operation to split. I understand why it is applicable to anything iterable and so can't easily be implemented *just* on list. For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
12,662,361
117
2012-09-30T15:21:16Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
This was discussed in the [String methods... finally](http://mail.python.org/pipermail/python-dev/1999-June/095366.html) thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and `str.join` was included in Python 1.6 (which supported Unicode) was released in Sep 2000. Python 2.0 (supported `str` methods including `join`) was released in Oct 2000. * There were four options proposed in this thread: + `str.join(seq)` + `seq.join(str)` + `seq.reduce(str)` + `join` as a built-in function * Guido wanted to support not only `list`s, `tuple`s, but all sequences/iterables. * `seq.reduce(str)` is difficult for new-comers. * `seq.join(str)` introduces unexpected dependency from sequences to str/unicode. * `join()` as a built-in function would support only specific data types. So using a built in namespace is not good. If `join()` supports many datatypes, creating optimized implementation would be difficult, if implemented using the `__add__` method then it's O(n2). * The separater string (`sep`) should not be omitted. Explicit is better than implicit. *There are no other reasons offered in this thread.* Here are some additional thoughts (my own, and my friend's): * Unicode support was coming, but it was not final. At that time `UTF-8` was the most likely about to replace `UCS2/4`. To calculate total buffer length of `UTF-8` strings it needs to know character coding rule. * At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn't support extending built-in types until 2.2. At that time it was difficult to provide basic iterable class (which is mentioned in another comment). Guido's decision is recorded in a [historical mail](http://mail.python.org/pipermail/python-dev/1999-June/095436.html), deciding on `str.join(seq)`: > Funny, but it does seem right! Barry, go for it... > --Guido van Rossum
Python join, why is it string.join(list) instead of list.join(string)?
493,819
919
2009-01-29T22:45:13Z
29,617,379
14
2015-04-14T00:45:18Z
[ "python", "string", "list", "join" ]
This has always confused me. It seems like this would be nicer: ``` my_list = ["Hello", "world"] print my_list.join("-") # Produce: "Hello-world" ``` Than this: ``` my_list = ["Hello", "world"] print "-".join(my_list) # Produce: "Hello-world" ``` Is there a specific reason it does it like this?
> # Why is it `string.join(list)` instead of `list.join(string)`? This is because `join` is a "string" method! It creates a string from any iterable. If we stuck the method on lists, what about when we have iterables that aren't lists? What if you have a tuple of strings? If this were a `list` method, you would have to cast every such iterator of strings as a `list` before you could join the elements into a single string! For example: ``` some_strings = ('foo', 'bar', 'baz') ``` Let's roll our own list join method: ``` class OurList(list): def join(self, s): return s.join(self) ``` And to use it, note that we have to first create a list from each iterable to join the strings in that iterable, wasting both memory and processing power: ``` >>> l = OurList(some_strings) # step 1, create our list >>> l.join(', ') # step 2, use our list join method! 'foo, bar, baz' ``` So we see we have to add an extra step to use our list method, instead of just using the builtin string method: ``` >>> ' | '.join(some_strings) # a single step! 'foo | bar | baz' ``` ## Performance Caveat for Generators The algorithm Python uses to create the final string with `str.join` actually has to pass over the iterable twice, so if you provide it a generator expression, it has to materialize it into a list first before it can create the final string. Thus, while passing around generators is usually better than list comprehensions, `str.join` is an exception: ``` >>> import timeit >>> min(timeit.repeat(lambda: ''.join(str(i) for i in range(10) if i))) 3.839168446022086 >>> min(timeit.repeat(lambda: ''.join([str(i) for i in range(10) if i]))) 3.339879313018173 ``` Nevertheless, the `str.join` operation is still semantically a "string" operation, so it still makes sense to have it on the `str` object than on miscellaneous iterables.
Uses for Dynamic Languages
493,973
8
2009-01-29T23:42:47Z
494,055
15
2009-01-30T00:23:01Z
[ "python", "programming-languages", "language-design", "dynamic-languages", "duck-typing" ]
My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compile-time duck typing), I'm curious what the benefits are of dynamic languages even when you have those. The bottom line is that, if I'm going to learn Python, I want to learn it in a way that really changes my thinking about programming, rather than just writing D in Python. I have not used dynamic languages since I was a fairly novice programmer and unable to appreciate the flexibility they supposedly offer, and want to learn to take full advantage of them now. What can be done easily/elegantly in a dynamically typed, interpreted language that's awkward or impossible in a static language, **even with templates, polymorphism, static type inference, and maybe runtime reflection?**
In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making *very good* dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up. In time, this will swing the other way. Already various static languages have: * Generics, which make static types less stupid by letting it select the right type when objects are passed around, saving the programmer from having to cast it themselves * Type inference, which saves having to waste time on writing the stuff that should be obvious * Closures, which among *many* other things help to separate mechanism from intention, letting you pull together complicated algorithms from mostly existing ingredients. * Implicit conversions, which lets you simulate "monkey patching" without the risks it usually involves. * Code loading and easy programmatic access to the compiler, so users and third parties can script your program. Use with caution! * Syntaxes that are more conducive to the creation of Domain Specific Languages within them. ...and no doubt more to come. The dynamic movement has spawned some interesting developments in static language design, and we all benefit from the competition. I only hope more of these features make it to the mainstream. There's one place where I don't see the dominant dynamic language being replaced, and that's Javascript in the browser. There's just too much of an existing market to replace, so the emphasis seems to be towards making Javascript itself better instead.
How can I disable quoting in the Python 2.4 CSV reader?
494,054
10
2009-01-30T00:22:40Z
494,126
12
2009-01-30T01:05:04Z
[ "python", "csv" ]
I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the [Python 2.4 version of the csv library](http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html#csv-fmt-params) does not seem to give me any way to turn off quoting, it just allows me to set the quote character (`dialect.quotechar = '"'` or whatever). If I try setting the quote character to `None` or the empty string, I get an error. I can sort of work around this by setting `dialect.quotechar` to some "rare" character, but this is brittle, as there is no ASCII character I can absolutely guarantee will not show up in field values (except the delimiter, but if I set `dialect.quotechar = dialect.delimiter`, things go predictably haywire). In [Python 2.5 and later](http://docs.python.org/library/csv.html), if I set `dialect.quoting` to `csv.QUOTE_NONE`, the CSV reader respects that and does not interpret any character as a quote character. Is there any way to duplicate this behavior in Python 2.4? **UPDATE**: Thanks Triptych and Mark Roddy for helping to narrow the problem down. Here's a simplest-case demonstration: ``` >>> import csv >>> import StringIO >>> data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ >>> reader = csv.reader(StringIO.StringIO(data)) >>> for i in reader: print i ... [] Traceback (most recent call last): File "<stdin>", line 1, in ? _csv.Error: newline inside string ``` The problem only occurs when there's a single double-quote character in the *final* column of a row. Unfortunately, this situation exists in my dataset. I've accepted Tanj's solution: manually assign a nonprinting character (`"\x07"` or `BEL`) as the quotechar. This is hacky, but it works, and I haven't yet seen another solution that does. Here's a demo of the solution in action: ``` >>> import csv >>> import StringIO >>> class MyDialect(csv.Dialect): ... quotechar = '\x07' ... delimiter = ',' ... lineterminator = '\n' ... doublequote = False ... skipinitialspace = False ... quoting = csv.QUOTE_NONE ... escapechar = '\\' ... >>> dialect = MyDialect() >>> data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ >>> reader = csv.reader(StringIO.StringIO(data), dialect=dialect) >>> for i in reader: print i ... [] ['1', '2', '3', '4', '"5'] ['1', '2', '3', '4', '5'] ``` In Python 2.5+ setting quoting to csv.QUOTE\_NONE would be sufficient, and the value of `quotechar` would then be irrelevant. (I'm actually getting my initial dialect via a `csv.Sniffer` and then overriding the quotechar value, not by subclassing `csv.Dialect`, but I don't want that to be a distraction from the real issue; the above two sessions demonstrate that `Sniffer` isn't the problem.)
I don't know if python would like/allow it but could you use a non-printable ascii code such as BEL or BS (backspace) These I would think to be extremely rare.
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
494,636
16
2009-01-30T06:15:45Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening. ``` startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) ``` Someone pointed out in my Part II (which was closed for being a duplicate - <http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome. --- I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?). What I have so far is no actual coding but rather: * Write Fib sequence formula to infinite * Display startNumber to endNumber only from Fib sequence. I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
The idea behind the Fibonacci sequence is shown in the following Python code: ``` def fib(n): if n == 1: return 1 elif n == 0: return 0 else: return fib(n-1) + fib(n-2) ``` This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be: fib(n-1) + fib(n-2) Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic: ``` fib(2) = fib(1) + fib(0) fib(1) = 1 fib(0) = 0 # Therefore by substitution: fib(2) = 1 + 0 fib(2) = 1 ``` We can calculate fib(3) the same way with the arithmetic shown below: ``` fib(3) = fib(2) + fib(1) fib(2) = fib(1) + fib(0) fib(2) = 1 fib(1) = 1 fib(0) = 0 # Therefore by substitution: fib(3) = 1 + 1 + 0 ``` The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming. This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck! Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
499,245
153
2009-01-31T18:01:14Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening. ``` startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) ``` Someone pointed out in my Part II (which was closed for being a duplicate - <http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome. --- I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?). What I have so far is no actual coding but rather: * Write Fib sequence formula to infinite * Display startNumber to endNumber only from Fib sequence. I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
There is lots of information about the Fibonacci Sequence on [wikipedia](http://en.wikipedia.org/wiki/Fibonacci_number) and on [wolfram](http://mathworld.wolfram.com/FibonacciNumber.html). A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need. ## Write Fib sequence formula to infinite In math, it's given in a recursive form: ![fibonacci from wikipedia](http://upload.wikimedia.org/math/7/6/f/76f99713cf111eb035d908228c351710.png) In programming, **infinite** doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes: ``` def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) ``` Try it in your favourite language and see that this form requires **a lot** of time as n gets bigger. In fact, this is O(2n) in time. Go on on the sites I linked to you and will see this (on wolfram): ![alt text](http://mathworld.wolfram.com/images/equations/FibonacciNumber/NumberedEquation6.gif) This one is pretty easy to implement and very, very fast to compute, in Python: ``` from math import sqrt def F(n): return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)) ``` An other way to do it is following the definition (from [wikipedia](http://en.wikipedia.org/wiki/Fibonacci_number)): > The first number of the sequence is 0, > the second number is 1, and each > subsequent number is equal to the sum > of the previous two numbers of the > sequence itself, yielding the sequence > 0, 1, 1, 2, 3, 5, 8, etc. If your language supports iterators you may do something like: ``` def F(): a,b = 0,1 yield a yield b while True: a, b = b, a + b yield b ``` ## Display startNumber to endNumber only from Fib sequence. Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions. Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) ) In most languages you can do something like: ``` def SubFib(startNumber, endNumber): n = 0 cur = f(n) while cur <= endNumber: if startNumber <= cur: print cur n += 1 cur = f(n) ``` In python I'd use the iterator form and go for: ``` def SubFib(startNumber, endNumber): for cur in F(): if cur > endNumber: return if cur >= startNumber: yield cur for i in SubFib(10, 200): print i ``` My hint is to *learn to read* what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
24,846,766
24
2014-07-20T02:24:24Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening. ``` startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) ``` Someone pointed out in my Part II (which was closed for being a duplicate - <http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome. --- I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?). What I have so far is no actual coding but rather: * Write Fib sequence formula to infinite * Display startNumber to endNumber only from Fib sequence. I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
# Efficient Pythonic generator of the Fibonacci sequence I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a [Python Enhancement Proposal](https://www.python.org/dev/peps/pep-0255/)), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand: ``` def fib(): a, b = 0, 1 while True: # First iteration: yield a # yield 0 to start with and then a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1) ``` and usage: ``` for index, fibonacci_number in enumerate(fib()): print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number)) if index == 10: break ``` prints: ``` 0: 0 1: 1 2: 1 3: 2 4: 3 5: 5 6: 8 7: 13 8: 21 9: 34 10: 55 ``` (For attribution purposes, I recently noticed a [similar implementation](https://docs.python.org/2/tutorial/modules.html) in the Python documentation on modules, even using the variables `a` and `b`, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.) # Recursively defined implementation The [Online Encyclopedia of Integer Sequences](http://oeis.org/A000045) defines the Fibonacci Sequence recursively as > F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1 Succinctly defining this recursively in Python can be done as follows: ``` def rec_fib(n): '''inefficient recursive function as defined, returns Fibonacci number''' if n > 1: return rec_fib(n-1) + rec_fib(n-2) return n ``` But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following: ``` for i in range(40): print i, rec_fib(i) ``` # Memoized recursion for efficiency It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason): ``` def mem_fib(n, _cache={}): '''efficiently memoized recursive function, returns a Fibonacci number''' if n in _cache: return _cache[n] elif n > 1: return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2)) return n ``` You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this: ``` for i in range(40): print i, mem_fib(i) ``` (It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.) ``` def mem_fib(n, _cache={}): '''don't do this''' if n > 1: return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2)) return n ```
How to write the Fibonacci Sequence in Python
494,594
68
2009-01-30T05:49:13Z
26,118,289
7
2014-09-30T10:14:59Z
[ "python", "fibonacci", "sequences" ]
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 & 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening. ``` startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here ")) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) print map(fib, range(startNumber, endNumber)) ``` Someone pointed out in my Part II (which was closed for being a duplicate - <http://stackoverflow.com/questions/504193/how-to-write-the-fibonacci-sequence-in-python-part-ii>) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome. --- I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?). What I have so far is no actual coding but rather: * Write Fib sequence formula to infinite * Display startNumber to endNumber only from Fib sequence. I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
**Time complexity :** The caching feature reduces the normal way of calculating Fibonacci series from **O(2^n)** to **O(n)** by eliminating the repeats in the recursive tree of Fibonacci series : ![enter image description here](http://i.stack.imgur.com/59Rpw.png) **Code :** ``` import sys table = [0]*1000 def FastFib(n): if n<=1: return n else: if(table[n-1]==0): table[n-1] = FastFib(n-1) if(table[n-2]==0): table[n-2] = FastFib(n-2) table[n] = table[n-1] + table[n-2] return table[n] def main(): print('Enter a number : ') num = int(sys.stdin.readline()) print(FastFib(num)) if __name__=='__main__': main() ```
refactor this dictionary-to-xml converter in python
494,881
3
2009-01-30T08:33:12Z
494,905
9
2009-01-30T08:52:10Z
[ "python", "xml", "dry" ]
It's a small thing, really: I have this function that converts dict objects to xml. Here's the function: ``` def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for name, value in node.iteritems(): if isinstance(value, dict): lines.append(offset + u"<%s>" % name) addDict(value, offset + u" " * 4) lines.append(offset + u"</%s>" % name) elif isinstance(value, list): for item in value: if isinstance(item, dict): lines.append(offset + u"<%s>" % name) addDict(item, offset + u" " * 4) lines.append(offset + u"</%s>" % name) else: lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(item)), name)) else: lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(value)), name)) addDict(d, u"") lines.append(u"") return u"\n".join(lines) ``` For example, it converts this dictionary ``` { 'site': { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } } ``` to: ``` <site> <name>stackoverflow</name> <blogger>jeff</blogger> <blogger>joel</blogger> </site> ``` It works, but the `addDict` function looks a little too repetitive. I'm sure there's a way to refactor it into 3 co-recursive functions named `addDict`, `addList` and `addElse`, but my brain is stuck. Any help? Also, any way to get rid of the `offset +` thing in every line would be nice. **NOTE**: I chose these semantics because I'm trying to match the behavior of the [json-to-xml converter](http://www.json.org/javadoc/org/json/XML.html#toString(java.lang.Object)) in [org.json](http://www.json.org/java/index.html), which I use in a different part of my project. If you got to this page just looking for a dictionary to xml converter, there are some [really](#494905) good [options](#495512) in some of the answers. (Especially [pyfo](http://foss.cpcc.edu/pyfo/)).
``` >>> from pyfo import pyfo >>> d = ('site', { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } ) >>> result = pyfo(d, pretty=True, prolog=True, encoding='ascii') >>> print result.encode('ascii', 'xmlcharrefreplace') <?xml version="1.0" encoding="ascii"?> <site> <blogger> Jeff Joel </blogger> <name>stackoverflow</name> </site> ``` To install [pyfo](http://foss.cpcc.edu/pyfo/): ``` $ easy_install pyfo ```
Refactor this Python code to iterate over a container
495,294
3
2009-01-30T12:02:34Z
495,343
19
2009-01-30T12:22:05Z
[ "python", "django", "refactoring", "iterator" ]
Surely there is a better way to do this? ``` results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) ``` The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question. **EDIT:** I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".
``` results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []] ```
Refactor this Python code to iterate over a container
495,294
3
2009-01-30T12:02:34Z
495,400
8
2009-01-30T12:44:35Z
[ "python", "django", "refactoring", "iterator" ]
Surely there is a better way to do this? ``` results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) ``` The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question. **EDIT:** I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None".
How about ``` for obj in (queryset or []): # Do your stuff ``` It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.
Confusion about global variables in python
495,422
11
2009-01-30T12:56:57Z
495,570
15
2009-01-30T14:01:27Z
[ "python", "global-variables", "python-import" ]
I'm new to python, so please excuse what is probably a pretty dumb question. Basically, I have a single global variable, called \_debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it. I have two scripts: ``` one.py: ------- def my_function(): if _debug: print "debugging!" two.py: ------- from one import * _debug = False my_function() ``` Running two.py generates an error: ``` NameError: global name '_debug' is not defined ``` Can anyone tell me what I'm doing wrong?
There are more problems than just the leading underscore I'm afraid. When you call `my_function()`, it still won't have your `debug` variable in its namespace, unless you import it from `two.py`. Of course, doing that means you'll end up with cyclic dependencies (`one.py -> two.py -> one.py`), and you'll get `NameError`s unless you refactor where various things are imported and declared. One solution would be to create a simple third module which defines 'constants' like this, which can be safely imported from anywhere, e.g.: ``` constants.py ------------ debug = True one.py ------ from constants import debug #... two.py ------ from constants import debug #... ``` However, I would recommend just using the built in [logging](http://docs.python.org/library/logging.html#module-logging) module for this - why not? It's easy to configure, simpler to use, reliable, flexible and extensible.
Python's version of PHP's time() function
495,595
2
2009-01-30T14:09:29Z
495,610
19
2009-01-30T14:13:19Z
[ "python", "time" ]
I've looked at the [Python Time module](http://docs.python.org/library/time.html) and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time(). Am I simply missing something here or is there a common way to do this that's simply not listed there?
``` import time print int(time.time()) ```
Is there any case where len(someObj) does not call someObj's __len__ function?
496,009
5
2009-01-30T15:58:58Z
496,038
7
2009-01-30T16:07:33Z
[ "python" ]
Is there any case where len(someObj) does not call someObj's `__len__` function? I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there's not some edge case somewhere where len(someObj) is not the same as someObj.`__len__`().
What kind of speedup did you see? I cannot imagine it was noticeable was it? From <http://mail.python.org/pipermail/python-list/2002-May/147079.html> > in certain situations there is no > difference, but using len() is > preferred for a couple reasons. > > first, it's not recommended to go > calling the `__methods__` yourself, they > are meant to be used by other parts of > python. > > `len()` will work on any type of > sequence object (`lists`, `tuples`, and > all). > `__len__` will only work on class instances with a `__len__` method. > > `len()` will return a more appropriate > exception on objects without length.
What's a good way to keep track of class instance variables in Python?
496,582
8
2009-01-30T18:21:13Z
496,656
7
2009-01-30T18:39:58Z
[ "python", "variables" ]
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a `.h` file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? **Edit:** It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.
First of all: class attributes, or instance attributes? Or both? =) *Usually* you just add instance attributes in `__init__`, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases. If code adds attributes on the fly, it probably (hopefully :-) has good reasons for doing so... leveraging dynamic features, introspection, etc. Other than that, adding attributes this way is probably less common than you think.
What's a good way to keep track of class instance variables in Python?
496,582
8
2009-01-30T18:21:13Z
498,284
9
2009-01-31T04:45:58Z
[ "python", "variables" ]
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a `.h` file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all? I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this? **Edit:** It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly.
I would say, the standard practice to avoid this is to *not write classes where you can be 1000 lines away from anything!* Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code into separate modules should help keeping your LOC count down. The largest classes in the standard library have well below 100 lines!
Progress bar not updating during operation
496,814
7
2009-01-30T19:17:39Z
497,313
12
2009-01-30T21:26:52Z
[ "python", "user-interface", "gtk", "progress-bar", "pygtk" ]
in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my question is - do i need to have a multi-threaded application to upload the file and simultaneously update the gui? or is there some other mistake that im making? Thanks in advance!
I'm going to quote the [PyGTK FAQ](http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp): > You have created a progress bar inside a window, then you start running a loop that does some work: ``` while work_left: ...do something... progressbar.set_fraction(...) ``` > You will notice that the window doesn't even show up, or if it does the progress bar stays frozen until the end of the task. The explanation is simple: gtk is event driven, and you are stealing control away from the gtk main loop, thus preventing it from processing normal GUI update events. > > The simplest solution consists on temporarily giving control back to gtk every time the progress is changed: ``` while work_left: ...do something... progressbar.set_fraction(...) while gtk.events_pending(): gtk.main_iteration() ``` > Notice that with this solution, the user cannot quit the application (gtk.main\_quit would not work because of new loop [gtk.main\_iteration()]) until your heavy\_work is done. > > Another solution consists on using gtk idle functions, which are called by the gtk main loop whenever it has nothing to do. Therefore, gtk is in control, and the idle function has to do a bit of work. It should return True if there's more work to be done, otherwise False. > > The best solution (it has no drawbacks) was pointed out by James Henstridge. It is taking advantage of python's generators as idle functions, to make python automatically preserve the state for us. It goes like this: ``` def my_task(data): ...some work... while heavy_work_needed: ...do heavy work here... progress_label.set_text(data) # here we update parts of UI # there's more work, return True yield True # no more work, return False yield False def on_start_my_task_button_click(data): task = my_task(data) gobject.idle_add(task.next) ``` > The 'while' above is just an example. The only rules are that it should yield True after doing a bit of work and there's more work to do, and it must yield False when the task is done.
Is there a Python equivalent of Perl's x operator?
497,114
11
2009-01-30T20:27:49Z
497,119
31
2009-01-30T20:29:15Z
[ "python", "perl" ]
In Perl, I can replicate strings with the 'x' operator: ``` $str = "x" x 5; ``` Can I do something similar in Python?
``` >>> "blah" * 5 'blahblahblahblahblah' ```
Python's os.path choking on Hebrew filenames
497,233
13
2009-01-30T21:03:24Z
497,356
14
2009-01-30T21:40:06Z
[ "python", "internationalization", "hebrew" ]
I'm writing a script that has to move some file around, but unfortunately it doesn't seem `os.path` plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory: ![alt text](http://eli.thegreenplace.net/files/temp/hebfilenameshot.png) Now consider this code that goes over the files in this directory: ``` files = os.listdir('test_source') for f in files: pf = os.path.join('test_source', f) print pf, os.path.exists(pf) ``` The output is: ``` test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt False ``` Notice how `os.path.exists` thinks that the hebrew-named file doesn't even exist? How can I fix this? ActivePython 2.5.2 on Windows XP Home SP2
Hmm, after [some digging](http://www.amk.ca/python/howto/unicode) it appears that when supplying os.listdir a unicode string, this kinda works: ``` files = os.listdir(u'test_source') for f in files: pf = os.path.join(u'test_source', f) print pf.encode('ascii', 'replace'), os.path.exists(pf) ``` ===> ``` test_source\ex True test_source\joe True test_source\mie.txt True test_source\__()'''.txt True test_source\????.txt True ``` Some important observations here: * Windows XP (like all NT derivatives) stores *all* filenames in unicode * `os.listdir` (and similar functions, like `os.walk`) should be passed a unicode string in order to work correctly with unicode paths. Here's a quote from the aforementioned link: > os.listdir(), which returns filenames, > raises an issue: should it return the > Unicode version of filenames, or > should it return 8-bit strings > containing the encoded versions? > os.listdir() will do both, depending > on whether you provided the directory > path as an 8-bit string or a Unicode > string. If you pass a Unicode string > as the path, filenames will be decoded > using the filesystem's encoding and a > list of Unicode strings will be > returned, while passing an 8-bit path > will return the 8-bit versions of the > filenames. * And lastly, `print` wants an ascii string, not unicode, so the path has to be encoded to ascii.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,434
65
2009-01-30T22:02:26Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index). If your items are adjacent, you can use the slice assignment syntax: ``` a[2:10] = [] ```
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,439
45
2009-01-30T22:05:01Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
Probably not the best solution for this problem: ``` indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices] ```
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
497,451
13
2009-01-30T22:09:38Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
As a function: ``` def multi_delete(list_, *args): indexes = sorted(list(args), reverse=True) for index in indexes: del list_[index] return list_ ``` Runs in **n log(n)** time, which should make it the fastest correct solution yet.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
498,074
9
2009-01-31T02:23:39Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously. Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to\_delete indices are in ascending order, otherwise it won't work. ``` to_delete = [1, 4, 7] target = list("hello world") for offset, index in enumerate(to_delete): index -= offset del target[index] ``` It'd be a more complicated if you wanted to delete the elements in any order. IMO, sorting `to_delete` might be easier than figuring out when you should or shouldn't subtract from `index`.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
500,076
14
2009-02-01T02:55:32Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2: ``` >>> a= [0, 1, 2, 3, 4] >>> del a[0:3:2] >>> a [1, 3, 4] ``` This doesn't cover any arbitrary selection, of course, but it can certainly work for deleting any two items.
Deleting multiple elements from a list
497,426
78
2009-01-30T21:59:38Z
28,697,246
30
2015-02-24T13:36:44Z
[ "python", "list" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3]. I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
For some reason I don't like any of the answers here. Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy). Why not just delete the higher index first? Is there a reason for this? I would just do: ``` for i in sorted(indices, reverse=True): del somelist[i] ``` If you really don't want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can't really use the same index since you're having a different list) or use a copy of the list (which wouldn't be 'deleting' but replacing the original with an edited copy). Am I missing something here, any reason to NOT delete in the reverse order?
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
497,687
21
2009-01-30T23:29:45Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the model. 2. Delete the test database. (always a simple sqlite database for me.) 3. Run "syncdb". 4. Generate some test data via code. 5. goto 1. A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\ TIA.
Steps 2 & 3 can be done in one step: ``` manage.py reset appname ``` Step 4 is most easily managed, from my understanding, by using [fixtures](http://www.djangoproject.com/documentation/models/fixtures/)
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
497,696
14
2009-01-30T23:32:02Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the model. 2. Delete the test database. (always a simple sqlite database for me.) 3. Run "syncdb". 4. Generate some test data via code. 5. goto 1. A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\ TIA.
This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them. To use them: 1. Set up your data in your app (call it "foo") using the admin tool 2. Create a fixtures directory in your "foo" app directory 3. Type: `python manage.py dumpdata --indent=4 foo > foo/fixtures/foo.json` Now, after your syncdb stage, you just type: ``` python manage.py loaddata foo.json ``` And your data will be re-created. If you want them in a test case: ``` class FooTests(TestCase): fixtures = ['foo.json'] ``` Note that you will have to recreate or manually update your fixtures if your schema changes drastically. You can read more about fixtures in the django docs for [Fixture Loading](http://docs.djangoproject.com/en/dev/topics/testing/#fixture-loading)
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
498,092
12
2009-01-31T02:39:00Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the model. 2. Delete the test database. (always a simple sqlite database for me.) 3. Run "syncdb". 4. Generate some test data via code. 5. goto 1. A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\ TIA.
Here's what we do. 1. Apps are named with a Schema version number. `appa_2`, `appb_1`, etc. 2. Minor changes don't change the number. 3. Major changes increment the number. Syncdb works. And a "data migration" script can be written. ``` def migrate_appa_2_to_3(): for a in appa_2.SomeThing.objects.all(): appa_3.AnotherThing.create( a.this, a.that ) appa_3.NewThing.create( a.another, a.yetAnother ) for b in ... ``` The point is that drop and recreate isn't always appropriate. It's sometimes helpful to move data form the old model to the new model without rebuilding from scratch.
Django workflow when modifying models frequently?
497,654
24
2009-01-30T23:18:54Z
636,949
10
2009-03-12T00:33:46Z
[ "python", "django", "django-models", "workflow", "django-syncdb" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the model. 2. Delete the test database. (always a simple sqlite database for me.) 3. Run "syncdb". 4. Generate some test data via code. 5. goto 1. A secondary question regarding this.. In case your workflow is like above, how do you execute the 4. step? Do you generate the test data manually or is there a proper hook point in Django apps where you can inject the test-data-generating-code at server startup?\ TIA.
South is the coolest. Though good ol' reset works best when data doesn't matter. <http://south.aeracode.org/>
IronPython vs. C# for small-scale projects
497,747
8
2009-01-30T23:59:34Z
497,938
11
2009-01-31T01:15:04Z
[ "c#", ".net", "python", "ironpython" ]
I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Since Python is my favorite programming language (mainly because of its conciseness and clean syntax), IronPython sounds like the ideal option. Yet after reading about it a little bit I have several questions. For those of you who have used IronPython, does it ever become unclear where classic Python ends and .NET begins? For example, there appears to be significant overlap in functionality between the .NET libraries and the Python standard library, so when I need to do string operations or parse XML, I'm unclear which library I'm supposed to use. Also, I'm unclear when I'm supposed to use Python versus .NET data types in my code. For example, which of the following would I be using in my code? ``` d = {} ``` or ``` d = System.Collections.Hashtable() ``` (By the way, it seems that if I do a lot of things like the latter I might lose some of the conciseness, which is why I favor Python in the first place.) Another issue is that a number of Microsoft's developer tools, such as .NET CF and Xbox XNA, are not available in IronPython. Are there more situations where IronPython wouldn't give me the full reach of C#?
I've built a large-scale application in IronPython bound with C#. It's almost completely seamless. The only things missing in IronPython from the true "python" feel are the C-based libraries (gotta use .NET for those) and IDLE. The language interacts with other .NET languages like a dream... Specifically if you embed the interpreter and bind variables by reference. By the way, a hash in IronPython is declared: ``` d = {} ``` Just be aware that it's actually an IronPython.Dict object, and not a C# dictionary. That said, the conversions often work invisibly if you pass it to a .NET class, and if you need to convert explicitly, there are built-ins that do it just fine. All in all, an awesome language to use with .NET, if you have reason to. Just a word of advice: Avoid the Visual Studio IronPython IDE like the plague. I found the automatic line completions screwed up on indentation, between spaces and tabs. Now -that- is a difficult-to-trace bug inserted into code.
Python string.join(list) on object array rather than string array
497,765
134
2009-01-31T00:06:07Z
497,773
207
2009-01-31T00:10:58Z
[ "python", "list" ]
In Python, I can do: ``` >>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c' ``` Is there any easy way to do the same when I have a list of objects? ``` >>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, instance found ``` Or do I have to resort to a for loop?
You could use a list comprehension or a generator expression instead: ``` ', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression ```
Python string.join(list) on object array rather than string array
497,765
134
2009-01-31T00:06:07Z
497,787
49
2009-01-31T00:16:03Z
[ "python", "list" ]
In Python, I can do: ``` >>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c' ``` Is there any easy way to do the same when I have a list of objects? ``` >>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(), Obj()] >>> ', '.join(list) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, instance found ``` Or do I have to resort to a for loop?
The built-in string constructor will automatically call `obj.__str__`: ``` ''.join(map(str,list)) ```
Python element-wise tuple operations like sum
497,885
52
2009-01-31T00:51:48Z
497,894
72
2009-01-31T00:55:01Z
[ "python", "tuples" ]
Is there anyway to get tuple operations in Python to work like this: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (4,4,4) ``` instead of: ``` >>> a = (1,2,3) >>> b = (3,2,1) >>> a + b (1,2,3,3,2,1) ``` I know it works like that because the `__add__` and `__mul__` methods are defined to work like that. So the only way would be to redefine them?
``` import operator tuple(map(operator.add, a, b)) ```