From the course: Python Data Science Mistakes to Avoid

Name clashing with Python standard library - Python Tutorial

From the course: Python Data Science Mistakes to Avoid

Start my 1-month free trial

Name clashing with Python standard library

- [Instructor] A common mistake that can occur when programming is name clashing with modules from the Python Standard Library. The Python Standard Library consists of a wide range of modules with tools that help programmers in their everyday work. To view the entire Python Standard Library, you can go to this site. One of the built-in modules in the Python Standard Library is known as Built-in Types. Built-in Types refer to the datatypes that are built into Python's interpreter. One of the built-in types is list. Now there are a couple of different ways to create a list. One way is to use a pair of square brackets, and another way is to use the type constructor. First, I'll create a list using a pair of square brackets, containing the items zero, one, two, three, and four. And I'll save it in a variable named list. Note that the name of this variable is also the name of the built-in type, list. Now I'll do a check to see the value of this variable. This confirms that the variable named list refers to a list containing zero, one, two, three, four. Next, I'll try to create a new empty list by calling the list constructor and not passing in an argument. When I run the cell, I get a type error that says, "List object is not callable." The error occurred because, in the first cell, the name I gave to the variable clashed with the built-in type list. From that cell onwards, the name list refer to the list containing zero, one, two, three, four, and no longer refer to the built-in type list. So when I tried to call the constructor of the built-in type list in this cell, it did not work. To avoid name clashing, make sure to use names that have not been defined already in the Python Standard Library. In this case, I could have used the name List A, for example, instead of name clashing. I'll go ahead and do that. Now, I'll restart the kernel and clear output and then run all the cells again. There, as you can see, everything works now and I did not get any errors. Now that you've learnt how name clashing with Python Standard Library modules causes problems as well as how to avoid it, make sure to keep that in mind as you code and remember to name variables carefully.

Contents