Custom Search

Friday, April 2, 2010

Python Naming Guide

Python Naming Guide

Use "has" or "is" Prefix for Boolean Elements
When an element holds a Boolean value, the "is" and "has" prefixes provide a natural
way to make it more readable in its namespace:
>>> class DB(object):
... is_connected = False
... has_cache = False
>>> database = DB()
>>> database.has_cache
False
>>> if database.is_connected:
... print "That's a powerful class"
... else:
... print "No wonder..."
No wonder...

------------------------

Use Plural for Elements That Are Sequences
When an element is holding a sequence, it is a good idea to use a plural form. Some
mappings can also benefit from this when they are exposed like sequences:
>>> class DB(object):
... connected_users = ['Tarek']
... tables = {'Customer': ['id', 'first_name',
... 'last_name']}

------------------------

Use Explicit Names for Dictionaries
When a variable holds a mapping, you should use an explicit name when
possible. For example, if a dict holds some persons' addresses, it can be named
person_address:
>>> person_address = {'Bill': '6565 Monty Road',
... 'Pamela': '45 Python street'}
>>> person_address['Pamela']
'45 Python street'

------------------------

Avoid Generic Names
Using terms such as list, dict, sequence, or elements, even for local variables, is
evil if your code is not building a new abstract data type. It makes the code hard to
read, understand, and use. Using a built-in name has to be avoided as well, to avoid
shadowing it in the current namespace. Generic verbs should also be avoided, unless
they have a meaning in the namespace.
Instead, domain-specific terms should be used:
>>> def compute(data): # too generic
... for element in data:
... yield element * 12
>>> def display_numbers(numbers): # better
... for number in numbers:
... yield number * 12

------------------------

No comments:

Post a Comment