Questions tagged [repr]
Python built-in function that returns a string from an arbitrary object. Abbreviation for "representation".
269
questions
0
votes
1
answer
39
views
How to partially overwrite __repr__ for a class in python?
I'm learning Python and it's my first question here :)
So I am defining a class:
class Nr_Heap:
def __init__(self):
self._top = None #a queue() of Point()
self._tmp_bottom ...
1
vote
1
answer
31
views
When did CPython's `repr` start handling recursive data structures?
This MWE in the past would cause a stack overflow, as x references y that references x:
class Ref:
def __init__(self, name):
self.name = name
self.value = None
def __repr__(...
0
votes
1
answer
27
views
Get a string when running an object class through str.replace(obj_cls, "new string")
I have an object class:
class Color(object):
def __init__(self, color):
self.color = color
I want to run the following commands:
blue = Color("blue")
print blue
"The pen ...
1
vote
1
answer
74
views
Why does Pycharm Console do this with my __repr__ method?
class B:
def __init__(self):
print('boo!')
self.a = []
def __repr__(self):
print(len(self.a))
ret = ''
for a in self.a:
ret += str(a)
...
0
votes
1
answer
130
views
Can a dataclass field format its value for the repr?
I have a Node class holding RGB data in both hex and HSV form. I'll be using this to sort colors in various ways and would prefer the HSV tuple to remain in float form for comparisons instead of ...
6
votes
0
answers
165
views
Nativecall Segfaults Getting Tuple from Rust
Per the Rust FFI Omnibus the following should work.
This is a rust cdylib lib.rs named "foo" made with cargo build...
use std::convert::From;
// Rust FFI Omnibus: Tuples
// http://...
1
vote
0
answers
54
views
Is it recommended to have long repr strings in Python? [closed]
let's say i have a big python class with a lot of attributes. i want to add a __repr__ to it to allow for better debugging. naturally, the __repr__ would return a string with its attributes to be ...
3
votes
1
answer
418
views
Exclude default fields from python `dataclass` `__repr__`
Summary
I have a dataclass with 10+ fields. print()ing them buries interesting context in a wall of defaults - let's make them friendlier by not needlessly repeating those.
Dataclasses in Python
...
-4
votes
1
answer
43
views
when I use the repr function it is not working
I am trying to remove the ' ' in my list by using the repr function but it is not removing the ' '
code:
output:
output
input
0
votes
2
answers
79
views
How to print a list containing custom objects from a class?
I'm starting to learn about OOP in Python. I have a simple problem like this. For example, I have a class called Cat, and a class called ListOfCat which contains a List of Cat. Now I want to print the ...
1
vote
1
answer
97
views
Python's BeautifulTable modifies output
I'm forming a BeautifulTable table from dict, whose keys are string sets of digits (e.g. "21608", "32099", "02978"). The keys of the dict are to become the first column ...
0
votes
0
answers
17
views
what method is executed instread of __repr__ in jupyter notebook cells? [duplicate]
I have a data frame, say df, and when I go with print(df) or repr(df), I get a not very palatable output.
print(df) result:
but when I just put a naked df in the cell and run it, I get something like ...
0
votes
0
answers
12
views
override the __repr__ in list inherited class in Python3
Here's my own class which is inherited from the list class:
class UniqueList(list):
def __init__(self):
super().__init__()
def add_el(self, el: object):
if el not in self:
...
0
votes
1
answer
52
views
Why are str(repr(p)) and print(repr(p)) not the same?
I've read in this thread all the answers, but I got stuck in the following example:
Example:
class Person:
pass
p=Person()
According to this source, if you call repr(p) you will get this as ...
-1
votes
1
answer
33
views
Get __repr__ to return string that has same value when passed to eval?
I don't fully understand what is going on here. Why does the returned string from repr evaluate to False? If anyone can expand on what I'm not understanding here, that would be really appreciated.
...
-1
votes
1
answer
44
views
python __repr__(self): does not return
I have a below code in which the magic method repr(self) does not return my instance parameters below is the code
i am trying to learn the oops concept
class Item:
pay_rate = 0.8 # The pay rate ...
-2
votes
1
answer
51
views
I have a class with one required and two optional parameters, and a repr method which returns with one of the optional params, whichever is given [closed]
class MyClass():
def __init__(self, name, high=None, low=None):
self.name = name
if low:
self.low = low
elif high:
self.high = high
else:
...
3
votes
0
answers
41
views
Python: `foo = object.method; foo is object.method` returns `False` despite identical reprs [duplicate]
>>> a_string = "this is a string"
>>> a_method = a_string.upper
>>> a_string.upper()
'THIS IS A STRING'
>>> a_method()
'THIS IS A STRING'
>>> ...
1
vote
0
answers
23
views
I have a promlem when I try to write out a string saved in a variable into a txt file [duplicate]
I coded a little Python programm that gets the content of files in the internet.
It´s working with cURL and tkinter.
The code I wrote:
from tkinter import *
import tkinter as tk
import socket
import ...
3
votes
3
answers
406
views
Formatted Python string uses neither repr nor str - what is happening?
I have an enumeration ResourceType that inherits from both namedtuple and Enum, and I don't override __str__ or __repr__ anywhere. When I format an instance of that enum I unexpectedly get just the ...
1
vote
1
answer
106
views
How can I write a numpy.array to a file and retain all of the digits?
Suppose I have a numpy array with some high precision floats obtained from scipy.optimize.minimize, such as: arr = np.array([9.2387213981273981, 0.3219837123801298]). I would like to write this array ...
0
votes
1
answer
224
views
Using __str__ & __repr__ Python methods to print a list from within a class method
Firstly, thank you for taking the time to consider my question - I've included a lot of code, I certainly appreciate your support!
I have written two classes:
PlayingCard and Deck
I would like to ...
1
vote
1
answer
38
views
What does ! mean in Python? [duplicate]
I am trying to build a list containing children lisats inside the original list, and iterate over that list. I have a book called Python Cookbook, they used the code below to solve the question. What ...
0
votes
2
answers
165
views
RecursionError when inheriting from float and using str and repr
I was testing some features in Python for fun ;)
But I have a recursion error that I don't understand
class Test(float):
def __new__(cls, value):
return super().__new__(cls, value)
...
0
votes
0
answers
168
views
How can I get a repr of a DataFrame that is a valid Python expression?
I would like to unit test some code that returns a pd.DataFrame. The code already returns the correct value, and I'd like to use pd.testing.assert_frame_equal to assert that it returns this value so ...
2
votes
1
answer
50
views
Unexpected behavior when calling super().__repr__() on a subclass of set?
See edit below for an explanation of this behavior (in CPython)
In Python 3.9.5, I'm creating two custom collection types, one inheriting from list and the other from set. I want them to have custom ...
-1
votes
1
answer
34
views
Two values are same and different after defining a=b=class_name(value1) b=class_name(value2) in python
In the following code, I understand that the print of tree(named in the code) and parent(named in the code) should not be the same. But I do not understand, why the tree is always updating according ...
0
votes
0
answers
43
views
python eval(repr(file_handle)) fails with synax error
I'm trying to pass a file handle through some hoops that lead to me wanting to pass the file handle as it's repr to pull it back into existence later on. But, I've run into a problem. The built-in ...
2
votes
1
answer
61
views
Difference between a=b=class_name(value) and a=class_name(value) b=class_name(value) in python [not duplicate]
In the following code, if I use tree = parent = node(leaf_1)
the tree and parent are always having the same print result; whereas, if I change that line to tree = node(leaf_1) and parent = node(leaf_1)...
1
vote
1
answer
155
views
Error while rewriting __repr__ 'TypeError-expected 0 arguments, got 1'
I have an error while debugging the following code by figuring out the usage of __repr__.
class node(object):
def __init__(self, value):
self.value = value
self.children = []
...
0
votes
1
answer
160
views
Self defined __repr__ for pretty print in Python
I have got a piece of code from here, about using the __repr__ to get kind of pretty print. However, I want to modify this code, because while using it in a loop, I always got error: maximum ...
0
votes
0
answers
51
views
How to write a __repr__ when one of the inputs is a dataframe?
I have a class that takes a pandas dataframe as one of parameters. I've not been very good at adding __repr__ to my code so now I'm trying to go back and add to all the existing codebase. But here I ...
2
votes
2
answers
369
views
custom __repr__ as a class method for a class derived from Enum
I have a class which is derived from enum.Enum.
Now repr in enum.Enum refers to the member of the enum.Enum not the entire class.
For Example
from enum import Enum
class endpoints(Enum):
""&...
0
votes
0
answers
59
views
Why do I cannot use __repr__ data outside of a class
I started Python and struggle on using __repr__ data outside of a class. Printing the data outputs a list with lists (exactly what I wanted to do), example:
print(test) leads to:
[['Food', '-10.15', '-...
0
votes
1
answer
104
views
why is print(eval(repr(instance))) calling the str function and not repr function?
in the below code block why is the statement print(new) calling str function and not calling repr function. is it because the print function was called?
class Robot:
def __init__(self, name, ...
0
votes
0
answers
20
views
Cannot print object repr using __repr__ in Python
This is my directory's structure:
This is the declaration.py code:
class Declaration:
def __init__(self, prop, prop_value):
self.prop = prop
self.prop_value = prop_value
def ...
0
votes
1
answer
291
views
How should I define a __repr__ for a class hierarchy in python?
Given the following code:
class Base:
__slots__ = 'base_field',
def __init__(self, base_field):
self.base_field = base_field
def __repr__(self):
return f"{self....
1
vote
0
answers
32
views
__str__ and __repr__ for Integers in Python [duplicate]
New to Python. Basic understanding is __repr__() gives the object representation/info (I know it sounds silly) of an object while __str__() gives the String representation of an object.
When we do ...
0
votes
1
answer
1k
views
__init__ and create a linked list in Python
I am pretty new to Python. Although I can do some manipulation in arrays and define a new function, it is my first time to use class and __init__. I am solving the linked list question in Python and ...
0
votes
0
answers
46
views
Repr of lxml node
Is there a way to customize how an etree node appears for debugging purposes? It seems to give its memory address by default:
[<Element edition at 0x10dd2e998>, <Element edition at ...
0
votes
1
answer
54
views
python why does it call __str__ instead of __repr__ and why is the print(obj) not working and throws exception
I have a litte problem because whenever i run the code print(obj) in the try/except part it throws an exception. i followed it with the debugging tool and it jumps right in the str method but i coded ...
5
votes
5
answers
581
views
How to set a repr for a function itself? [duplicate]
__repr__ is used to return a string representation of an object, but in Python a function is also an object itself, and can have attributes.
How do I set the __repr__ of a function?
I see here that an ...
1
vote
1
answer
86
views
Where to find __repr__ of Python weakref proxy?
I am a bit puzzled right now about the following:
import weakref
class A:
def __init__(self, p):
self.p = p
def __repr__(self):
return f"{type(self).__name__}(p={...
0
votes
2
answers
68
views
In Python3 the behaviour of the inbuilt repr() function has changed when compared to Python2
In Python3 the behaviour of the inbuilt repr() function has changed when compared to Python2.
In python2
repr("Дует Світязь")
"'\\xd0\\x94\\xd1\\x83\\xd0\\xb5\\xd1\\x82 \\xd0\\xa1\\xd0\\...
1
vote
2
answers
505
views
Python's __repr__ method when __init__ takes an array as argument
I am quite new to OOP with Python, and trying to understand how the __repr__ method should output in this particular instance.
When initialising the Playlist class, an array, containing song objects, ...
1
vote
0
answers
47
views
Define different output for the _repr_ method when printing a list of objects
I have a custom class which has implemented the _repr_ method, printing out all the properties of this object, for example:
Id: XXX,
Name: XXX
PropA: XXX,
PropB: XXX,
PropC: XXX ...
Problem -
Is ...
1
vote
1
answer
362
views
Python: How to write __repr__ when having __slots__
I am wondering how to implement the __repr__ method for a class with __slots__. As far as I understand __repr__, it is supposed to return a string which can be used to construct the object of which we ...
4
votes
0
answers
31
views
Where/How is the function representation as shown in IPython REPL generated? [duplicate]
For example, in REPL:
In [0]: def func(x=0, y=1):
...: return x
In [1]: func
Out [1]: <function __main__.func(x=0, y=1)>
But how do I print it or store in a variable?
In [2]: print(...
1
vote
2
answers
79
views
Python TypeError: must be str, not Atom
Can someone tell me in beginner friendly way why am I not being able to print the Molecule name (here in this case 'NaCl') ?
if I replace return Molecule([self, other]) with return Molecule([self....
1
vote
1
answer
277
views
Why does changing `__repr__` in a pandas DataFrame not change its display?
Purely pedagogical, not trying to change anything. We have
class A:
def __init__(self):
pass
def __repr__(self):
return "abc"
a = A()
a
> abc
and
class B:
...