[Tutor] Regarding Python api script
Steven D'Aprano
steve at pearwood.info
Fri Dec 7 05:59:33 EST 2018
On Thu, Dec 06, 2018 at 09:13:01PM -0500, Avi Gross wrote:
> But so much code I see in python does not only reuse the same variable names
> but in a confusing way.
>
> file = "some name"
> file = open(file, "r")
> file = some_wrapper(file)
I agree this is confusing: you have the same name, "file", used to mean
a file name, an open file object, and whatever some_wrapper returns.
This is not the clearest code I've ever seen.
> mylist = [ ... ]
> mylist = sorted(mylist)
There's nothing wrong with that, except that it ought to be written:
mylist = [ ... ]
mylist.sort()
to sort in place instead of making a sorted copy.
> for index in range(...):
> stuff
>
> for index in open(...)
> more stuff
Using "index" to iterate over the lines in a file is just a crappy
choice of name.
[...]
> I have often seen something like this done with methods, such as to emulate
> decorator functionality where a method is created in an object with a name
> and the very next method created has the same name with the same function
> name as an argument to replace it.
I don't understand this. Can you show an example? Even if made up?
> So is there a guide on when reuse is good and when it just obfuscates? What
> is good practice?
If you pick *meaningful* names, it will be pretty obvious when to reuse
the same name: is the name still meaningful? Then you MAY reuse. If the
name is not meaningful, then you MUST NOT reuse it, unless you are
deliberately writing obfuscated code.
If you have a name "column" which you use for a columns, then you
shouldn't reuse it for rows, or lines of text read from a file, or the
length of a list, or the date. But you can reuse it for another column,
provided there's no confusion over which column is which.
The same applies to any other language.
--
Steve
More information about the Tutor
mailing list