'id' is a bad variable name in Python

Why is it bad to name a variable id in Python?


Asked by: Melissa559 | Posted: 28-01-2022






Answer 1

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.

Answered by: Grace339 | Posted: 01-03-2022



Answer 2

In PEP 8 - Style Guide for Python Code, the following guidance appears in the section Descriptive: Naming Styles :

  • single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

So, to answer the question, an example that applies this guideline is:

id_ = 42

Including the trailing underscore in the variable name makes the intent clear (to those familiar with the guidance in PEP 8).

Answered by: Nicole608 | Posted: 01-03-2022



Answer 3

id is a built-in function that gives the identity of an object (which is also its memory address in CPython). If you name one of your functions id, you will have to say builtins.id to get the original (or __builtins__.id in CPython). Renaming id globally is confusing in anything but a small script.

However, reusing built-in names as variables isn't all that bad as long as the use is local. Python has a lot of built-in functions that (1) have common names and (2) you will not use much anyway. Using these as local variables or as members of an object is OK because it's obvious from context what you're doing:

Example:

def numbered(filename):
    with open(filename) as file:
        for i, input in enumerate(file):
            print("%s:\t%s" % (i, input), end='')

Some built-ins with tempting names:

  • id
  • file
  • list, dict
  • map
  • all, any
  • complex, int
  • dir
  • input
  • slice
  • buffer
  • sum
  • min, max
  • object

Answered by: Kimberly665 | Posted: 01-03-2022



Answer 4

I might say something unpopular here: id() is a rather specialized built-in function that is rarely used in business logic. Therefore I don't see a problem in using it as a variable name in a tight and well-written function, where it's clear that id doesn't mean the built-in function.

Answered by: Aida652 | Posted: 01-03-2022



Answer 5

Others have mentioned that it's confusing, but I want to expand on why. Here's an example, based on a true story. Basically, I wrote a class that takes an id parameter but then tried to use the builtin id later.

class Employee:
    def __init__(self, name, id):
        """Create employee, with their name and badge id."""
        self.name = name
        self.id = id
        # ... lots more code, making you forget about the parameter names
        print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))

tay = Employee('Taylor Swift', 1985)

Expected output:

Created Employee 'Taylor Swift' at 0x7efde30ae910

Actual output:

Traceback (most recent call last):
  File "company.py", line 9, in <module>
    tay = Employee('Taylor Swift', 1985)
  File "company.py", line 7, in __init__
    print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
TypeError: 'int' object is not callable

Huh? Where am I trying to call an int? Those are all builtins...

If I had named it badge_id or id_, I wouldn't have had this problem.

Answered by: Marcus202 | Posted: 01-03-2022



Answer 6

It's bad to name any variable after a built in function. One of the reasons is because it can be confusing to a reader that doesn't know the name is overridden.

Answered by: Aldus206 | Posted: 01-03-2022



Answer 7

id is a built-in function in Python. Assigning a value to id will override the function. It is best to either add a prefix as in some_id or use it in a different capitalization as in ID.

The built in function takes a single argument and returns an integer for the memory address of the object that you passed (in CPython).

>>> id(1)
9787760
>>> x = 1
>>> id(x)
9787760

Answered by: John851 | Posted: 01-03-2022



Answer 8

Because it's the name of a builtin function.

Answered by: Brooke920 | Posted: 01-03-2022



Answer 9

Because python is a dynamic language, it's not usually a good idea to give a variable and a function the same name. id() is a function in python, so it's recommend not to use a variable named id. Bearing that in mind, that applies to all functions that you might use... a variable shouldn't have the same name as a function.

Answered by: Julia805 | Posted: 01-03-2022



Similar questions

python - Variable number of inputs with Django forms possible?

Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload. So how do I get django t...


Using Python split to splice a variable together

I have this list ["camilla_farnestam@hotmail.com : martin00", ""], How do I split so it only be left with: camilla_farnestam@hotmail.com:martin00


python - PY: Url Encode without variable name

Is there a way in python to url encode list without variables names? for example q=['with space1', 'with space2'] into qescaped=['with%20space1', 'with%20space2']


python variable scope

I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this def some_function(): foo.some_method() # some other code if __name__ == '__main__' : foo = Some_Object() some_function() even ...


python - Getting every odd variable in a list?

If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that? For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3].


python - How do I save to a field that is specified in a variable?

I want to do something like this: # models.py class Model(models.Model): name_in_my_model = models.CharField(max_length=100) # later fieldname = 'name_in_my_model' # this is what I want to do somehow: obj = Model.objects.get(pk=1) obj.fieldname = 'new name' obj.save() Is this possible? I'm making a reusable application, and the user needs to specify a name of a field that is going to be updat...


python - How to add a variable to the module I import from?

What I want to do is something like this: template.py def dummy_func(): print(VAR) # more functions like this to follow fabfile.py # this gets called by fabric (fabfile.org) # safe to think of it as ant build.xml import template template.VAR = 'some_val' from template import * Namely I have a template module other modules should 'extend' contributing the required variables. Can this...


In Python how should I test if a variable is None, True or False

I have a function that can return one of three things: success (True) failure (False) error reading/parsing stream (None) My question is, if I'm not supposed to test against True or False, how should I see what the result is. Below is how I'm currently doing it: result = simulate(open("myfile")) i...


tar - how do i get the byte count of a variable in python just like wc -c gives in unix

i am facing some problem with files with huge data. i need to skip doing some execution on those files. i get the data of the file into a variable. now i need to get the byte of the variable and if it is greater than 102400 , then print a message. update : i cannot open the files , since it is present in a tar file. the content is already getting copied to a variable called 'data' i am able to pr...


python - cross module variable

from here I got an idea about how using variables from other modules. this all works fine with import foo as bar But I don't want to import my modules as "bar" I want to use it without any prefix like from foo import * Using this it´s impossible to modify va...


Python - one variable equals another variable when it shouldn't

Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop. i=1 while (i&gt;0): x_past = x_present j=0 while(j&lt;3): value=0 k=0 while(k&lt;3): if(k!=j): if(i==1): if(k&gt;j): value=val...


python - Variable number of inputs with Django forms possible?

Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload. So how do I get django t...


Using Python split to splice a variable together

I have this list ["camilla_farnestam@hotmail.com : martin00", ""], How do I split so it only be left with: camilla_farnestam@hotmail.com:martin00


Easy way to check that a variable is defined in python?

This question already has answers here:


python - PY: Url Encode without variable name

Is there a way in python to url encode list without variables names? for example q=['with space1', 'with space2'] into qescaped=['with%20space1', 'with%20space2']


Unable to put a variable in Python's print

My code: year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\"&gt;" I run it and I get File "/tmp/aku.py", line 2 photo=[{70,72,73},{64,65,68},{79,80,81,8...


python class variable not visible in __init__?

This code produces an error message, which I found surprising: class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() Can anyone provide enlightenment?


python - How do I access the request object or any other variable in a form's clean() method?

I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?


python - how to tell a variable is iterable but not a string

I have a function that take an argument which can be either a single item or a double item: def iterable(arg) if #arg is an iterable: print "yes" else: print "no" so that: >>> iterable( ("f","f") ) yes >>> iterable( ["f","f"] ) yes >>> iterable("ff") no The problem is that string is technically iterable, so I can't just catch the ValueError w...


python - How to set LANG variable in Windows?

I'm making an application that supports multi language. And I am using gettext and locale to solve this issue. How to set LANG variable in Windows? In Linux and Unix-like systems it's just as simple as $ LANG=en_US python appname.py And it will automatically set the locale to that particular language. But in Windows, the C:\&gt;SET LANG=en_US py...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top