Dict naming, global vs local imports, etc. [was Re: *Naming Conventions*]
George Sakkis
george.sakkis at gmail.com
Sun Jun 3 19:00:10 EDT 2007
On Jun 3, 4:32 pm, Steve Howell <showel... at yahoo.com> wrote:
> I also still waste brain cycles on naming
> dictionaries. Sometimes I name the dictionary after
> the values it stores, sometimes after the keys it
> uses, and sometimes after both.
I was in the same boat but now I've pretty much settled to the
convention `key2value`, e.g.:
name2func = {
'sum' : sum,
'avg' : lambda values: sum(values) / float(len(values))
'product' : lambda values: reduce(operator.mul,values,1),
}
word2positions = {
'dog' : [3, 45, 79, 840],
'cat' : [56, 97, 810],
}
At some point I was torn between this and the plural form, i.e.
`keys2values`, but that's ambiguous in cases where each key or value
is a collection, such as the 'positions' above.
While we're at it, although it's not strictly a naming convention
issue I still waste brain cycles on where to put the import statements
that are used only once or twice in a module. Should
(1) all imports be at the global scope at the top of the module, or
(2) be imported in the function or method they are actually used ?
Reasons for (1)
---------------
- PEP-8 compatible.
- Easy to see all external dependencies in one place.
Reasons for (2)
---------------
- Point of import closer to point of use; easy to notice if a given
import is not used any more after refactoring.
- Less name pollution.
- Faster name lookup in locals (might make a difference for tight
loops).
I usually go for (1), at least until the number of global imports in
the top remains in single digits. After some point though I often
localize the standard library imports that are used only once or twice
(the third-party and local application imports are almost always
global). Any others that are not strictly PEP-8 compliant on this ?
George
More information about the Python-list
mailing list