Jump to content

"list"-method, a problem ?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
Hey all fellow-nerds,

I have sometimes used in classes methods which were named "list". Recently someone claimed that this could be a problem because it is also how an empty list is created.
Is this true ?
And if it is, in what kind of situation?

All responses are appreciated.

#2
Vladimir

Vladimir

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Typically you don't have to use name (variable name, method name, class name etc) which conflicts with existing one or built-in or commonly used. For example, look at this code:


val = 'Test'


print(len(val)) # 4, OK


def len(str):

    return 10


# 100 lines of the code, you forgot that you introduced new function with same name or you are editing existing module


print(len(val)) # 10, wtf?


You can spend hours debugging such code without success.

Your code is safe, because you have to prefix class method with 'self' or class name (self.list(), YourClass.list()), but still such name can be confusing for people reading/using your code, because there is a built-in function in Python with same name and known behavior. So better don't use names from this list 2. Built-in Functions — Python v2.7 documentation without a great need.

#3
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts

Vladimir said:

Typically you don't have to use name (variable name, method name, class name etc) which conflicts with existing one or built-in or commonly used. For example, look at this code:

val = 'Test'

print(len(val)) # 4, OK

def len(str):
    return 10

# 100 lines of the code, you forgot that you introduced new function with same name or you are editing existing module

print(len(val)) # 10, wtf?
You can spend hours debugging such code without success.

Your code is safe, because you have to prefix class method with 'self' or class name (self.list(), YourClass.list()), but still such name can be confusing for people reading/using your code, because there is a built-in function in Python with same name and known behavior. So better don't use names from this list 2. Built-in Functions — Python v2.7 documentation without a great need.

Very logical.
Thanks for the reply.