Is It Bad Practice to Use a Built-In Function Name as an Attribute or Method Identifier

Is it bad practice to use a built-in function name as an attribute or method identifier?

It won't confuse the interpreter but it may confuse people reading your code. Unnecessary use of builtin names for attributes and methods should be avoided.

Another ill-effect is that shadowing builtins confuses syntax highlighters in most python-aware editors (vi, emacs, pydev, idle, etc.) Also, some of the lint tools will warn about this practice.

Is using type as an attribute name a bad practice?

There's nothing wrong with it. It's not a member of python's reserved keywords.

However, naming a method type() would probably be confusing...

Is it a bad practice to name a instance variable after a built-in

I would say it's ok.

Grepping through Python's standard library you can see plenty of places where attributes are named the same as built-ins:

For example:

:~/cpython/Lib$ egrep -R "\.set[^a-zA-Z0-9_]" | wc -l
583
:~/cpython/Lib$ egrep -R "\.type[^a-zA-Z0-9_]" | wc -l
319

TypeError when passing a 'file' variable to a fuction

In python 2, there is a file builtin, which is what you are calling extract_archive with in your unrar function. You are not using your loop variable from chktree because it only lives within chktree. You can write it like this:

def unrar(f):
patoolib.extract_archive(f, outdir="/root/tree/def")

def chktree():
for f in glob.glob('/root/tree/down/*'):
if fnmatch.fnmatch(f, '*.rar'):
unrar(f)

I used f as the name for the file to prevent masking the builtin.

id' is a bad variable name in Python

id() is a fundamental built-in:

Help on built-in function id in module
__builtin__:

id(...)

id(object) -> integer

Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory
address.)

In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.

In Python is it bad to create an attribute called 'id'?

That's ok, and is pretty common. For example, objects mapped to a database record will often have an "id" attribute mapped to the database "id" column value.

Attributes are always "namespaced" so you have to refer to them via self.id or obj.id so there's no conflict with the built-in function.

Call a child method inherit from parents inside another child method

You're not returning anything from Child.Eval(), so it returns None implicitly. You just need to add return:

def Eval(self, x):
return super(Child, self).Eval(x)

However, this isn't inheritance, it's delegation. Using inheritance would mean simply not defining Child.Eval(). And in fact, that's the better option since Child.Eval() doesn't do anything additional.



Related Topics



Leave a reply



Submit