Default function in python shell [duplicate] - python

This question already has answers here:
Python console default hex display
(5 answers)
Closed 1 year ago.
Entering an expression in Python shell outputs the repr() of the expression.
Is it possible to set this default function to some user defined function?

What you are looking for is sys.displayhook:
sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook.
Normal behaviour:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2021, 11, 25, 15, 26, 1, 772968)
then
>>> import sys
>>> def new_hook(value):
... sys.stdout.write(str(value))
... sys.stdout.write("\n")
...
>>> sys.displayhook = new_hook
modified behaviour:
>>> datetime.now()
2021-11-25 15:26:14.177267

Related

Formatting problem from string to Datetime [duplicate]

This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 5 months ago.
I'm trying to parse a string with the datetime standard library module and then display it.
When I try this code, the output looks correct:
>>> import datetime
>>> endDate = datetime.datetime.strptime("2022-05-03", '%Y-%m-%d').date()
>>> print(endDate)
2022-05-03
But it changes if the endDate is put into a list or tuple:
>>> print([endDate])
[datetime.date(2022, 5, 3)]
Why does the output have the "datetime.date" text?
>>> from datetime import datetime
>>> endDate = datetime.strptime("2022-05-03", '%Y-%m-%d').date()
When you printed the date object, it used str representation of the date object.
>>> str(endDate)
'2022-05-03'
When you included that in a container and printed it, the container internally uses repr representation of the object
>>> repr(endDate)
'datetime.date(2022, 5, 3)'
print function by default converts all the objects passed to it to a String with str.
All non-keyword arguments are converted to strings like str() does
To understand this better, we can create a class which implements both __str__ and __repr__ functions like this
>>> class Test:
... def __str__(self):
... return "TEST_FROM_STR"
...
... def __repr__(self):
... return "TEST_FROM_REPR"
...
Now, we can create instances of that class and print them separately and with list, like this
>>> Test()
TEST_FROM_REPR
>>> [Test()]
[TEST_FROM_REPR]
>>> print(Test())
TEST_FROM_STR
>>> print([Test()])
[TEST_FROM_REPR]

Function argument for an f-string '=' debugging operator [duplicate]

This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 1 year ago.
How to pass a variable for an f-string '=' debugging operator?
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'{var = }')
test = 5
print_var(test)
I expect print_var(test) to print the variable name from outside the function, ie.
test = 5
Please refer to Python: Print a variable's name and value? for the context of the question.
In f-strings you need to put the variable that needs to be printed between accolades. Like this:
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'var = {var}')
Running the test yields the following:
test = 5
print_var(test)
>>>2021-10-06 11:32:05 var = 5

How to dynamically print the arguments used in a function call? [duplicate]

This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 2 years ago.
I have the following code:
var1='aaa'
var2='bbb'
debug(var1, var2)
I would like the debug function to print:
"var1=aaa var2=bbb"
My function currently looks like
def debug(thing1, thing2):
print(f"{thing1=} {thing2=}")
and outputs:
"thing1=aaa thing2=bbb"
I tried using locals() in the function as well but got the same output. I would like to have "var1" and "var2" in the output without hardcoding them in the print statement.
You need to come at this problem in a slightly different way.
As stated, there is no way for debug to know the variable names.
You need to supply that information:
>>> import pprint
>>> var1 = 'aaa'
>>> var2 = 'bbb'
>>> def debug(**kwargs):
... pprint.pprint(kwargs, width=20)
...
>>> debug(var1=var1, var2=var2)
{'var1': 'aaa',
'var2': 'bbb'}

Do stuff with variable that has the same name of a string [duplicate]

This question already has answers here:
How to use string value as a variable name in Python? [duplicate]
(3 answers)
How do I create variable variables?
(17 answers)
Closed 4 years ago.
let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string?
For example change the variable's value or call a method if it's an object?
Thanks in advance
Variables are available through dictionaries locals() and globals(). If you want to access a particular variable by it's spring name, you can do e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x]
'hello'
You can also assign back to the variable using this approach, e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x] = 'something else'
>>> my_var
'something else'
Since functions are objects in Python, you can access any locally available functions in the same manner to call them.
>>> def my_test_function(n):
>>> return n*8
Accessing the method and calling it.
>>> locals()['my_test_function'](4)
32
For accessing attributes of objects by their name you can use getattr(), and setattr() to set them. For example, creating an object with a single property called your_prop.
class Example:
your_prop = 2
a = Example()
The value is available via your_prop.
>>> a.your_prop
2
The property can be accessed via name using getattr
>>> getattr(a, 'your_prop')
2
The property can be set using setattr:
>>> setattr(a, 'your_prop', 5)
>>> a.your_prop
5
Ok, let's suppose that you have lots of different functions: Aoo(), Boo(), Coo()... and let's suppose that you want to specify which of them to call via command line argument.
Now, that argument will be a string, so you need to call a function through its name, but you do not know in advance the name of the function.
One possible solution is to use exec():
def boo():
print("boo function")
def coo():
print("coo function")
Now:
argument = "boo"
exec(argument + "()")
>>> boo function
and
argument = "coo"
exec(argument + "()")
>>> coo function
It depends what you're trying to do, but you can scoop up whatever x is pointing to with locals() or globals():
def x(k):
return k + 1
string1 = "x"
the_function_x = locals()[string1]
print(the_function_x(3))
outputs 4 (it called the x function by utilizing string1).

How to call a function using dictionary key Value? [duplicate]

This question already has answers here:
Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?
(3 answers)
Closed 4 years ago.
Here I am trying to call a function using dictionary key value.
>>> def hello():
print('hello')
>>> a = {'+': hello()}
it just prints hello after executing this line.
>>> a['+']
If I call the dictionary using key value, it results nothing. What am I missing here?
Do not put () while you are using the function name as a value for the dictionary because as soon as python find () it will execute the function.
Instead just add the function name a = {'+': hello}
And then use the () while fetching the value from the dictionary
a["+"]()
You need a return call.
def hello():
return 'hello'
Or I think that is what you want
You should put your callable as the value into the dict and then call it.
>>> def hello():
print('hello')
>>> a = {'+': hello}
>>> a['+']()
hello

Categories

Resources