Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
Help with Dictionaries and Classes requested please.
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Bruno Desthuilliers, post: 3005745"] special_dragonfly a écrit : May I suggest a couple possible improvements ? First : you're of course free to use any naming convention you like, and it's obviously better to stay consistent, but the canonical Python convention is to use all_lower for vars, functions (and methods) and modules, and MixedCase for classes. About the code now: def EnterDictionary(FieldsDictionary,key,data): for i in range(0,int(data[6:])): 1/ Golden rule : avoid the use of "magic numbers". This one stands true for any languages !-). The usual solution is to use symbolic constants. While Python doesn't have real symbolic constant, the convention is to write them ALL_UPPER. 2/ range() can be used with only one argument, which then will be use as the upper bound. IOW, range(0, X) is the same as range(X) line=myfile.readline() 3/ where does this 'myfile' comes from ? (hint : don't use globals when you can avoid them) line=line.strip() line=line[6:-1] 4/ magic numbers again, cf /1. Question : does this 6 has anything to do with the other one ? What will happen when the file format will change ? 5/ you can do all this in a single line, adding the split() too: args = myfile.readline().strip()[XXX:-1].split(",") If you expect key to most of the times be already in FieldsDictionnary, then a try/except block might be a bit faster. If you expect key to not be here most of the times, then your solution is right. Note that you can also use dict.setdefault(key, default): # probably bad names but I don't have a clue what they should be DATA_INDEX_OFFSET = 6 LINE_START = 6 LINE_END = -1 def update_fields_dict(fields_dict, key, data, datafile): for i in range(int(data[DATA_INDEX_OFFSET:])): args =datafile.readline().strip()[LINE_START:LINE_END].split(",") fields_dict.setdefault(key, []).append(FieldClass(*args)) Feel free to take or leave what you consider appropriate here. But by all means avoid magic numbers, except possibly for Q&D throw-away scripts (and even then...). HTH That's usually what happens then, don't worry. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
Help with Dictionaries and Classes requested please.
Top