简体   繁体   中英

Python variables naming convention

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?

eg 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!

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.

我会使用open_sum_

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.

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.

Pep8建议使用尾随下划线,但是也有人提到在可能的情况下使用同义词来表示变量会更好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM