Python variables naming convention

2019-06-16 04:23发布

问题:

So I am trying to switch to PEP8 notation (from a rather personal CamelCase notation) and I was wondering how you guys are tackling the cases where existing functions/variables would be overwritten?

e.g. having something like:

open, high, low, close, sum = row

would already overwrite the "open" and "sum" functions. First, if I wouldn't use a good IDE, I wouldn't even notice that I've just overwritten important basic functions. Second, how would you name the variables instead? In this example I would have used apps hungarian and wouldn't have encountered any potential problem at all.

Thanks!

回答1:

Why not just pick non-conflicting names? Such as opening_price, closing_price and total if that's what they represent. While it's possible to qualify the namespace as in the other replies, surely that shouldn't be needed for local variables. Whatever language you program in it's your job to know the reserved words; there aren't that many of them.



回答2:

I would use open_ and sum_.



回答3:

In this particular case, I'd use a namedtuple. This would turn those names into qualified ones (data.open, data.low, etc.).

from collections import namedtuple
Data = namedtuple('Data', ['open', 'high', 'low' 'close', 'sum'])

data = Data(*row)

This would eliminate the prospect of name clashes with built-in functions, and likely improve the overall readability along the way.



回答4:

If they are all values from the same domain, you can use a dictionary:

params = ('open', 'high', 'low', 'close', 'sum') # defined once

val = dict(zip(params, row)) # for each row

# val == {'open': 12, 'high': 34, 'low': 56, 'close': 78, 'sum': 90}

Then you can access them directly: val['open']. You can iterate over them val.iteritems() and so on.



回答5:

Pep8 recommends using trailing underscore, however there is also mentioned that in possible cases using synonym word for the variable would be better idea.



标签: python pep8