435
votes
19answers
66k views

Single quotes vs. double quotes in Python [closed]

According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
161
votes
7answers
32k views

What is a clean, pythonic way to have multiple constructors in Python?

I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So what is a good way to solve this problem? Suppose I have an class called Cheese ...
95
votes
23answers
36k views

Tabs versus spaces in Python programming

I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to ...
94
votes
6answers
54k views

Python `if x is not None` or `if not x is None`?

I've always thought of the if not x is None version to be more clear, but Google's style guide implies (based on this excerpt) that they use if x is not None. Is there any minor performance difference ...
89
votes
8answers
79k views

How do you return multiple values in Python?

The canonical way to return multiple values in languages that support it is often tupling. Consider this trivial example: def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) ...
79
votes
11answers
13k views

Should Python import statements always be at the top of a module?

PEP 08 states: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. However if the class/method/function that I ...
62
votes
5answers
19k views

What is the standard Python docstring format?

I have seen a few different styles of writing docstrings in Python, is there an official or "agreed-upon" style?
59
votes
17answers
57k views

Python style: multiple-line conditions in IFs

Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): ...
52
votes
8answers
23k views

Python coding standards/best practices [closed]

In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?
47
votes
9answers
2k views

Should I Return None or (None, None)?

We have a object method that returns a city/state tuple, i.e. ('Boston', 'MA'). Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return ...
37
votes
10answers
1k views

Any reason NOT to always use keyword arguments?

Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, ...
28
votes
9answers
3k views

Why is it “Easier to ask forgiveness than permission” in python, but not in Java? [closed]

It seems that this is accepted as perfectly good code in the python community: def is_integer(input): try: return x % 1 == 0 except TypeError: return False On the other ...
27
votes
5answers
16k views

python - why use def main() [duplicate]

Possible Duplicate: What does <if name==“main”:> do? Hi there, Just being doing some things with python, and from what i've seen (code samples/tutorials) that code uses ...
25
votes
9answers
7k views

Python import coding style

I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are ...
25
votes
7answers
6k views

pythonic way to do something N times

Hey! Every day I love python more and more. Today, I was writing some code like: for i in xrange(N): do_something() I had to do something N times. But each time didn't depend on the value of ...
23
votes
5answers
8k views

Should I use `import os.path` or `import os`?

According to the official documentation, os.path is a module. Thus, what is the preferred way of importing it? # Should I always import it explicitly? import os.path Or... # Is importing os ...
22
votes
2answers
4k views

Python style - line continuation with strings?

In trying to obey the python style rules, I've set my editors to a max of 79 cols. In the PEP, it recommends using python's implied continuation within brackets, parentheses and braces. However, ...
22
votes
4answers
11k views

Function and class documentation best practices for Python

I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python ...
20
votes
8answers
6k views

What is the best Python library module skeleton code?

Many python IDE's will start you with a template like: print 'hello world' That's not enough... So here's my skeleton code to get this question started: My Module Skeleton, Short Version: ...
19
votes
5answers
580 views

PEP8 and PyQt, how to reconcile

I'm starting to use PyQt in some projects and I'm running into a stylistic dilemma. PyQt's functions use camel case, but PEP8, which I prefer to follow, says to use underscores and all lowercase for ...
18
votes
10answers
5k views

Javascript style dot notation for dictionary keys unpythonic?

I've started to use constructs like these: class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def ...
17
votes
7answers
2k views

In Python, is it better to use list comprehensions or for-each loops?

Which of the following is better to use and why? Method 1: for k, v in os.environ.items(): print "%s=%s" % (k, v) Method 2: print "\n".join(["%s=%s" % (k, v) for k,v in ...
16
votes
3answers
1k views

Line continuation for list comprehensions or generator expressions in python

How are you supposed to break up a very long list comprehension? [something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long] I have also seen somewhere that ...
16
votes
1answer
324 views

How to cleanly keep below 80-char width with long strings?

I'm attempting to keep my code to 80 chars or less nowadays as I think it looks more aesthetically pleasing, for the most part. Sometimes, though, the code ends up looking worse if I have to put line ...
15
votes
8answers
6k views

Python: Alter elements of a list

I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: for b in bool_list: b = False I found it doesn't work. I spent a moment scratching my ...
14
votes
4answers
20k views

Creating an empty list in Python

What is the best way to create a new empty list in Python? l = [] or l = list() I am asking this because of two reasons: Technical reasons, as to which is faster. (creating a class causes ...
14
votes
3answers
255 views

Is making in-place operations return the object a bad idea?

I'm talking mostly about Python here, but I suppose this probably holds for most languages. If I have a mutable object, is it a bad idea to make an in-place operation also return the object? It seems ...
14
votes
9answers
4k views

Code-style for indent of multi-line IF statement in Python? [duplicate]

When indenting long if conditions, you usually do something like this (actually, PyDev indents like that): if (collResv.repeatability is None or collResv.somethingElse): collResv.rejected = ...
14
votes
3answers
961 views

emacs 23 python.el auto-indent style — can this be configured?

I have been using emacs 23 (python.el) for just over a month now and I'm unhappy with the default auto-indentation settings. Currently, my Python files are auto-indented as follows: x = ...
13
votes
12answers
1k views

“Interfaces” in Python: Yea or Nay?

So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any ...
13
votes
3answers
1k views

Best practice for lazy loading Python modules

Occasionally I want lazy module loading in Python. Usually because I want to keep runtime requirements or start-up times low and splitting the code into sub-modules would be cumbersome. A typical use ...
13
votes
1answer
3k views

How to configure PyLint to check all things PEP8 checks?

Searching for an answer on PyLint's mailing list brings no interesting results. PyLint is known to be very customizable so I guess this should be possible... The reason I would like PyLint to check ...
12
votes
6answers
597 views

Best python style for complex one-liners

I recently wrote a rather ugly looking one-liner, and was wondering if it is better python style to break it up into multiple lines, or leave it as a commented one-liner. I looked in PEP 8, but it did ...
12
votes
4answers
4k views

Algorithm for neatly indenting SQL statements (Python implementation would be nice)

I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read. I don't personally know of a good coding style for indenting SQL - how ...
12
votes
2answers
1k views

Chained method calls indentation style in Python [duplicate]

From reading PEP-8, I get it that you should put the closing parenthesis on the same line as the last argument in function calls: ShortName.objects.distinct().filter( ...
12
votes
4answers
1k views

In Python, when should I use a function instead of a method?

The Zen of Python states that there should only be one way to do things- yet frequently I run into the problem of deciding when to use a function versus when to use a method. Let's take a trivial ...
11
votes
7answers
2k views

What is the best way to get the first item from an iterable matching a condition?

In Python, I would like to get the first item from a list matching a condition. For example, the following function is adequate: def first(the_iterable, condition = lambda x: True): for i in ...
11
votes
4answers
1k views

Importing modules in Python - best practice

I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts. What is best practice in Python. I have ...
11
votes
3answers
710 views

Attributes initialization/declaration in Python class: where to place them?

I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function? i.e. class A(object): foo = None vs class ...
11
votes
4answers
251 views

How to design a program with many configuration options?

Lets say I have a program that has a large number of configuration options. The user can specify them in a config file. My program can parse this config file, but how should it internally store and ...
10
votes
6answers
2k views

File open: Is this bad Python style?

To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other ...
10
votes
8answers
929 views

How do you PEP 8-name a class whose name is an acronym?

I try to adhere to the style guide for Python code (also known as PEP 8). Accordingly, the preferred way to name a class is using CamelCase: Almost without exception, class names use the ...
10
votes
6answers
7k views

Open file, read it, process, and write back - shortest method in Python

I want to do some basic filtering on a file. Read it, do processing, write it back. I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with: ...
10
votes
4answers
1k views

When should a Python script be split into multiple files/modules?

In Java, this question is easy (if a little tedious) - every class requires its own file. So the number of .java files in a project is the number of classes (not counting anonymous/nested classes). ...
9
votes
13answers
626 views

Is it acceptable to use tricks to save programmer when putting data in your code?

Example: It's really annoying to type a list of strings in python: ["January", "February", "March", "April", ...] I often do something like this to save me having to type quotation marks all over ...
9
votes
7answers
319 views

which style is preferred?

Option 1: def f1(c): d = { "USA": "N.Y.", "China": "Shanghai" } if c in d: return d[c] return "N/A" Option 2: def f2(c): d = { "USA": "N.Y.", "China": "Shanghai" ...
9
votes
6answers
471 views

PEP8 - 80 Characters - Big Integers

This is somehow related to question about big strings and PEP8. How can I make my script that has the following line PEP8 compliant ("Maximum Line Length" rule)? pub_key = { 'e': ...
8
votes
4answers
6k views

python close file descriptor question

I think this question is more of a "coding style" rather than technical issue. Said I have a line of code: buf = open('test.txt','r').readlines() ... Will the file descriptor automatically close, ...
5
votes
1answer
429 views

Tool to convert Python code to be PEP8 compliant

I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both an online service and a python module. However, I cannot find a service or module ...
-2
votes
2answers
34 views

what is special to use class structure in python albeit it is possible to import functions from plain script? [closed]

I am a newbie programmer at python and I am thinking about the class usage of the python. Although it is possible to import all the functions inside a script, what might be the situation that faces to ...

1 2 3 4 5 9
15 30 50 per page