If you actually ran that in Java, I think you'd find it probably prints out true because of string interning, but that's somewhat irrelevant.
I'm not sure what you mean by "replaces it with the object it is referring to". What actually happens is that when you write a == b, Python calls a.__eq__(b), which is just like any other method call on a with b as an argument.
If you want an equivalent to Java-like ==, use the is operator: a is b. That compares whether the name a refers to the same object as b, regardless of whether they compare as equal.
If you actually ran that in Java, I think you'd find it probably prints out true because of string interning, but that's somewhat irrelevant.
I'm not sure what you mean by "replaces it with the object it is referring to". What actually happens is that when you write a == b, Python calls a.__eq__(b), which is just like any other method call on a with b as an argument.
If you want an equivalent to Java-like ==, use the is operator: a is b. That compares whether the name a refers to the same object as b, regardless of whether they compare as equal.
Python interning:
>>> a = "hello"
>>> b = "hello"
>>> c = "world"
>>> id(a)
4299882336
>>> id(b)
4299882336
>>> id(c)
4299882384
Short strings tend to get interned automatically, explaining why a is b == True. See here for more.
django - Find all references to an object in python - Stack Overflow
How to get an object name?
python - How to print instances of a class using print()? - Stack Overflow
How to store an object reference in a variable?
It represents an infinite loop within the structure. An example:
In [1]: l = [1, 2]
In [2]: l[0] = l
In [3]: l
Out[3]: [[...], 2]
l's first item is itself. It's a recursive reference, and so python can't reasonably display its contents. Instead it shows [...]
Depending on the context here it could different things:
indexing/slicing with Ellipsis
I think it's not implemented for any python class but it should represent an arbitary number of data structure nestings (as much needed).
So for example: a[..., 1] should return all the second elements of the innermost nested structure:
>>> import numpy as np
>>> a = np.arange(27).reshape(3,3,3) # 3dimensional array
>>> a[..., 1] # this returns a slice through the array in the third dimension
array([[ 1, 4, 7],
[10, 13, 16],
[19, 22, 25]])
>>> a[0, ...] # This returns a slice through the first dimension
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
and to check for this ... you compare it to an Ellipsis (this is a singleton so recommended is using is:
>>> ... is Ellipsis
True
>>> Ellipsis in [...]
True
# Another (more or less) equivalent alternative to the previous line:
>>> any(i is Ellipsis for i in [1, ..., 2])
True
Recursive Datastructures
The other case in which you see an [...] in your output is if you have the sequence inside the sequence itself. Here it stands for an infinite deeply nested sequence (that's not printable). For example:
>>> alist = ['a', 'b', 'c']
>>> alist[0] = alist
>>> alist
[[...], 'b', 'c']
# Infinite deeply nested so you can use as many leading [0] as you want
>>> alist[0][1]
'b'
>>> alist[0][0][0][0][0][1]
'b'
>>> alist[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][1]
'b'
You can even replace it several times:
>>> alist[2] = alist
>>> alist
[[...], 'b', [...]]
>>> alist[1] = alist
>>> alist
[[...], [...], [...]]
To test if you have any such recursion in your output you need to check if the data-structure itself is also one of the elements:
>>> alist in alist
True
>>> any(i is alist for i in alist)
True
Another way to get a more meaningful output is using pprint.pprint:
>>> import pprint
>>> pprint.pprint(alist) # Assuming you only replaced the first element:
[<Recursion on list with id=1628861250120>, 'b', 'c']
Python's gc module has several useful functions, but it sounds like gc.get_referrers() is what you're looking for. Here's an example:
import gc
def foo():
a = [2, 4, 6]
b = [1, 4, 7]
l = [a, b]
d = dict(a=a)
return l, d
l, d = foo()
r1 = gc.get_referrers(l[0])
r2 = gc.get_referrers(l[1])
print r1
print r2
When I run that, I see the following output:
[[[2, 4, 6], [1, 4, 7]], {'a': [2, 4, 6]}]
[[[2, 4, 6], [1, 4, 7]]]
You can see that the first line is l and d, and the second line is just l.
In my brief experiments, I've found that the results are not always this clean. Interned strings and tuples, for example, have more referrers than you would expect.
Python's standard library has gc module containing garbage collector API. One of the function you possible want to have is
gc.get_objects()
This function returns list of all objects currently tracked by garbage collector. The next step is to analyze it.
If you know the object you want to track you can use sys module's getrefcount function:
>>> x = object()
>>> sys.getrefcount(x)
2
>>> y = x
>>> sys.getrefcount(x)
3
I'm trying to print the object's name from inside the class definition. Basically if I have t = class() and then call a function "t.printObjectName()", I want the function to print its object "t" or it's "self". Is this possible?
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).
If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.
As Chris Lutz explains, this is defined by the __repr__ method in your class.
From the documentation of repr():
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__repr__()method.
Given the following class Test:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f"<Test a:{self.a} b:{self.b}>"
def __str__(self):
return f"From str method of Test: a is {self.a}, b is {self.b}"
..it will act the following way in the Python shell:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print(repr(t))
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead
If no __repr__ method is defined then the default is used, which is roughly equivalent to:
def __repr__(self):
cls = self.__class__
return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"