Python Style Guide Questions
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Jan 16 01:38:58 EST 2009
On Thu, 15 Jan 2009 22:13:06 -0800, koranthala wrote:
> Hi,
> Which is more advisable?
> import x
> b = x.a
> or
> from x import a
> b = a
>
> I read in Learning Python that it is always better to use the
> former
Perhaps not "always", but often.
> - especially since namespace wont be dirtied. But, doing that
> with PEP 8 together causes my code to look rather cluttered. Reason
> being that - PEP 8 suggests that have max line length = 79 chars. So my
> code mostly looks like this:
> class x:
> def y():
> try:
> if test:
> obj.filename = str(os.path.basename
> (obj1.find_next_element().\
> get_file_path()))
> obj.modify_time = obj.filename.find_created_time()
> + \
> datetime.timedelta
> (seconds=time.find_time())
A few ideas for you:
There is rarely enough performance benefit from squashing as much as
possible into a single expression to make up for the loss of readability.
Use temporary values to aid comprehension and readability.
class X:
def y(self):
try:
if test:
path = obj1.find_next_element().get_file_path()
obj.filename = str(os.path.basename(path))
ctime = obj.filename.find_created_time()
offset = datetime.timedelta(seconds=time.find_time())
obj.modify_time = ctime + offset
Alternatively, don't nest so much.
class X:
def _y(self):
path = obj1.find_next_element().get_file_path()
obj.filename = str(os.path.basename(path))
ctime = obj.filename.find_created_time()
offset = datetime.timedelta(seconds=time.find_time())
obj.modify_time = ctime + offset
def y(self):
try:
if test:
self._y()
Last but not least, Python now does automatic line continuations inside
open brackets. You can use this to eliminate many backslashes.
class X:
def y(self):
try:
if test:
obj.filename = str(
os.path.basename(
obj1.find_next_element().get_file_path()
))
obj.modify_time = \
obj.filename.find_created_time() + \
datetime.timedelta(seconds=time.find_time())
Hope this helps.
--
Steven
More information about the Python-list
mailing list