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
Unicode block of a character in python
243,831
5
2008-10-28T15:56:18Z
245,072
10
2008-10-28T22:13:30Z
[ "python", "unicode", "character-properties" ]
Is there a way to get the Unicode Block of a character in python? The [unicodedata](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html) module doesn't seem to have what I need, and I couldn't find an external library for it. Basically, I need the same functionality as [`Character.UnicodeBlock.of()`](http://java.sun.com/javase/6/docs/api/java/lang/Character.UnicodeBlock.html#of(char)) in java.
I couldn't find one either. Strange! Luckily, the number of Unicode blocks is quite manageably small. This implementation accepts a one-character Unicode string, just like the functions in `unicodedata`. If your inputs are mostly ASCII, this linear search might even be faster than binary search using `bisect` or whatever. If I were submitting this for inclusion in the Python standard library, I'd probably write it as a binary search through an array of statically-initialized `struct`s in C. ``` def block(ch): ''' Return the Unicode block name for ch, or None if ch has no block. >>> block(u'a') 'Basic Latin' >>> block(unichr(0x0b80)) 'Tamil' >>> block(unichr(0xe0080)) ''' assert isinstance(ch, unicode) and len(ch) == 1, repr(ch) cp = ord(ch) for start, end, name in _blocks: if start <= cp <= end: return name def _initBlocks(text): global _blocks _blocks = [] import re pattern = re.compile(r'([0-9A-F]+)\.\.([0-9A-F]+);\ (\S.*\S)') for line in text.splitlines(): m = pattern.match(line) if m: start, end, name = m.groups() _blocks.append((int(start, 16), int(end, 16), name)) # retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt _initBlocks(''' # Blocks-5.1.0.txt # Date: 2008-03-20, 17:41:00 PDT [KW] # # Unicode Character Database # Copyright (c) 1991-2008 Unicode, Inc. # For terms of use, see http://www.unicode.org/terms_of_use.html # For documentation, see UCD.html # # Note: The casing of block names is not normative. # For example, "Basic Latin" and "BASIC LATIN" are equivalent. # # Format: # Start Code..End Code; Block Name # ================================================ # Note: When comparing block names, casing, whitespace, hyphens, # and underbars are ignored. # For example, "Latin Extended-A" and "latin extended a" are equivalent. # For more information on the comparison of property values, # see UCD.html. # # All code points not explicitly listed for Block # have the value No_Block. # Property: Block # # @missing: 0000..10FFFF; No_Block 0000..007F; Basic Latin 0080..00FF; Latin-1 Supplement 0100..017F; Latin Extended-A 0180..024F; Latin Extended-B 0250..02AF; IPA Extensions 02B0..02FF; Spacing Modifier Letters 0300..036F; Combining Diacritical Marks 0370..03FF; Greek and Coptic 0400..04FF; Cyrillic 0500..052F; Cyrillic Supplement 0530..058F; Armenian 0590..05FF; Hebrew 0600..06FF; Arabic 0700..074F; Syriac 0750..077F; Arabic Supplement 0780..07BF; Thaana 07C0..07FF; NKo 0900..097F; Devanagari 0980..09FF; Bengali 0A00..0A7F; Gurmukhi 0A80..0AFF; Gujarati 0B00..0B7F; Oriya 0B80..0BFF; Tamil 0C00..0C7F; Telugu 0C80..0CFF; Kannada 0D00..0D7F; Malayalam 0D80..0DFF; Sinhala 0E00..0E7F; Thai 0E80..0EFF; Lao 0F00..0FFF; Tibetan 1000..109F; Myanmar 10A0..10FF; Georgian 1100..11FF; Hangul Jamo 1200..137F; Ethiopic 1380..139F; Ethiopic Supplement 13A0..13FF; Cherokee 1400..167F; Unified Canadian Aboriginal Syllabics 1680..169F; Ogham 16A0..16FF; Runic 1700..171F; Tagalog 1720..173F; Hanunoo 1740..175F; Buhid 1760..177F; Tagbanwa 1780..17FF; Khmer 1800..18AF; Mongolian 1900..194F; Limbu 1950..197F; Tai Le 1980..19DF; New Tai Lue 19E0..19FF; Khmer Symbols 1A00..1A1F; Buginese 1B00..1B7F; Balinese 1B80..1BBF; Sundanese 1C00..1C4F; Lepcha 1C50..1C7F; Ol Chiki 1D00..1D7F; Phonetic Extensions 1D80..1DBF; Phonetic Extensions Supplement 1DC0..1DFF; Combining Diacritical Marks Supplement 1E00..1EFF; Latin Extended Additional 1F00..1FFF; Greek Extended 2000..206F; General Punctuation 2070..209F; Superscripts and Subscripts 20A0..20CF; Currency Symbols 20D0..20FF; Combining Diacritical Marks for Symbols 2100..214F; Letterlike Symbols 2150..218F; Number Forms 2190..21FF; Arrows 2200..22FF; Mathematical Operators 2300..23FF; Miscellaneous Technical 2400..243F; Control Pictures 2440..245F; Optical Character Recognition 2460..24FF; Enclosed Alphanumerics 2500..257F; Box Drawing 2580..259F; Block Elements 25A0..25FF; Geometric Shapes 2600..26FF; Miscellaneous Symbols 2700..27BF; Dingbats 27C0..27EF; Miscellaneous Mathematical Symbols-A 27F0..27FF; Supplemental Arrows-A 2800..28FF; Braille Patterns 2900..297F; Supplemental Arrows-B 2980..29FF; Miscellaneous Mathematical Symbols-B 2A00..2AFF; Supplemental Mathematical Operators 2B00..2BFF; Miscellaneous Symbols and Arrows 2C00..2C5F; Glagolitic 2C60..2C7F; Latin Extended-C 2C80..2CFF; Coptic 2D00..2D2F; Georgian Supplement 2D30..2D7F; Tifinagh 2D80..2DDF; Ethiopic Extended 2DE0..2DFF; Cyrillic Extended-A 2E00..2E7F; Supplemental Punctuation 2E80..2EFF; CJK Radicals Supplement 2F00..2FDF; Kangxi Radicals 2FF0..2FFF; Ideographic Description Characters 3000..303F; CJK Symbols and Punctuation 3040..309F; Hiragana 30A0..30FF; Katakana 3100..312F; Bopomofo 3130..318F; Hangul Compatibility Jamo 3190..319F; Kanbun 31A0..31BF; Bopomofo Extended 31C0..31EF; CJK Strokes 31F0..31FF; Katakana Phonetic Extensions 3200..32FF; Enclosed CJK Letters and Months 3300..33FF; CJK Compatibility 3400..4DBF; CJK Unified Ideographs Extension A 4DC0..4DFF; Yijing Hexagram Symbols 4E00..9FFF; CJK Unified Ideographs A000..A48F; Yi Syllables A490..A4CF; Yi Radicals A500..A63F; Vai A640..A69F; Cyrillic Extended-B A700..A71F; Modifier Tone Letters A720..A7FF; Latin Extended-D A800..A82F; Syloti Nagri A840..A87F; Phags-pa A880..A8DF; Saurashtra A900..A92F; Kayah Li A930..A95F; Rejang AA00..AA5F; Cham AC00..D7AF; Hangul Syllables D800..DB7F; High Surrogates DB80..DBFF; High Private Use Surrogates DC00..DFFF; Low Surrogates E000..F8FF; Private Use Area F900..FAFF; CJK Compatibility Ideographs FB00..FB4F; Alphabetic Presentation Forms FB50..FDFF; Arabic Presentation Forms-A FE00..FE0F; Variation Selectors FE10..FE1F; Vertical Forms FE20..FE2F; Combining Half Marks FE30..FE4F; CJK Compatibility Forms FE50..FE6F; Small Form Variants FE70..FEFF; Arabic Presentation Forms-B FF00..FFEF; Halfwidth and Fullwidth Forms FFF0..FFFF; Specials 10000..1007F; Linear B Syllabary 10080..100FF; Linear B Ideograms 10100..1013F; Aegean Numbers 10140..1018F; Ancient Greek Numbers 10190..101CF; Ancient Symbols 101D0..101FF; Phaistos Disc 10280..1029F; Lycian 102A0..102DF; Carian 10300..1032F; Old Italic 10330..1034F; Gothic 10380..1039F; Ugaritic 103A0..103DF; Old Persian 10400..1044F; Deseret 10450..1047F; Shavian 10480..104AF; Osmanya 10800..1083F; Cypriot Syllabary 10900..1091F; Phoenician 10920..1093F; Lydian 10A00..10A5F; Kharoshthi 12000..123FF; Cuneiform 12400..1247F; Cuneiform Numbers and Punctuation 1D000..1D0FF; Byzantine Musical Symbols 1D100..1D1FF; Musical Symbols 1D200..1D24F; Ancient Greek Musical Notation 1D300..1D35F; Tai Xuan Jing Symbols 1D360..1D37F; Counting Rod Numerals 1D400..1D7FF; Mathematical Alphanumeric Symbols 1F000..1F02F; Mahjong Tiles 1F030..1F09F; Domino Tiles 20000..2A6DF; CJK Unified Ideographs Extension B 2F800..2FA1F; CJK Compatibility Ideographs Supplement E0000..E007F; Tags E0100..E01EF; Variation Selectors Supplement F0000..FFFFF; Supplementary Private Use Area-A 100000..10FFFF; Supplementary Private Use Area-B # EOF ''') ```
How to copy all properties of an object to another object, in Python?
243,836
21
2008-10-28T15:58:11Z
244,116
20
2008-10-28T17:16:27Z
[ "python" ]
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' PropertyUtilsBean.copyProperties() Thanks!
If your class does not modify `__getitem__` or `__setitem__` for special attribute access all your attributes are stored in `__dict__` so you can do: ``` nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy ``` If you use python properties you should look at `inspect.getmembers()` and filter out the ones you want to copy.
How to copy all properties of an object to another object, in Python?
243,836
21
2008-10-28T15:58:11Z
244,654
27
2008-10-28T20:06:09Z
[ "python" ]
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' PropertyUtilsBean.copyProperties() Thanks!
Try `destination.__dict__.update(source.__dict__)`.
What is the OCaml idiom equivalent to Python's range function?
243,864
16
2008-10-28T16:06:33Z
244,078
9
2008-10-28T17:07:22Z
[ "python", "ocaml" ]
I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1). What is the right OCaml idiom for this?
Here you go: ``` let rec range i j = if i > j then [] else i :: (range (i+1) j) ``` Note that this is not tail-recursive. Modern Python versions even have a lazy range.
What is the OCaml idiom equivalent to Python's range function?
243,864
16
2008-10-28T16:06:33Z
244,104
19
2008-10-28T17:13:42Z
[ "python", "ocaml" ]
I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1). What is the right OCaml idiom for this?
There is no idiom that I know of, but here is a fairly natural definition using an infix operator: ``` # let (--) i j = let rec aux n acc = if n < i then acc else aux (n-1) (n :: acc) in aux j [] ;; val ( -- ) : int -> int -> int list = <fun> # 1--2;; - : int list = [1; 2] # 1--5;; - : int list = [1; 2; 3; 4; 5] # 5--10;; - : int list = [5; 6; 7; 8; 9; 10] ``` Alternatively, the [comprehensions syntax extension](http://dutherenverseauborddelatable.wordpress.com/downloads/comprehension-for-ocaml/) (which gives the syntax `[i .. j]` for the above) is likely to be included in a future release of the ["community version" of OCaml](http://forge.ocamlcore.org/projects/batteries/), so that may become idiomatic. I don't recommend you start playing with syntax extensions if you are new to the language, though.
What is the OCaml idiom equivalent to Python's range function?
243,864
16
2008-10-28T16:06:33Z
2,926,149
10
2010-05-28T01:33:00Z
[ "python", "ocaml" ]
I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1). What is the right OCaml idiom for this?
With [Batteries Included](http://batteries.forge.ocamlcore.org), you can write ``` let nums = List.of_enum (1--10);; ``` The `--` operator generates an enumeration from the first value to the second. The `--^` operator is similar, but enumerates a half-open interval (`1--^10` will enumerate from 1 through 9).
How do I merge two python iterators?
243,865
16
2008-10-28T16:07:12Z
243,892
10
2008-10-28T16:12:19Z
[ "python", "merge", "iterator" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration ``` What is the simplest, most concise way to do this?
I'd do something like this. This will be most time and space efficient, since you won't have the overhead of zipping objects together. This will also work if both `a` and `b` are infinite. ``` def imerge(a, b): i1 = iter(a) i2 = iter(b) while True: try: yield i1.next() yield i2.next() except StopIteration: return ```
How do I merge two python iterators?
243,865
16
2008-10-28T16:07:12Z
243,902
32
2008-10-28T16:14:02Z
[ "python", "merge", "iterator" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration ``` What is the simplest, most concise way to do this?
A generator will solve your problem nicely. ``` def imerge(a, b): for i, j in itertools.izip(a,b): yield i yield j ```
How do I merge two python iterators?
243,865
16
2008-10-28T16:07:12Z
244,049
13
2008-10-28T16:59:35Z
[ "python", "merge", "iterator" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration ``` What is the simplest, most concise way to do this?
You can do something that is almost exaclty what @Pramod first suggested. ``` def izipmerge(a, b): for i, j in itertools.izip(a,b): yield i yield j ``` The advantage of this approach is that you won't run out of memory if both a and b are infinite.
How do I merge two python iterators?
243,865
16
2008-10-28T16:07:12Z
345,415
8
2008-12-05T22:39:29Z
[ "python", "merge", "iterator" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration ``` What is the simplest, most concise way to do this?
I also agree that itertools is not needed. But why stop at 2? ``` def tmerge(*iterators): for values in zip(*iterators): for value in values: yield value ``` handles any number of iterators from 0 on upwards. UPDATE: DOH! A commenter pointed out that this won't work unless all the iterators are the same length. The correct code is: ``` def tmerge(*iterators): empty = {} for values in itertools.izip_longest(*iterators, fillvalue=empty): for value in values: if value is not empty: yield value ``` and yes, I just tried it with lists of unequal length, and a list containing {}.
Which Eclipse package to download for pydev?
243,962
52
2008-10-28T16:33:20Z
243,981
26
2008-10-28T16:39:43Z
[ "python", "eclipse", "package", "pydev" ]
I'm getting started with python, eclipse and pydev. Which Eclipse package should I choose? Nothing on the eclipse homepage tells me what to choose and python documentation assumes I have eclipse installed. Does which package I choose matter?
If you just plan on doing Python dev, I'd just go with [Platform Runtime Binary](http://download.eclipse.org/eclipse/downloads/). After that, I'd follow the instructions <http://pydev.org/download.html> and <http://pydev.org/manual_101_root.html> to install PyDev. I use the same setup for Python development. I also have the RadRails plugin for Ruby on Rails development.
With Lua and Python embeddable, is there a place for Basic?
244,138
6
2008-10-28T17:27:32Z
244,304
10
2008-10-28T18:24:02Z
[ "python", "scripting", "lua", "interpreter", "basic" ]
I started off programming in Basic on the [ZX81](http://en.wikipedia.org/wiki/ZX81), then [BASICA](http://en.wikipedia.org/wiki/IBM_BASICA), [GW-BASIC](http://en.wikipedia.org/wiki/GW-BASIC), and [QBasic](http://en.wikipedia.org/wiki/QBasic). I moved on to C (Ah, Turbo C 3.1, I hardly knew ye...) When I got started in microcontrollers I regressed with the [BASIC Stamp](http://en.wikipedia.org/wiki/BASIC_Stamp) from Parallax. However, BASIC is/was awesome because it was so easy to understand and so hard to make a mistake. I moved on to assembly and C eventually because I needed the additional power (speed, capacity, resources, etc.), but I know that if the bar was much higher many people would never get into programming microcontrollers. I keep getting an itch to make my own on-chip BASIC interpretor, but I wonder if there's need for BASIC now that Lua and Python are easily embeddable, and just as approachable as BASIC. * What, if any, are the advantages BASIC has over other languages? * Why is it still around? * If I decide to make a general purpose microcontroller board with an interpreter, is there any reason to make a version of BASIC? Plenty of other languages are considered dead, but BASIC just keeps hanging on.
[This may come off sounding more negative than it really is. I'm not saying Basic is the root of all evil, [others have said that](http://en.wikiquote.org/wiki/Edsger_Dijkstra). I'm saying it's a legacy we can afford to leave behind.] **"because it was so easy to understand and so hard to make a mistake"** That's certainly debatable. I've had some bad experiences with utterly opaque basic. Professional stuff -- commercial products -- perfectly awful code. Had to give up and decline the work. **"What, if any, are the advantages Basic has over other languages?"** None, really. **"Why is it still around?"** Two reasons: (1) Microsoft, (2) all the IT departments that started doing VB and now have millions of lines of VB legacy code. **"Plenty of other languages are considered dead..."** Yep. Basic is there along side COBOL, PL/I and RPG as legacies that sometimes have more cost than value. But because of the "if it ain't broke don't fix it" policy of big IT, there they sit, sucking up resources who could easily replace it with something smaller, simpler and cheaper to maintain. Except it hasn't "failed" -- it's just disproportionately expensive. 30-year old COBOL is a horrible situation to rework. Starting in 2016 we'll be looking at 30-year old MS Basic that we just can't figure out, don't want to live without, and can't decide how to replace. **"but basic just keeps hanging on"** It appears that some folks love Basic. Others see it as yet another poorly-designed language; it's advantages are being early to market and being backed by huge vendors (IBM, initially). Poorly-design, early-to-market only leaves us with a legacy that we'll be suffering with for decades. I still have my 1965-edition Dartmouth Basic manual. I don't long for the good old days.
Map two lists into one single list of dictionaries
244,438
6
2008-10-28T19:06:54Z
244,551
13
2008-10-28T19:35:22Z
[ "python", "dictionary", "list" ]
Imagine I have these python lists: ``` keys = ['name', 'age'] values = ['Monty', 42, 'Matt', 28, 'Frank', 33] ``` Is there a direct or at least a simple way to produce the following list of dictionaries ? ``` [ {'name': 'Monty', 'age': 42}, {'name': 'Matt', 'age': 28}, {'name': 'Frank', 'age': 33} ] ```
Here is the zip way ``` def mapper(keys, values): n = len(keys) return [dict(zip(keys, values[i:i + n])) for i in range(0, len(values), n)] ```
AJAX console window with ANSI/VT100 support?
244,750
8
2008-10-28T20:32:24Z
244,823
9
2008-10-28T20:49:22Z
[ "python", "ajax", "vt100" ]
I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task? I'm thinking something like this: <http://tryruby.hobix.com/> My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.
Try [AnyTerm](http://wiki.kartbuilding.net/index.php/Anyterm) [AjaxTerm](http://wiki.kartbuilding.net/index.php/Ajaxterm) [WebShell](http://www-personal.umich.edu/~mressl/webshell/)
AJAX console window with ANSI/VT100 support?
244,750
8
2008-10-28T20:32:24Z
963,694
7
2009-06-08T06:47:26Z
[ "python", "ajax", "vt100" ]
I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task? I'm thinking something like this: <http://tryruby.hobix.com/> My preferred backend for the system is Python/Twisted/Pylons, but since I'm just planning, I will explore every option.
There's also [Shell In A Box](http://shellinabox.com).
What are "first class" objects?
245,192
85
2008-10-28T22:58:47Z
245,208
82
2008-10-28T23:04:22Z
[ "python", "language-agnostic" ]
When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not? EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?
In short, it means there are no restrictions on the object's use. It's the same as any other object. A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. > Depending on the language, this can > imply: > > * being expressible as an anonymous literal value > * being storable in variables > * being storable in data structures > * having an intrinsic identity (independent of any given name) > * being comparable for equality with other entities > * being passable as a parameter to a procedure/function > * being returnable as the result of a procedure/function > * being constructible at runtime > * being printable > * being readable > * being transmissible among distributed processes > * being storable outside running processes [Source](http://en.wikipedia.org/wiki/First-class_object). In C++ functions themselves are not first class objects, however: * You can override the '()' operator making it possible to have an object function, which is first class. * Function pointers are first class. * boost bind, lambda and function do offer first class functions In C++, classes are not first class objects but instances of those classes are. In Python both the classes *and* the objects are first class objects. (See [this answer](http://stackoverflow.com/a/6581949/1612701) for more details about classes as objects). Here is an example of Javascript first class functions: ``` // f: function that takes a number and returns a number // deltaX: small positive number // returns a function that is an approximate derivative of f function makeDerivative( f, deltaX ) { var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv; } var cos = makeDerivative( Math.sin, 0.000001); // cos(0) ~> 1 // cos(pi/2) ~> 0 ``` [Source](http://en.wikipedia.org/wiki/First-class_function). Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. **Regarding the edit:** > EDIT. When one says "everything is > an object" (like in Python), does he > indeed mean that "everything is > first-class"? The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class.
What are "first class" objects?
245,192
85
2008-10-28T22:58:47Z
245,209
14
2008-10-28T23:04:36Z
[ "python", "language-agnostic" ]
When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not? EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?
“First class” means you can operate on them in the usual manner. Most of the times, this just means you can pass these first-class citizens as arguments to functions, or return them from functions. This is self-evident for objects but not always so evident for functions, or even classes: ``` void f(int n) { return n * 2; } void g(Action<int> a, int n) { return a(n); } // Now call g and pass f: g(f, 10); // = 20 ``` This is an example in C# where functions actually *aren't* first-class objects. The above code therefore uses a small workaround (namely a generic delegate called `Action<>`) to pass a function as an argument. Other languages, such as Ruby, allow treating even classes and code blocks as normal variables (or in the case of Ruby, constants).
What are "first class" objects?
245,192
85
2008-10-28T22:58:47Z
245,295
9
2008-10-28T23:49:30Z
[ "python", "language-agnostic" ]
When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not? EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?
"When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?" Yes. Everything in Python is a proper object. Even things that are "primitive types" in other languages. You find that an object like `2` actually has a fairly rich and sophisticated interface. ``` >>> dir(2) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] ``` Because everything's a first-class object in Python, there are relatively few obscure special cases. In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and an class have to exist side-by-side. It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time. The type of `2` is the `type 'int'` object, which has methods, attributes and a type. ``` >>> type(2) <type 'int'> ``` The type of a built-in type like `int` is the `type 'type'` object. This has methods and attributes, also. ``` >>> type(type(2)) <type 'type'> ```
What are "first class" objects?
245,192
85
2008-10-28T22:58:47Z
417,721
7
2009-01-06T19:03:53Z
[ "python", "language-agnostic" ]
When are objects or something else said to be "first class" in a given programming language, and why? In what do they differ from languages where they are not? EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?
From a slide in [Structure and Interpretation of Computer Programs](http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/), lecture 2A (1986), which in turns quotes [Christopher Stracey](http://en.wikipedia.org/wiki/Christopher_Strachey): **The rights and privileges of first-class citizens:** * To be named by variables. * To be passed as arguments to procedures. * To be returned as values of procedures. * To be incorporated into data structures
Which library should I use to write an XLS from Linux / Python?
245,225
7
2008-10-28T23:11:54Z
245,275
16
2008-10-28T23:37:26Z
[ "java", "python", "xls", "jexcelapi", "hssf" ]
I'd love a *good* native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does. So I'm trying to decide between jexcelapi and Apache HSSF: <http://www.andykhan.com/jexcelapi/tutorial.html#writing> <http://poi.apache.org/hssf/quick-guide.html> (I can't use COM automation because I'm not on Windows, and even if I was, I couldn't afford Office licenses.) My initial thoughts are that POI/HSSF is very thorough, but also very Java-- everything seems a bit harder than it needs to be. Good documentation, but my head hurts trying to bridge the gap between what it describes and what I need to accomplish. jexcepapi seems to have a simpler, nicer (for me) interface, but doesn't have very good documentation or community. Which would you use, and why?
What's wrong with [xlwt](http://pypi.python.org/pypi/xlwt)?
Running Django with FastCGI or with mod_python
245,237
20
2008-10-28T23:16:23Z
245,660
21
2008-10-29T03:06:03Z
[ "python", "django", "apache", "fastcgi" ]
which would you recommend? which is faster, reliable? apache mod\_python or nginx/lighttpd FastCGI?
I've done both, and Apache/mod\_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod\_wsgi, which is everything I've ever wanted and more: * Easy management of daemon processes. * As a result, **much** better process isolation (running multiple sites in the same Apache config with mod\_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that). * Easy code reloads (set it up right and you can just touch the `.wsgi` file to reload instead of restarting Apache). * More predictable resource usage. With mod\_python, a given Apache child process' memory use can jump around a lot. With mod\_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use.
How do I get the name of a function or method from within a Python function or method?
245,304
36
2008-10-28T23:52:09Z
245,333
15
2008-10-29T00:07:24Z
[ "python" ]
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
This decorator makes the name of the method available inside the function by passing it as a keyword argument. ``` from functools import wraps def pass_func_name(func): "Name of decorated function will be passed as keyword arg _func_name" @wraps(func) def _pass_name(*args, **kwds): kwds['_func_name'] = func.func_name return func(*args, **kwds) return _pass_name ``` You would use it this way: ``` @pass_func_name def sum(a, b, _func_name): print "running function %s" % _func_name return a + b print sum(2, 4) ``` But maybe you'd want to write what you want directly inside the decorator itself. Then the code is an example of a way to get the function name in a decorator. If you give more details about what you want to do in the function, that requires the name, maybe I can suggest something else.
How do I get the name of a function or method from within a Python function or method?
245,304
36
2008-10-28T23:52:09Z
245,346
52
2008-10-29T00:13:35Z
[ "python" ]
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
This seems to be the simplest way using module `inspect`: ``` import inspect def somefunc(a,b,c): print "My name is: %s" % inspect.stack()[0][3] ``` You could generalise this with: ``` def funcname(): return inspect.stack()[1][3] def somefunc(a,b,c): print "My name is: %s" % funcname() ``` Credit to [Stefaan Lippens](http://stefaanlippens.net/python_inspect) which was found via google.
How do I get the name of a function or method from within a Python function or method?
245,304
36
2008-10-28T23:52:09Z
245,561
10
2008-10-29T01:58:33Z
[ "python" ]
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
``` # file "foo.py" import sys import os def LINE( back = 0 ): return sys._getframe( back + 1 ).f_lineno def FILE( back = 0 ): return sys._getframe( back + 1 ).f_code.co_filename def FUNC( back = 0): return sys._getframe( back + 1 ).f_code.co_name def WHERE( back = 0 ): frame = sys._getframe( back + 1 ) return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ), frame.f_lineno, frame.f_code.co_name ) def testit(): print "Here in %s, file %s, line %s" % ( FUNC(), FILE(), LINE() ) print "WHERE says '%s'" % WHERE() testit() ``` Output: ``` $ python foo.py Here in testit, file foo.py, line 17 WHERE says 'foo.py/18 testit()' ``` Use "back = 1" to find info regarding two levels back down the stack, etc.
How do I get the name of a function or method from within a Python function or method?
245,304
36
2008-10-28T23:52:09Z
245,581
21
2008-10-29T02:09:48Z
[ "python" ]
I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.
The answers involving introspection via `inspect` and the like are reasonable. But there may be another option, depending on your situation: If your integration test is written with the [unittest](http://docs.python.org/library/unittest.html) module, then you could use `self.id()` within your TestCase.
How do I draw text at an angle using python's PIL?
245,447
15
2008-10-29T01:04:48Z
245,892
22
2008-10-29T05:31:25Z
[ "python", "python-imaging-library", "imaging" ]
Using Python I want to be able to draw text at different angles using PIL. For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees. Therefore, I need to be able to draw many different strings at many different angles.
Draw text into a temporary blank image, rotate that, then paste that onto the original image. You could wrap up the steps in a function. Good luck figuring out the exact coordinates to use - my cold-fogged brain isn't up to it right now. This demo writes yellow text on a slant over an image: ``` # Demo to add rotated text to an image using PIL import Image import ImageFont, ImageDraw, ImageOps im=Image.open("stormy100.jpg") f = ImageFont.load_default() txt=Image.new('L', (500,50)) d = ImageDraw.Draw(txt) d.text( (0, 0), "Someplace Near Boulder", font=f, fill=255) w=txt.rotate(17.5, expand=1) im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w) ```
How do I draw text at an angle using python's PIL?
245,447
15
2008-10-29T01:04:48Z
741,592
7
2009-04-12T10:48:23Z
[ "python", "python-imaging-library", "imaging" ]
Using Python I want to be able to draw text at different angles using PIL. For example, imagine you were drawing the number around the face of a clock. The number **3** would appear as expected whereas **12** would we drawn rotated counter-clockwise 90 degrees. Therefore, I need to be able to draw many different strings at many different angles.
It's also usefull to know our text's size in pixels before we create an Image object. I used such code when drawing graphs. Then I got no problems e.g. with alignment of data labels (the image is exactly as big as the text). ``` (...) img_main = Image.new("RGB", (200, 200)) font = ImageFont.load_default() # Text to be rotated... rotate_text = u'This text should be rotated.' # Image for text to be rotated img_txt = Image.new('L', font.getsize(rotate_text)) draw_txt = ImageDraw.Draw(img_txt) draw_txt.text((0,0), rotate_text, font=font, fill=255) t = img_value_axis.rotate(90, expand=1) ``` The rest of joining the two images together is already described on this page. When you rotate by an "unregular" angle, you have to improve this code a little bit. It actually works for 90, 180, 270...
When is not a good time to use python generators?
245,792
55
2008-10-29T04:25:02Z
245,797
16
2008-10-29T04:28:58Z
[ "python", "optimization", "iterator", "generator" ]
This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. **So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?** * When should I prefer `zip()` over `itertools.izip()`, or * `range()` over `xrange()`, or * `[x for x in foo]` over `(x for x in foo)`? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
You should never favor [`zip`](http://docs.python.org/2/library/functions.html#zip) over [`izip`](http://docs.python.org/2/library/itertools.html#itertools.izip), `range` over `xrange`, or list comprehensions over generator comprehensions. In Python 3.0 `range` has `xrange`-like semantics and `zip` has `izip`-like semantics. List comprehensions are actually clearer like `list(frob(x) for x in foo)` for those times you need an actual list.
When is not a good time to use python generators?
245,792
55
2008-10-29T04:25:02Z
245,816
33
2008-10-29T04:42:05Z
[ "python", "optimization", "iterator", "generator" ]
This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. **So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?** * When should I prefer `zip()` over `itertools.izip()`, or * `range()` over `xrange()`, or * `[x for x in foo]` over `(x for x in foo)`? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
In general, don't use a generator when you need list operations, like len(), reversed(), and so on. There may also be times when you don't want lazy evaluation (e.g. to do all the calculation up front so you can release a resource). In that case, a list expression might be better.
When is not a good time to use python generators?
245,792
55
2008-10-29T04:25:02Z
246,481
21
2008-10-29T11:37:31Z
[ "python", "optimization", "iterator", "generator" ]
This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. **So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?** * When should I prefer `zip()` over `itertools.izip()`, or * `range()` over `xrange()`, or * `[x for x in foo]` over `(x for x in foo)`? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
Profile, Profile, Profile. Profiling your code is the only way to know if what you're doing has any effect at all. Most usages of xrange, generators, etc are over static size, small datasets. It's only when you get to large datasets that it really makes a difference. range() vs. xrange() is mostly just a matter of making the code look a tiny little bit more ugly, and not losing anything, and maybe gaining something. Profile, Profile, Profile.
When is not a good time to use python generators?
245,792
55
2008-10-29T04:25:02Z
26,635,939
24
2014-10-29T16:36:57Z
[ "python", "optimization", "iterator", "generator" ]
This is rather the inverse of [What can you use Python generator functions for?](http://stackoverflow.com/questions/102535/what-can-you-use-python-generator-functions-for): python generators, generator expressions, and the `itertools` module are some of my favorite features of python these days. They're especially useful when setting up chains of operations to perform on a big pile of data--I often use them when processing DSV files. **So when is it *not* a good time to use a generator, or a generator expression, or an `itertools` function?** * When should I prefer `zip()` over `itertools.izip()`, or * `range()` over `xrange()`, or * `[x for x in foo]` over `(x for x in foo)`? Obviously, we eventually need to "resolve" a generator into actual data, usually by creating a list or iterating over it with a non-generator loop. Sometimes we just need to know the length. This isn't what I'm asking. We use generators so that we're not assigning new lists into memory for interim data. This especially makes sense for large datasets. Does it make sense for small datasets too? Is there a noticeable memory/cpu trade-off? I'm especially interested if anyone has done some profiling on this, in light of the eye-opening discussion of [list comprehension performance vs. map() and filter()](http://www.gossamer-threads.com/lists/python/python/76267). ([alt link](https://mail.python.org/pipermail//python-list/2001-December/096256.html))
**Use a list instead of a generator when:** 1) You need to access the data **multiple** times (i.e. cache the results instead of recomputing them): ``` for i in outer: # used once, okay to be a generator or return a list for j in inner: # used multiple times, reusing a list is better ... ``` 2) You need **random access** (or any access other than forward sequential order): ``` for i in reversed(data): ... # generators aren't reversible s[i], s[j] = s[j], s[i] # generators aren't indexable ``` 3) You need to **join** strings (which requires two passes over the data): ``` s = ''.join(data) # lists are faster than generators in this use case ``` 4) You are using **PyPy** which sometimes can't optimize generator code as much as it can with normal function calls and list manipulations.
How can I draw a bezier curve using Python's PIL?
246,525
11
2008-10-29T11:59:08Z
246,628
10
2008-10-29T12:39:15Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
A bezier curve isn't that hard to draw yourself. Given three points `A`, `B`, `C` you require three linear interpolations in order to draw the curve. We use the scalar `t` as the parameter for the linear interpolation: ``` P0 = A * t + (1 - t) * B P1 = B * t + (1 - t) * C ``` This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so: ``` Pfinal = P0 * t + (1 - t) * P1 ``` There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some `dt` (delta t) and we need to be aware that `0 <= t <= 1`. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.
How can I draw a bezier curve using Python's PIL?
246,525
11
2008-10-29T11:59:08Z
246,933
7
2008-10-29T14:09:59Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
You can use the [aggdraw](http://effbot.org/zone/aggdraw-index.htm) on top of PIL, bezier curves are [supported](http://effbot.org/zone/pythondoc-aggdraw.htm#aggdraw.Path-class). **EDIT:** I made an example only to discover there is a bug in the `Path` class regarding `curveto` :( Here is the example anyway: ``` from PIL import Image import aggdraw img = Image.new("RGB", (200, 200), "white") canvas = aggdraw.Draw(img) pen = aggdraw.Pen("black") path = aggdraw.Path() path.moveto(0, 0) path.curveto(0, 60, 40, 100, 100, 100) canvas.path(path.coords(), path, pen) canvas.flush() img.save("curve.png", "PNG") img.show() ``` [This](http://www.mail-archive.com/[email protected]/msg02108.html) should fix the bug if you're up for recompiling the module...
How can I draw a bezier curve using Python's PIL?
246,525
11
2008-10-29T11:59:08Z
2,292,690
16
2010-02-18T22:23:02Z
[ "python", "python-imaging-library", "bezier", "imaging" ]
I'm using Python's Imaging Library and I would like to draw some bezier curves. I guess I could calculate pixel by pixel but I'm hoping there is something simpler.
``` def make_bezier(xys): # xys should be a sequence of 2-tuples (Bezier control points) n = len(xys) combinations = pascal_row(n-1) def bezier(ts): # This uses the generalized formula for bezier curves # http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization result = [] for t in ts: tpowers = (t**i for i in range(n)) upowers = reversed([(1-t)**i for i in range(n)]) coefs = [c*a*b for c, a, b in zip(combinations, tpowers, upowers)] result.append( tuple(sum([coef*p for coef, p in zip(coefs, ps)]) for ps in zip(*xys))) return result return bezier def pascal_row(n): # This returns the nth row of Pascal's Triangle result = [1] x, numerator = 1, n for denominator in range(1, n//2+1): # print(numerator,denominator,x) x *= numerator x /= denominator result.append(x) numerator -= 1 if n&1 == 0: # n is even result.extend(reversed(result[:-1])) else: result.extend(reversed(result)) return result ``` This, for example, draws a heart: ``` from PILL import Image from PIL import ImageDraw if __name__ == '__main__': im = Image.new('RGBA', (100, 100), (0, 0, 0, 0)) draw = ImageDraw.Draw(im) ts = [t/100.0 for t in range(101)] xys = [(50, 100), (80, 80), (100, 50)] bezier = make_bezier(xys) points = bezier(ts) xys = [(100, 50), (100, 0), (50, 0), (50, 35)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(50, 35), (50, 0), (0, 0), (0, 50)] bezier = make_bezier(xys) points.extend(bezier(ts)) xys = [(0, 50), (20, 80), (50, 100)] bezier = make_bezier(xys) points.extend(bezier(ts)) draw.polygon(points, fill = 'red') im.save('out.png') ```
How do I add tab completion to the Python shell?
246,725
55
2008-10-29T13:09:10Z
246,774
30
2008-10-29T13:21:43Z
[ "python", "shell", "interpreter" ]
When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc. ``` Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) ``` When just starting a python interpreter using `python`, it doesn't offer tab completion. Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
I think django does something like <https://docs.python.org/library/rlcompleter.html> If you want to have a really good interactive interpreter have a look at <http://ipython.scipy.org/>.
How do I add tab completion to the Python shell?
246,725
55
2008-10-29T13:09:10Z
246,779
91
2008-10-29T13:24:39Z
[ "python", "shell", "interpreter" ]
When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc. ``` Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) ``` When just starting a python interpreter using `python`, it doesn't offer tab completion. Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
I may have found a way to do it. Create a file .pythonrc ``` # ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") ``` then in your .bashrc file, add ``` export PYTHONSTARTUP=~/.pythonrc ``` That seems to work.
How do I add tab completion to the Python shell?
246,725
55
2008-10-29T13:09:10Z
247,513
21
2008-10-29T16:39:03Z
[ "python", "shell", "interpreter" ]
When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc. ``` Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) ``` When just starting a python interpreter using `python`, it doesn't offer tab completion. Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
For the record, this is covered in the tutorial: <http://docs.python.org/tutorial/interactive.html>
How can I launch an instance of an application using Python?
247,724
11
2008-10-29T17:40:12Z
247,740
8
2008-10-29T17:44:31Z
[ "python", "scripting", "ipc" ]
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
or ``` os.system("start excel.exe <path/to/file>") ``` (presuming it's in the path, and you're on windows) and also on Windows, just `start <filename>` works, too - if it's an associated extension already (as xls would be)
How can I launch an instance of an application using Python?
247,724
11
2008-10-29T17:40:12Z
248,080
10
2008-10-29T19:22:09Z
[ "python", "scripting", "ipc" ]
I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?
While the `Popen` answers are reasonable for the general case, I would recommend `win32api` for this specific case, if you want to do something useful with it: It goes something like this: ``` from win32com.client import Dispatch xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls') xl.Visible = True # optional: if you want to see the spreadsheet ``` Taken from [a mailing list post](https://mail.python.org/pipermail/python-list/2005-June/315330.html) but there are plenty of examples around.
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
248,066
13
2008-10-29T19:18:15Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
This was trivial. Each module has a `__file__` variable that shows its relative path from where you are right now. Therefore, getting a directory for the module to notify it is simple as: ``` os.path.dirname(__file__) ```
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
248,862
385
2008-10-29T23:57:13Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
``` import a_module print a_module.__file__ ``` Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do ``` import os path = os.path.dirname(amodule.__file__) ``` You can also try ``` path = os.path.abspath(amodule.__file__) ``` To get the directory to look for changes.
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
4,431,672
12
2010-12-13T17:35:17Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
``` import os path = os.path.abspath(__file__) dir_path = os.path.dirname(path) ```
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
6,416,114
49
2011-06-20T19:05:40Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
As the other answers have said, the best way to do this is with `__file__` (demonstrated again below). However, there is an important caveat, which is that `__file__` does NOT exist if you are running the module on its own (i.e. as `__main__`). For example, say you have two files (both of which are on your PYTHONPATH): ``` #/path1/foo.py import bar print bar.__file__ ``` and ``` #/path2/bar.py import os print os.getcwd() print __file__ ``` Running foo.py will give the output: ``` /path1 # "import bar" causes the line "print os.getcwd()" to run /path2/bar.py # then "print __file__" runs /path2/bar.py # then the import statement finishes and "print bar.__file__" runs ``` HOWEVER if you try to run bar.py on its own, you will get: ``` /path2 # "print os.getcwd()" still works fine Traceback (most recent call last): # but __file__ doesn't exist if bar.py is running as main File "/path2/bar.py", line 3, in <module> print __file__ NameError: name '__file__' is not defined ``` Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
12,154,601
121
2012-08-28T07:24:09Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
There is `inspect` module in python. ## [Official documentation](http://docs.python.org/library/inspect.html) > The inspect module provides several useful functions to help get > information about live objects such as modules, classes, methods, > functions, tracebacks, frame objects, and code objects. For example, > it can help you examine the contents of a class, retrieve the source > code of a method, extract and format the argument list for a function, > or get all the information you need to display a detailed traceback. Example: ``` >>> import os >>> import inspect >>> inspect.getfile(os) '/usr/lib64/python2.7/os.pyc' >>> inspect.getfile(inspect) '/usr/lib64/python2.7/inspect.pyc' >>> os.path.dirname(inspect.getfile(inspect)) '/usr/lib64/python2.7' ```
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
16,826,913
22
2013-05-30T02:15:40Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
I will try tackling a few variations on this question as well: 1. finding the path of the called script 2. finding the path of the currently executing script 3. finding the directory of the called script (Some of these questions have been asked on SO, but have been closed as duplicates and redirected here.) ## Caveats of Using `__file__` For a module that you have imported: ``` import something something.__file__ ``` will return the **absolute** path of the module. However, given the folowing script foo.py: ``` #foo.py print '__file__', __file__ ``` Calling it with 'python foo.py' Will return simply 'foo.py'. If you add a shebang: ``` #!/usr/bin/python #foo.py print '__file__', __file__ ``` and call it using ./foo.py, it will return './foo.py'. Calling it from a different directory, (eg put foo.py in directory bar), then calling either ``` python bar/foo.py ``` or adding a shebang and executing the file directly: ``` bar/foo.py ``` will return 'bar/foo.py' (the **relative** path). ## Finding the directory Now going from there to get the directory, `os.path.dirname(__file__)` can also be tricky. At least on my system, it returns an empty string if you call it from the same directory as the file. ex. ``` # foo.py import os print '__file__ is:', __file__ print 'os.path.dirname(__file__) is:', os.path.dirname(__file__) ``` will output: ``` __file__ is: foo.py os.path.dirname(__file__) is: ``` In other words, it returns an empty string, so this does not seem reliable if you want to use it for the current **file** (as opposed to the **file** of an imported module). To get around this, you can wrap it in a call to abspath: ``` # foo.py import os print 'os.path.abspath(__file__) is:', os.path.abspath(__file__) print 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__)) ``` which outputs something like: ``` os.path.abspath(__file__) is: /home/user/bar/foo.py os.path.dirname(os.path.abspath(__file__)) is: /home/user/bar ``` Note that abspath() does NOT resolve symlinks. If you want to do this, use realpath() instead. For example, making a symlink file\_import\_testing\_link pointing to file\_import\_testing.py, with the following content: ``` import os print 'abspath(__file__)',os.path.abspath(__file__) print 'realpath(__file__)',os.path.realpath(__file__) ``` executing will print absolute paths something like: ``` abspath(__file__) /home/user/file_test_link realpath(__file__) /home/user/file_test.py ``` file\_import\_testing\_link -> file\_import\_testing.py ## Using inspect @SummerBreeze mentions using the [inspect](http://docs.python.org/2/library/inspect.html) module. This seems to work well, and is quite concise, for imported modules: ``` import os import inspect print 'inspect.getfile(os) is:', inspect.getfile(os) ``` obediently returns the absolute path. However for finding the path of the currently executing script, I did not see a way to use it.
Retrieving python module path
247,770
351
2008-10-29T17:52:40Z
28,976,381
10
2015-03-11T00:10:44Z
[ "python", "module", "inotify" ]
I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?
I don't get why no one is talking about this, but to me the simplest solution is using **imp.find\_module("modulename")** (documentation [here](https://docs.python.org/2/library/imp.html?highlight=import#module-imp)): ``` import imp imp.find_module("os") ``` It gives a tuple with the path in second position: ``` (<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>, '/usr/lib/python2.7/os.py', ('.py', 'U', 1)) ``` The advantage of this method over the "inspect" one is that you don't need to import the module to make it work, and you can use a string in input. Useful when checking modules called in another script for example. **EDIT**: In python3, `importlib` module should do: Doc of `importlib.util.find_spec`: > Return the spec for the specified module. > > First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].**spec** is returned. If that happens to be > set to None, then ValueError is raised. If the module is not in > sys.modules, then sys.meta\_path is searched for a suitable spec with the > value of 'path' given to the finders. None is returned if no spec could > be found. > > If the name is for submodule (contains a dot), the parent module is > automatically imported. > > The name and package arguments work the same as importlib.import\_module(). > In other words, relative module names (with leading dots) work.
Is there something between a normal user account and root?
248,730
3
2008-10-29T23:02:30Z
248,758
7
2008-10-29T23:11:01Z
[ "python", "linux", "root" ]
I'm developing an application that manages network interfaces on behalf of the user and it calls out to several external programs (such as ifconfig) that requires root to make changes. (Specifically, changing the IP address of a local interface, etc.) During development, I have been running the IDE as root (ugh) and the debugger as root (double-ugh). Is there a nice way for the end-user to run these under a non-root account? I strongly dislike the size of the attack surface presented by GTK, wxPython, Python, and my application when it runs as root. I have looked into capabilities, but they look half-baked and I'm not sure if I'd be able to use them in Python, especially if they are on a thread basis. The only option I haven't explored is a daemon that has the setuid bit set and does all the root-type stuff on behalf of the UI. I'm hesitant to introduce that complexity this early in the project, as running as root is not a dealbreaker for the users.
Your idea about the daemon has much merit, despite the complexity it introduces. As long as the actions don't require some user interface interaction *as root*, a daemon allows you to control what operations are allowed and disallowed. However, you can use SUDO to create a controlled compromise between ROOT and normal users... simply grant SUDO access to the users in question for the specific tools they need. That reduces the attack surface by allowing only "permitted" root launches.
Python: using a recursive algorithm as a generator
248,830
79
2008-10-29T23:45:56Z
248,854
96
2008-10-29T23:53:47Z
[ "python", "recursion", "generator" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: ``` def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation ``` (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation ``` This code does *not* work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator *without replacing it with an iterative one*?
``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]): yield perm ``` Or without an accumulator: ``` def getPermutations(string): if len(string) == 1: yield string else: for i in xrange(len(string)): for perm in getPermutations(string[:i] + string[i+1:]): yield string[i] + perm ```
Python: using a recursive algorithm as a generator
248,830
79
2008-10-29T23:45:56Z
248,857
19
2008-10-29T23:54:51Z
[ "python", "recursion", "generator" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: ``` def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation ``` (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation ``` This code does *not* work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator *without replacing it with an iterative one*?
The interior call to getPermutations -- it's a generator, too. ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) # <----- ``` You need to iterate through that with a for-loop (see @MizardX posting, which edged me out by seconds!)
Python: using a recursive algorithm as a generator
248,830
79
2008-10-29T23:45:56Z
252,199
24
2008-10-31T00:05:38Z
[ "python", "recursion", "generator" ]
Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences. Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one: ``` def getPermutations(string, storage, prefix=""): if len(string) == 1: storage.append(prefix + string) # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], storage, prefix+string[i]) storage = [] getPermutations("abcd", storage) for permutation in storage: print permutation ``` (Please don't care about inefficiency, this is only an example.) Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string # <----- else: for i in range(len(string)): getPermutations(string[:i]+string[i+1:], prefix+string[i]) for permutation in getPermutations("abcd"): print permutation ``` This code does *not* work (the function behaves like an empty generator). Am I missing something? Is there a way to turn the above recursive algorithm into a generator *without replacing it with an iterative one*?
This avoids the `len(string)`-deep recursion, and is in general a nice way to handle generators-inside-generators: ``` from types import GeneratorType def flatten(*stack): stack = list(stack) while stack: try: x = stack[0].next() except StopIteration: stack.pop(0) continue if isinstance(x, GeneratorType): stack.insert(0, x) else: yield x def _getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: yield (_getPermutations(string[:i]+string[i+1:], prefix+string[i]) for i in range(len(string))) def getPermutations(string): return flatten(_getPermutations(string)) for permutation in getPermutations("abcd"): print permutation ``` `flatten` allows us to continue progress in another generator by simply `yield`ing it, instead of iterating through it and `yield`ing each item manually. --- Python 3.3 will add [`yield from`](http://docs.python.org/dev/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator) to the syntax, which allows for natural delegation to a sub-generator: ``` def getPermutations(string, prefix=""): if len(string) == 1: yield prefix + string else: for i in range(len(string)): yield from getPermutations(string[:i]+string[i+1:], prefix+string[i]) ```
I need a really good reason to use Python
249,064
10
2008-10-30T01:59:48Z
249,075
12
2008-10-30T02:04:09Z
[ "python" ]
I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like [IronRuby](http://en.wikipedia.org/wiki/Ironruby) and [IronPython](http://en.wikipedia.org/wiki/Ironpython), I started seriously investigating. I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would **require** a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just *because* doesn't quite work. Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects? Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages. Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason.
Almost no problem **requires** a specific programming language, that's just not how things work. The easiest way to get a new language into an environment like yours is to start a new work project in your own time in the new language. Make it do something you need doing, and write it on your own time. Use it yourself, and other people will probably notice it. They then say "Can you send me that program?" and boom, they're using your new language. If you really want to something, I would probably write a site in Django, simply because its admin interface blows everyone away. The main point to remember is that if you start using python, that's one more thing everyone else has to learn, and it's another bullet point that will need to be on every prospective employee's resume. That can get expensive, and management won't like it.
I need a really good reason to use Python
249,064
10
2008-10-30T01:59:48Z
249,101
28
2008-10-30T02:12:10Z
[ "python" ]
I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like [IronRuby](http://en.wikipedia.org/wiki/Ironruby) and [IronPython](http://en.wikipedia.org/wiki/Ironpython), I started seriously investigating. I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would **require** a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just *because* doesn't quite work. Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects? Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages. Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason.
"Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?" Nope. Nothing succeeds like success. Use Python. Be successful. Make people jealous. When asked why you're successful, you can talk about Python. Not before. Choose projects wisely: things where a dynamic language has significant advantages. Things where the requirements are **not** nailed down in detail. Things like data transformations, log-file scraping, and super-sophisticated replacements for BAT files. Use Python to get started doing something useful while everyone else is standing around trying to get enough business and domain information to launch a project to develop a complicated MVC design. --- Edit: Some Python to the Rescue stories. * [Exploratory Programming](http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081005191603/index.html) * [Tooling to build test cases](http://homepage.mac.com/s_lott/iblog/architecture/C20071019092637/E20080830091128/index.html) * [What's Central Here?](http://homepage.mac.com/s_lott/iblog/architecture/C465799452/E20080712112540/index.html) * [Control-Break Reporting](http://homepage.mac.com/s_lott/iblog/architecture/C588245363/E20060206184914/index.html) * [One More Cool Thing About Python Is...](http://homepage.mac.com/s_lott/iblog/architecture/C588245363/E20051022112554/index.html) * [In Praise of Serialization](http://homepage.mac.com/s_lott/iblog/architecture/C465799452/E20080603055001/index.html) And that's just me. --- Edit: "boss prompted ME to investigate", "figure out how we can use it" changes everything. The "finally convince my boss to really learn Python" is misleading. You aren't swimming upstream. See [How Do I Make the Business Case for Python](http://stackoverflow.com/questions/202337/how-do-i-make-the-business-case-for-python) for the "convince my boss" problem. The edit says you're past this phase. Dynamic languages offer flexibility. Exploit that. My two sets of examples above are two areas where flexibility matters. * Requirements aren't totally nailed down. With a dynamic language, you can get started. Rework won't be a deal-breaker. With Java (and C++ and C#) you are reluctant to tackle devastating design changes because it's hard to break everything and get it to compile and work again. In Python, devastating changes aren't as expensive. * Design is in flux because you can't pick components. You can write Wrappers and Facades very easily in Python. It's a scripting language. And, Python modules compose into larger aggregates very simply. * Coding is in flux because requirements and design keep changing. It's scripted -- not compiled. You just make a change to the code and you're off and running. Testing is easier because the work cycle is shorter. It isn't code-compile-build-test it's code-test. * Testing is in flux because the requirements keep changing. Same as above. The work cycle is shorter and faster.
Django: Arbitrary number of unnamed urls.py parameters
249,110
16
2008-10-30T02:18:32Z
249,524
11
2008-10-30T07:52:30Z
[ "python", "django", "django-urls" ]
I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: ``` /browse/<name1>/<value1>/<name2>/<value2>/ .... etc .... ``` where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match. Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs. Ideally each name/value pair will be passed to the view function as a parameter named `name1`, `name2`, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there? So, it seems I need to do something like this: ``` urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) ``` It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead: ``` urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) ``` ... and got the same problem, but this time `*args` only includes the last matched pattern. Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.\*) pattern?
A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example: ``` urlpatterns = patterns('', url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'), ) def view(request, match): pieces = match.split('/') # even indexed pieces are the names, odd are values ... ``` No promises about the regexp I used, but I think you understand what I mean. (Edited to try and fix the regexp.)
Virtualenv on Ubuntu with no site-packages
249,283
24
2008-10-30T04:32:52Z
1,670,513
34
2009-11-03T22:20:07Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system. What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?
``` $ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ $ ln -s /usr/lib/pymodules/python2.6/pygtk.pth $ ln -s /usr/lib/pymodules/python2.6/pygtk.py $ ln -s /usr/lib/pymodules/python2.6/cairo/ $ python >>> import pygtk >>> import gtk ```
How to determine if a directory is on same partition
249,775
6
2008-10-30T10:45:42Z
249,796
11
2008-10-30T10:54:11Z
[ "python", "linux", "osx", "filesystems" ]
Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory? What I want to do is the copy a file if it's on a different, but move it if it's the same. For example: ``` target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) ``` --- Thanks to CesarB's answer, the `same_partition` function implemented: ``` import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev ```
In C, you would use `stat()` and compare the `st_dev` field. In python, `os.stat` should do the same.
How can I add post-install scripts to easy_install / setuptools / distutils?
250,038
30
2008-10-30T12:42:10Z
253,103
7
2008-10-31T10:33:46Z
[ "python", "setuptools", "distutils" ]
I would like to be able to add a hook to my setup.py that will be run post-install (either when easy\_install'ing or when doing python setup.py install). In my project, [PySmell](http://code.google.com/p/pysmell), I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them. What is the best way to do this? Thanks My setup.py looks like so: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = '[email protected]', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) ``` EDIT: Here's a stub which demonstrates the `python setup.py install`: ``` from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... ``` No luck with the easy\_install route yet.
It depends on how the user installs your package. If the user actually runs "setup.py install", it's fairly easy: Just add another subcommand to the install command (say, install\_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub\_commands, and pass the command into setup(). If you want a post-install script in a binary, it depends on the type of binary you are creating. For example, bdist\_rpm, bdist\_wininst, and bdist\_msi have support for post-install scripts, because the underlying packing formats support post-install scripts. bdist\_egg doesn't support a post-install mechanism by design: <http://bugs.python.org/setuptools/issue41>
Lua as a general-purpose scripting language?
250,151
33
2008-10-30T13:21:41Z
250,158
10
2008-10-30T13:24:26Z
[ "python", "scripting", "lua" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
Just because it is "marketed" (in some general sense) as a special-purpose language for embedded script engines, does not mean that it is limited to that. In fact, WoW could probably just as well have chosen Python as their embedded scripting language.
Lua as a general-purpose scripting language?
250,151
33
2008-10-30T13:21:41Z
250,168
9
2008-10-30T13:28:04Z
[ "python", "scripting", "lua" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
It's probably because Lua was designed as a scripting and extension language. On the [official site](http://www.lua.org/about.html) it's described as a powerful, fast, light-weight, embeddable scripting language. There's nothing stopping you from writing general purpose programs for it (if I recall correctly it ships with an interpreter and compiler), but the language designers intended it to be used mainly as an embedded language (hence being light-weight and all)
Lua as a general-purpose scripting language?
250,151
33
2008-10-30T13:21:41Z
252,900
33
2008-10-31T08:48:29Z
[ "python", "scripting", "lua" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
Lua is a cool language, light-weight and extremely fast! But the point is: **Is performance so important for those tasks you mentioned?** * Renaming a bunch of files * Download some files from the web * Webscraping You write those programs once, and run them once, too maybe. Why do you care about performance so much for a run-once program? For example: 1. Cost 3 hours to write a C/C++ program, to handle data once, the program will take 1 hour to run. 2. Cost 30 Minute to write a Python program to handle data once, the program will take 10 hours to run. If you choose the first, you save the time to run the program, but you cost your time to develop the program. On the other hand, if you choose the second, you waste time to run the program, but you can do other things when the program is running. **How about play World of Warcraft, kill monsters with your warlock? Eat my D.O.T**! :P That's it! Although Lua is not so difficult to write, everything about Lua is designed to be efficient.And what's more, there are little modules for Lua, but there are so many modules for Python. You don't want to port a C library for Lua just for a run-once program, do you? Instead, choose Python and use those module to achieve your task easily might be a better idea. FYI: Actually, I have tried to use Lua to do webscraping, but finally, I realized I do not have to care so much about language performance. **The bottleneck of webscraping is not on the performance of the language**. The bottleneck is on network I/O, HTML parsing and multitasking. All I have to do is make sure the program works and find the bottleneck. Finally, I chose Python rather than Lua. There is so many excellent Python modules; I have no reason to build my own. According to my experience about webscraping, I chose Twisted for network I/O and lxml for html parsing as the backend of my webscraping program. I have wrote an article for an introduction to this technology. [The best choice to grab data from websites: Python + Twisted + lxml](http://blog.ez2learn.com/2009/09/26/the-best-choice-to-grab-data-from-websites-python-twisted-lxml/) Hope this is helpful.
Lua as a general-purpose scripting language?
250,151
33
2008-10-30T13:21:41Z
253,755
21
2008-10-31T14:40:55Z
[ "python", "scripting", "lua" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
Lua has fewer libraries than Python. But be sure to have a look at [LuaForge](http://luaforge.net/). It has a lot of interesting libs, like [LuaCURL](http://luaforge.net/projects/luacurl/), [wxLua](http://wxlua.sourceforge.net/) or [getopt](http://luaforge.net/projects/getopt/). Then, visit [LuaRocks](http://luarocks.org/), the package management system for Lua. With it, you can search and install most mature Lua modules with dependencies. It feels like [RubyGems](http://en.wikipedia.org/wiki/RubyGems) or [aptitude](http://en.wikipedia.org/wiki/Aptitude%5F%28software%29). The site [lua-users.org](http://lua-users.org/) has a lot of interesting resources too, like tutorials or the [Lua Wiki](http://lua-users.org/wiki). What I like about Lua is not its speed, it's its minimal core language, flexibility and extensibility. That said, I would probably use Python for the tasks you mentionned because of the larger community doing such things in Python.
Lua as a general-purpose scripting language?
250,151
33
2008-10-30T13:21:41Z
326,660
8
2008-11-28T20:56:38Z
[ "python", "scripting", "lua" ]
When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW". Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl? Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example: * Renaming a bunch of files * Download some files from the web * Webscraping Is it the lack of the standard library?
This is a sociological question, not a programming question. I use Lua for general-purpose scripting almost exclusively. But I had to write a few hundred lines of code so that Lua would play better with the shell. This included such tricks as * Quoting a string so it is seen as one word by the shell * Writing a function to capture the output of a command as in shell $(command) * Writing a function to crawl the filesystem using the Lua posix library and expand shell globbing patterns (For those who may be interested, I've left the code in my [Lua drop box](http://www.cs.tufts.edu/~nr/drop/lua/), which also contains some other stuff. The interesting stuff is probably in `osutil` in `os.quote`, `os.runf`, `os.capture`, and maybe `os.execve`. The globbing is in [`posixutil.lua`](http://www.cs.tufts.edu/~nr/drop/lua/posixutil.lua). They both use Luiz Henrique de Figuereido's [Lua Posix library](http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/).) To me, the extra effort is worth it because I can deal with simple syntax and great data structures. To others, a more direct connection with the shell might be preferred.
How can I optimize this Google App Engine code?
250,209
5
2008-10-30T13:40:19Z
250,395
7
2008-10-30T14:41:19Z
[ "python", "google-app-engine", "optimization" ]
I'm relatively new to the python world, but this seems very straight forward. Google is yelling at me that this code needs to be optimized: ``` class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) ``` The dashboard is telling me that this is using a ton of CPU. Where should I look for improvements?
The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty. If you do need an entity for each link, try this: ``` # For each line in the input, add to the database groups = [] for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x groups.append(newGroup) db.put(groups) ``` It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.
Python Regex - How to Get Positions of Matches
250,271
50
2008-10-30T14:04:33Z
250,303
65
2008-10-30T14:15:39Z
[ "python", "regex" ]
How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too).
``` import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print m.start(), m.group() ```
Python Regex - How to Get Positions of Matches
250,271
50
2008-10-30T14:04:33Z
250,306
27
2008-10-30T14:16:02Z
[ "python", "regex" ]
How can I get the start and end positions of all matches using the `re` module? For example given the pattern `r'[a-z]'` and the string `'a1b2c3d4'` I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too).
Taken from [*Regular Expression HOWTO*](http://docs.python.org/3.3/howto/regex.html) > span() returns both start and end indexes in a single tuple. Since the > match method only checks if the RE matches at the start of a string, > start() will always be zero. However, the search method of RegexObject > instances scans through the string, so the match may not start at zero > in that case. ``` >>> p = re.compile('[a-z]+') >>> print p.match('::: message') None >>> m = p.search('::: message') ; print m <re.MatchObject instance at 80c9650> >>> m.group() 'message' >>> m.span() (4, 11) ``` Combine that with: In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator. ``` >>> p = re.compile( ... ) >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') >>> iterator <callable-iterator object at 0x401833ac> >>> for match in iterator: ... print match.span() ... (0, 2) (22, 24) (29, 31) ``` you should be able to do something on the order of ``` for match in re.finditer(r'[a-z]', 'a1b2c3d4'): print match.span() ```
How to scp in python?
250,283
97
2008-10-30T14:09:21Z
250,786
11
2008-10-30T16:18:00Z
[ "python", "ssh", "scp" ]
What's the most pythonic way to scp a file in Python? The only route I'm aware of is ``` os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) ``` which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted's `conch`, but I'd prefer to avoid implementing scp myself via low-level ssh modules. I'm aware of `paramiko`, a Python module that supports ssh and sftp; but it doesn't support scp. Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option. **EDIT**: This is a duplicate of <http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh>. **However**, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like ``` import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') ```
You might be interested in trying [Pexpect](http://www.noah.org/wiki/Pexpect) ([SourceForge project](http://sourceforge.net/projects/pexpect/)). This would allow you to deal with interactive prompts for your password. Here's a snip of example usage (for ftp) from the main website: ``` # This connects to the openbsd ftp site and # downloads the recursive directory listing. import pexpect child = pexpect.spawn ('ftp ftp.openbsd.org') child.expect ('Name .*: ') child.sendline ('anonymous') child.expect ('Password:') child.sendline ('[email protected]') child.expect ('ftp> ') child.sendline ('cd pub') child.expect('ftp> ') child.sendline ('get ls-lR.gz') child.expect('ftp> ') child.sendline ('bye') ```
How to scp in python?
250,283
97
2008-10-30T14:09:21Z
251,625
8
2008-10-30T20:22:43Z
[ "python", "ssh", "scp" ]
What's the most pythonic way to scp a file in Python? The only route I'm aware of is ``` os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) ``` which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted's `conch`, but I'd prefer to avoid implementing scp myself via low-level ssh modules. I'm aware of `paramiko`, a Python module that supports ssh and sftp; but it doesn't support scp. Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option. **EDIT**: This is a duplicate of <http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh>. **However**, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like ``` import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') ```
You could also check out [paramiko](http://www.lag.net/paramiko/). There's no scp module (yet), but it fully supports sftp. [EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes. [scp.py for paramiko](https://github.com/jbardin/scp.py)
How to scp in python?
250,283
97
2008-10-30T14:09:21Z
4,282,261
62
2010-11-26T03:03:37Z
[ "python", "ssh", "scp" ]
What's the most pythonic way to scp a file in Python? The only route I'm aware of is ``` os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) ``` which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted's `conch`, but I'd prefer to avoid implementing scp myself via low-level ssh modules. I'm aware of `paramiko`, a Python module that supports ssh and sftp; but it doesn't support scp. Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option. **EDIT**: This is a duplicate of <http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh>. **However**, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like ``` import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') ```
Try the module [paramiko\_scp](https://github.com/jbardin/scp.py). It's very easy to use. See the following example: ``` def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return client ssh = createSSHClient(server, port, user, password) scp = SCPClient(ssh.get_transport()) ``` Then call scp.get() or scp.put() to do scp operations. ([SCPClient code](https://github.com/jbardin/scp.py/blob/master/scp.py))
Truncate a string without ending in the middle of a word
250,357
31
2008-10-30T14:32:20Z
250,373
49
2008-10-30T14:36:03Z
[ "python", "truncate" ]
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: ``` Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." ``` I'm looking for a way to accomplish the "smart" truncate from above.
I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller. ``` def smart_truncate(content, length=100, suffix='...'): if len(content) <= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix ``` What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').
Truncate a string without ending in the middle of a word
250,357
31
2008-10-30T14:32:20Z
250,406
36
2008-10-30T14:43:16Z
[ "python", "truncate" ]
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: ``` Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." ``` I'm looking for a way to accomplish the "smart" truncate from above.
Here's a slightly better version of the last line in Adam's solution: ``` return content[:length].rsplit(' ', 1)[0]+suffix ``` (This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.)
Truncate a string without ending in the middle of a word
250,357
31
2008-10-30T14:32:20Z
250,471
7
2008-10-30T14:59:41Z
[ "python", "truncate" ]
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: ``` Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." ``` I'm looking for a way to accomplish the "smart" truncate from above.
``` def smart_truncate1(text, max_length=100, suffix='...'): """Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. """ if len(text) > max_length: pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix)-1) return re.sub(pattern, r'\1' + suffix, text) else: return text ``` OR ``` def smart_truncate2(text, min_length=100, suffix='...'): """If the `text` is more than `min_length` characters long, it will be cut at the next word-boundary and `suffix`will be appended. """ pattern = r'^(.{%d,}?\S)\s.*' % (min_length-1) return re.sub(pattern, r'\1' + suffix, text) ``` OR ``` def smart_truncate3(text, length=100, suffix='...'): """Truncates `text`, on a word boundary, as close to the target length it can come. """ slen = len(suffix) pattern = r'^(.{0,%d}\S)\s+\S+' % (length-slen-1) if len(text) > length: match = re.match(pattern, text) if match: length0 = match.end(0) length1 = match.end(1) if abs(length0+slen-length) < abs(length1+slen-length): return match.group(0) + suffix else: return match.group(1) + suffix return text ```
Truncate a string without ending in the middle of a word
250,357
31
2008-10-30T14:32:20Z
250,684
11
2008-10-30T15:47:04Z
[ "python", "truncate" ]
I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word. For example: ``` Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." ``` I'm looking for a way to accomplish the "smart" truncate from above.
There are a few subtleties that may or may not be issues for you, such as handling of tabs (Eg. if you're displaying them as 8 spaces, but treating them as 1 character internally), handling various flavours of breaking and non-breaking whitespace, or allowing breaking on hyphenation etc. If any of this is desirable, you may want to take a look at the textwrap module. eg: ``` def truncate(text, max_size): if len(text) <= max_size: return text return textwrap.wrap(text, max_size-3)[0] + "..." ``` The default behaviour for words greater than max\_size is to break them (making max\_size a hard limit). You can change to the soft limit used by some of the other solutions here by passing break\_long\_words=False to wrap(), in which case it will return the whole word. If you want this behaviour change the last line to: ``` lines = textwrap.wrap(text, max_size-3, break_long_words=False) return lines[0] + ("..." if len(lines)>1 else "") ``` There are a few other options like expand\_tabs that may be of interest depending on the exact behaviour you want.
What do you like about Django?
250,397
6
2008-10-30T14:41:38Z
250,459
8
2008-10-30T14:57:22Z
[ "python", "django" ]
I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more. Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything. So i would like to know your opinion about Django. What do you like about it? What made you switch/use it? What features you would like it to have that aren't there? What would make you switch to it? How fast is it in production? How hard is it to master it?
***What do I like about it :*** * Very simple ORM * clear separation of template / controller * django-admin * pluggable apps : it seems to me that the Django community really nailed that one ! ***What made me switch :*** * mainly curiosity * I heard a lot of good things about it from a colleague * I wanted something more lightweight than the Java I do for a living * I had a side project heavily data-driven for which the Django-Admin interface is very useful ***What features I'd like :*** * better / simpler control of the transactions (configuring different types of transactions (read only / read write / some tweaking here and there) isnt as easy as i am used to. Having a session in view model, where the transaction is still open in the view doesnt make me all that comfortable, I would prefer if the transactions didnt leave a service layer. But again, there isnt really a service layer in the Django model. * better model for business logic (maybe that's just me, but I miss the service oriented approach of enterprise java, I never know if I should put the business logic in the view, in the form or in the model. None of those solution make me feel warm and fuzzy ... at the same time, I dont have heavy business logic in the application I develop for the moment, and I would probably still use Java for those) * stability (in the sense of not changing, not in the sense of not crashing). Again, coming from Java, where I'm still working on Java 1.4 for a lot of projects, having a project that just released 1.0 and all the refactoring that went with it is not very reassuring. It did take some work to follow trunk and using 0.96 was not particularly compelling. I dont think I would feel comfortable to use it on a mission critical enterprise project yet. I realize that there is quite a few improvements that I would like. Dont understand me wrong, I love Django and I will stick to it for a lot of projects. I jsut wont put it everywhere yet ...
What do you like about Django?
250,397
6
2008-10-30T14:41:38Z
250,461
8
2008-10-30T14:57:53Z
[ "python", "django" ]
I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more. Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything. So i would like to know your opinion about Django. What do you like about it? What made you switch/use it? What features you would like it to have that aren't there? What would make you switch to it? How fast is it in production? How hard is it to master it?
### What do you like about it? URL dispatching: I was never a big fan of "/foo.php" is the file "foo.php" on my server, and if I want nicer URLs I need to mess around with mod\_rewrite and keep that in line with what my logic in foo expects. ORM: Because 90%+ of your queries, in my experience, do not need to be written by hand. Smart caching is much more important for performance, in general. You can *always* drop to raw SQL as needed. Middleware and Signals: Easy to extend most parts of the request / response / view / render cycle without touching Django code itself. ### What made you switch/use it? It came out when I was disappointed with the Python web framework offerings. An easy sell for me. ### How fast is it in production? Hmm, to be honest, I've never cared too much. The webserver part of your app is (in my opinion) always the easiest to scale. As long as you use 'best practices' and share nothing, all you need to do is add a software load balancer and you can add new webservers until the cows come home. The first bottleneck people generally hit is database load - but Django gives you great caching APIs that help you alleviate that. That said, I only skimmed this but it seems faster than Rails and the well known PHP frameworks: <http://wiki.rubyonrails.org/rails/pages/Framework+Performance> ### How hard is it to master it? I guess it depends how you define 'master'. The documentation is great, over the course of a decent sized site/app I think you'll use a little bit of everything, which is a great start.
How to get a function name as a string in Python?
251,464
306
2008-10-30T19:38:24Z
251,469
32
2008-10-30T19:39:19Z
[ "python", "string", "function" ]
In Python, how do I get a function name as a string without calling the function? ``` def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes ``` should output `"my_function"`. Is this available in python? If not, any idea how to write `get_function_name_as_string` in Python?
``` my_function.func_name ``` There are also other fun properties of functions. Type `dir(func_name)` to list them. `func_name.func_code.co_code` is the compiled function, stored as a string. ``` import dis dis.dis(my_function) ``` will display the code in *almost* human readable format. :)
How to get a function name as a string in Python?
251,464
306
2008-10-30T19:38:24Z
255,297
357
2008-11-01T00:07:17Z
[ "python", "string", "function" ]
In Python, how do I get a function name as a string without calling the function? ``` def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes ``` should output `"my_function"`. Is this available in python? If not, any idea how to write `get_function_name_as_string` in Python?
``` my_function.__name__ ``` Using `__name__` is the preferred method as it applies uniformly. Unlike `func_name`, it works on built-in functions as well: ``` >>> import time >>> time.time.func_name Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' >>> time.time.__name__ 'time' ``` Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a `__name__` attribute too, so you only have remember one special name.
How to get a function name as a string in Python?
251,464
306
2008-10-30T19:38:24Z
13,514,318
116
2012-11-22T13:59:49Z
[ "python", "string", "function" ]
In Python, how do I get a function name as a string without calling the function? ``` def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes ``` should output `"my_function"`. Is this available in python? If not, any idea how to write `get_function_name_as_string` in Python?
You could also use ``` import sys this_function_name = sys._getframe().f_code.co_name ```
How to get a function name as a string in Python?
251,464
306
2008-10-30T19:38:24Z
20,714,270
21
2013-12-21T00:59:58Z
[ "python", "string", "function" ]
In Python, how do I get a function name as a string without calling the function? ``` def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes ``` should output `"my_function"`. Is this available in python? If not, any idea how to write `get_function_name_as_string` in Python?
This function will return the caller's function name. ``` def func_name(): import traceback return traceback.extract_stack(None, 2)[0][2] ``` It is like Albert Vonpupp's answer with a friendly wrapper.
Possible Google Riddle?
252,221
11
2008-10-31T00:14:12Z
260,580
15
2008-11-04T01:46:39Z
[ "python" ]
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg) So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. ``` #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print ``` [t-shirt](http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg).
I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"
How can I use a DLL file from Python?
252,417
105
2008-10-31T02:01:48Z
252,473
88
2008-10-31T02:43:41Z
[ "python", "dll" ]
What is the easiest way to use a DLL file from within Python? Specifically, how can this be done *without* writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.
For ease of use, [ctypes](http://docs.python.org/library/ctypes.html) is the way to go. The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask. ``` import ctypes # Load DLL into memory. hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll") # Set up prototype and parameters for the desired function call. # HLLAPI hllApiProto = ctypes.WINFUNCTYPE ( ctypes.c_int, # Return type. ctypes.c_void_p, # Parameters 1 ... ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p) # ... thru 4. hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0), # Actually map the call ("HLLAPI(...)") to a Python name. hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams) # This is how you can actually call the DLL function. # Set up the variables and call the Python name with them. p1 = ctypes.c_int (1) p2 = ctypes.c_char_p (sessionVar) p3 = ctypes.c_int (1) p4 = ctypes.c_int (0) hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4)) ``` The `ctypes` stuff has all the C-type data types (`int`, `char`, `short`, `void*`, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference). --- In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface. All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an `int` so, while I specify `int` as the return type, I can safely ignore it) as per IBM's documentation [here](http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm). In other words, the C variant of the function would be: ``` int hllApi (void *p1, void *p2, void *p3, void *p4) ``` This makes for a single, simple `ctypes` function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate `ctypes` function set up per library function. The return value from `WINFUNCTYPE` is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in `hllApiParams` has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the `ctypes` doco for details Once you have the prototype and parameter information, you can create a Python "callable" `hllApi` with which to call the function. You simply create the needed variable (`p1` through `p4` in my case) and call the function with them.
How can I use a DLL file from Python?
252,417
105
2008-10-31T02:01:48Z
3,173,926
32
2010-07-04T06:28:31Z
[ "python", "dll" ]
What is the easiest way to use a DLL file from within Python? Specifically, how can this be done *without* writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.
[This page](http://web.archive.org/web/20111006042404/http://www.knowledgetantra.com/component/content/article/2-python/1-call-dll-function-in-python.html) is a very simple example of calling functions from a DLL file. > It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: `add` and `sub` which take two arguments. > > `add(a, b)` returns addition of two numbers > `sub(a, b)` returns substraction of two numbers > > The name of the DLL file will be "demo.dll" > > **Program:** > > `from ctypes import*` > `# give location of dll` > `mydll = cdll.LoadLibrary("C:\\demo.dll")` > `result1= mydll.add(10,1)` > `result2= mydll.sub(10,1)` > `print "Addition value:-"+result1` > `print "Substraction:-"+result2` > > **Output:** > > `Addition value:-11` > `Substraction:-9`
Why won't Django 1.0 admin application work?
252,531
5
2008-10-31T03:35:19Z
252,621
12
2008-10-31T04:50:27Z
[ "python", "django", "admin" ]
I've just started playing with Django and am loosely following the tutorial with my own set of basic requirements. The models I've sketched out so far are a lot more comprehensive than the tutorial, but they compile fine. Otherwise, everything should have been the same. My problem is with the admin application. I can log into it, and view the editable models, but when I click on a model or any of the change/add buttons, I get a 404. This is the exact error I get: ``` Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin/auth/user/add/ App u'', model u'auth', not found. ``` These are the relevant files and what is in them: urls.py ``` from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^daso/', include('daso.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: #(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin(.*)', admin.site.root) ) ``` admin.py ``` from daso.clients.models import Person, Client, Contact from django.contrib import admin admin.site.register(Person) admin.site.register(Client) admin.site.register(Contact) ``` models.py - I'll just show one model ``` class Client(Person): relationships = models.ManyToManyField("Contact", through="Relationship", null=True) disabilities = models.ManyToManyField("Disability", related_name="disability", null=True) medical_issues = models.ManyToManyField("MedicalIssue", related_name="medical_issue", null=True) medicare_num = models.CharField(max_length=15, blank=True) insurance = models.OneToOneField("Insurance", null=True, blank=True) medications = models.ManyToManyField("Medication", through="Medication_Details", null=True) def __unicode__(self): client = u"[Client[id: ", self.id, " name: ", self.first_name, " ", self.last_name, "]" return client ``` settings.py ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'daso.clients', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ``` Those should be the relevant files/sections of files. If anyone has an idea about WHY I'm getting a 404, please enlighten me? Note, when pasting in here, installed apps had the last 2 apps tabbed instead of spaced\*4, and when reloading the admin page it worked for half a second then 404'd again. Strange. Ideas?
It's because you left out a `/` in `urls.py`. Change the admin line to the following: ``` (r'^admin/(.*)', admin.site.root), ``` I checked this on my server and got the same error with your line from `urls.py`.
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
252,704
72
2008-10-31T05:57:32Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
`append` appends a single element. `extend` appends a list of elements. Note that if you pass a list to append, it still adds one element: ``` >>> a = [1, 2, 3] >>> a.append([4, 5, 6]) >>> a [1, 2, 3, [4, 5, 6]] ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
252,705
388
2008-10-31T05:57:37Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
`append` adds an element to a list, `extend` concatenates the first list with another list (or another iterable not necessarily a list.) ``` >>> li = ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li.append("new") >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new'] >>> li.extend(["two", "elements"]) >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] ``` From [Dive into Python](http://www.diveintopython.net/native_data_types/lists.html#d0e5887).
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
252,711
2,392
2008-10-31T06:02:25Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
[`append`](https://docs.python.org/2/library/array.html?#array.array.append): Appends object at end. ``` x = [1, 2, 3] x.append([4, 5]) print (x) ``` gives you: `[1, 2, 3, [4, 5]]` --- [`extend`](https://docs.python.org/2/library/array.html?#array.array.extend): Extends list by appending elements from the iterable. ``` x = [1, 2, 3] x.extend([4, 5]) print (x) ``` gives you: `[1, 2, 3, 4, 5]`
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
252,918
50
2008-10-31T09:03:22Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
Good answers, but don't forget, any iterable will do for `extend` (not just list): ``` l.extend(xrange(5)) ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
262,132
197
2008-11-04T15:19:52Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
And in this context it can also be good to remember that strings are also iterable. ``` >>> a = [1, 2] >>> a [1, 2] >>> a.extend('hey') >>> a [1, 2, 'h', 'e', 'y'] ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
5,605,403
31
2011-04-09T13:46:02Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
Like `Ali A` said, any iterable will do for the extend, here is an example for dictionary argument, ``` >>> li=[1,2,3] >>> li.extend({4:5,6:7}) >>> li [1, 2, 3, 4, 6] >>> ``` as you can see, only `keys` are added to the list.
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
12,045,242
28
2012-08-20T21:11:00Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
The following two snippets are semantically equivalent: ``` for item in iterator: a_list.append(item) ``` and ``` a_list.extend(iterator) ``` The latter may be faster as the loop is implemented in C.
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
16,510,635
10
2013-05-12T18:21:40Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
`extend()` can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way: from ``` list2d = [[1,2,3],[4,5,6], [7], [8,9]] ``` you want ``` >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` You may use `itertools.chain.from_iterable()` to do so. This method's output is an iterator. It's implementation is equivalent to ``` def from_iterable(iterables): # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F for it in iterables: for element in it: yield element ``` Back to our example, we can do ``` import itertools list2d = [[1,2,3],[4,5,6], [7], [8,9]] merged = list(itertools.chain.from_iterable(list2d)) ``` and get the wanted list. Here is how equivalently `extend()` can be used with an iterator argument: ``` merged = [] merged.extend(itertools.chain.from_iterable(list2d)) print(merged) >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
16,511,403
10
2013-05-12T19:51:07Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
append(object) - Updates the list by adding an object to the list. ``` x = [20] # list passed to the append(object) method is treated as a single object. x.append([21,22,23]) #hence the resultant list length will be 2 print x --> [20, [21,22,23]] ``` extend(list) - Essentially concatenates 2 lists. ``` x = [20] #the parameter passed to extend(list) method is treated as a list. #eventually it is 2 list's being concatenated. x.extend([21,22,23]) #here the resultant list's length is 4 print x [20,21,22,23] ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
18,442,908
20
2013-08-26T11:21:12Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
You can use "+" for returning extend, instead of extending in place. ``` l1=range(10) l1+[11] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11] l2=range(10,1,-1) l1+l2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2] ``` Similarly `+=` for in place behavior, but with slight differences from `append` & `extend`. One of the biggest differences of `+=` from `append` and `extend` is when it is used in function scopes, see this blog post: <https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make?utm_medium=referral&utm_source=zeef.com&utm_campaign=ZEEF>
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
19,707,477
22
2013-10-31T13:12:10Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
The append() method adds a single item to the end of the list. ``` x = [1, 2, 3] x.append([4, 5]) x.append('abc') print x # gives you [1, 2, 3, [4, 5], 'abc'] ``` The extend() method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.) ``` x = [1, 2, 3] x.extend([4, 5]) x.extend('abc') print x # gives you [1, 2, 3, 4, 5, 'a', 'b', 'c'] ``` From [Dive Into Python](http://rads.stackoverflow.com/amzn/click/1430224150)
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
24,632,188
8
2014-07-08T12:42:52Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
This is the equivalent of `append` and `extend` using the `+` operator: ``` >>> x = [1,2,3] >>> x [1, 2, 3] >>> x = x + [4,5,6] # Extend >>> x [1, 2, 3, 4, 5, 6] >>> x = x + [[7,8]] # Append >>> x [1, 2, 3, 4, 5, 6, [7, 8]] ```
append vs. extend
252,703
1,581
2008-10-31T05:55:36Z
28,119,966
58
2015-01-23T22:44:37Z
[ "python", "list", "append", "extend" ]
What's the difference between the list methods `append()` and `extend()`?
> # What is the difference between the list methods append and extend? * `append` adds its argument as a single element to the end of a list. The length of the list itself will increase by one. * `extend` iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument. # `append` The `list.append` method appends an object to the end of the list. ``` my_list.append(object) ``` Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of `my_list` as a single entry on the list. ``` >>> my_list ['foo', 'bar'] >>> my_list.append('baz') >>> my_list ['foo', 'bar', 'baz'] ``` So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want): ``` >>> another_list = [1, 2, 3] >>> my_list.append(another_list) >>> my_list ['foo', 'bar', 'baz', [1, 2, 3]] #^^^^^^^^^--- single item on end of list. ``` # `extend` The `list.extend` method extends a list by appending elements from an iterable: ``` my_list.extend(iterable) ``` So with extend, each element of the iterable gets appended onto the list. For example: ``` >>> my_list ['foo', 'bar'] >>> another_list = [1, 2, 3] >>> my_list.extend(another_list) >>> my_list ['foo', 'bar', 1, 2, 3] ``` Keep in mind that a string is an iterable, so if you extend a list with a string, you'll append each character as you iterate over the string (which may not be what you want): ``` >>> my_list.extend('baz') >>> my_list ['foo', 'bar', 1, 2, 3, 'b', 'a', 'z'] ``` # Operator Overload, `__and__`, (`+`) and `__iand__` (`+=`) Both `+` and `+=` operators are defined for `list`. They are semantically similar to extend. `my_list + another_list` creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list. `my_list += another_list` modifies the list in-place (it *is* the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable. # Performance You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing: ``` def append(alist, iterable): for item in iterable: alist.append(item) def extend(alist, iterable): alist.extend(iterable) ``` So let's time them: ``` import timeit >>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz"))) 2.867846965789795 >>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz"))) 0.8060121536254883 ``` # Conclusion We see that `extend` can run much faster than `append`, and it is semantically clearer, so it is preferred *when you intend to append each element in an iterable to a list.* If you only have a single element to add to the list, use `append`.
What Python bindings are there for CVS or SVN?
253,375
13
2008-10-31T12:51:14Z
253,390
8
2008-10-31T13:01:31Z
[ "python", "svn", "version-control", "cvs" ]
I once did a cursory search and found no good CVS bindings for Python. I wanted to be able to write helper scripts to do some fine-grained manipulation of the repository and projects in it. I had to resort to using `popen` and checking `stdout` and `stderr` and then parsing those. It was messy and error-prone. Are there any good quality modules for CVS integration for Python? Which module do you prefer and why? While I am at it, is there a good Subversion integration module for Python? My understanding is that Subversion has a great API for such things.
For cvs, [pyCVS](http://pycvs.sourceforge.net/) may be worth a look. For svn, there is [pysvn](http://pysvn.tigris.org/), which is pretty good.
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
29
2008-10-31T17:47:39Z
254,357
40
2008-10-31T17:50:04Z
[ "python" ]
I don't care what the differences are. I just want to know whether the contents are different.
The low level way: ``` from __future__ import with_statement with open(filename1) as f1: with open(filename2) as f2: if f1.read() == f2.read(): ... ``` The high level way: ``` import filecmp if filecmp.cmp(filename1, filename2, shallow=False): ... ```
In Python, is there a concise way of comparing whether the contents of two text files are the same?
254,350
29
2008-10-31T17:47:39Z
254,373
20
2008-10-31T17:56:15Z
[ "python" ]
I don't care what the differences are. I just want to know whether the contents are different.
If you're going for even basic efficiency, you probably want to check the file size first: ``` if os.path.getsize(filename1) == os.path.getsize(filename2): if open('filename1','r').read() == open('filename2','r').read(): # Files are the same. ``` This saves you reading every line of two files that aren't even the same size, and thus can't be the same. (Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not "in Python", so I'll stop here.)
Tiny python executable?
254,635
8
2008-10-31T19:20:30Z
254,723
9
2008-10-31T19:51:46Z
[ "python", "executable", "pyinstaller" ]
I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb). Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something similiar?
If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c
Converting datetime to POSIX time
255,035
36
2008-10-31T21:38:02Z
255,053
44
2008-10-31T21:44:35Z
[ "python", "datetime", "posix" ]
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
``` import time, datetime d = datetime.datetime.now() print time.mktime(d.timetuple()) ```
Converting datetime to POSIX time
255,035
36
2008-10-31T21:38:02Z
5,872,022
19
2011-05-03T15:39:15Z
[ "python", "datetime", "posix" ]
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
For UTC calculations, `calendar.timegm` is the inverse of `time.gmtime`. ``` import calendar, datetime d = datetime.datetime.utcnow() print calendar.timegm(d.timetuple()) ```