This question already has answers here:
How to get a function name as a string?
(14 answers)
Closed 6 years ago.
I'm using format to test a function in Python. I would like the output of a function
def test(f,k):
print "{0}({1})={2}".format(f,k,f(k))
given
test(Sqrt,4)
to be
Sqrt(4)=2
But format is giving back the type 'function' and a memory address inside angle braces. Is there a neat way to shorten the output to get what I'm after?
You are looking to use __name__:
def test(f,k):
print("{0}({1})={2}".format(f.__name__,k,f(k)))
test(sqrt, 2)
Output:
sqrt(2)=1.4142135623730951
From the "Callable types" section of the Data Model docs here , __name__ is simply:
__name__ func_name : The function’s name.
Read the documentation carefully to understand what is available to you when wanting to use these types of attributes. Typically, this will be available to callable types (e.g. when defining a method or class, the __name__ attribute will be available to you). But if you simply define a non-callable, something like:
x = 5
and try to call x.__name__, you will be met with an AttributeError
Unlike most objects in Python, functions have a __name__ attribute set to the name they were defined with. You could use that:
print "{0}({1})={2}".format(f.__name__, k, f(k))
Classes also have a __name__, but most other callables don't. If f is some other kind of callable, you'll have to deal with it differently, in a manner that will depend on what kind of callable it is and whether you control its implementation.
Related
This question already has answers here:
How to create dynamical scoped variables in Python?
(4 answers)
Closed 2 years ago.
Why, in this code, can't I access db or file from inside do_more()?
def do_stuff(queue):
db = getDbConn()
while True:
file = queue.get() #DirEntry object
...
do_more(otherObject)
q.task_done()
I'm aware I could pass db and file as arguments to do_more(), but I feel like those variables should just be available in functions called from other functions. It works that way from main to first level functions. What am I missing here?
In the code you provided, you don't even attempt using the variables from do_stuff.
But as a general rule, you should be able to use variables from a parent function inside a child function, either by passing them as variables or by using them when initializing the child function, like this:
def foo():
foo2 = "foo"
def bar():
print(foo2)
bar()
foo()
If i did not answer your question let me know.
no , you cant access those variables , I know what you think , which is wrong.
you can access variables inside loops and if statements, not here.
imagine you have a function which is used in many different places, in that case you have access from this function to many variables which makes things complicated.
functions should be stand-alone objects which take some arguments do stuff and return something.so inside a function scope you can only see variables which are defined there and the arguments passed from the parent function using parenthesis.
This question already has answers here:
Obtaining closures at runtime [duplicate]
(1 answer)
How to open a closure in python?
(5 answers)
Closed 2 years ago.
I would like to know if there is any method to check whether two functions have the same arguments at runtime in python 3.
Basically, I have this function (func) that takes two arguments and perform some sort of computation. I want to check whether or not a and b have the same arguments' values at runtime
a = func(2, 3)
b = func(2, 3)
a.argsvalue == b.argsvalue
It is not feasible to run the code before and check the results because I am implementing a lazy framework. My main goal is to be able to understand what are the arguments of the function because there is one variable argument that I do not care but there is one static that is created before running the function.
##EDIT
I actually solved this problem using the inspect module (getclosure) for those who are interested. Thank you so much for the comments it helped me to familiarize myself with the terminology. I was actually looking for the closure, which I assigned dynamically.
when you do this - a.argsvalue == b.argsvalue you try to access a member of the value returned from the function.
so, if your "func" would return an object having the args you called it with (which sound like a weird thing to do) you would be able to access it.
anyway, if you need these values, just store them before sending them to the function, and then you can do whatever you want with them.
This question already has an answer here:
Can't dynamically bind __repr__/__str__ to a class created with type [duplicate]
(1 answer)
Closed 3 years ago.
I'm curious how repr works. It can't be exactly
def repr_(x):
return x.__repr__()
since that does not work on classes, namely
repr_(int)
causes an error since int's repr expects an int object as the first argument. I know that I can customize a class's repr by creating a metaclass with a desired __repr__, but I want to know how does Python's built in repr work? And how does it specifically handle the case of having a class passed into it.
Does it do something like a try catch where it first tries what my repr_ does and then looks up the MRO for other reprs? Or something else?
Figured it out. If we inspect how Python internally computes repr, which we can see in the source file object.c, we can see that repr is essentially
def repr_(x):
return x.__class__.__repr__(x)
import datetime
today=datetime.date.today()
print(repr(today))
for objects of classes, repr basically displays unambiguous output when obj call is their.
Documentation https://www.cmi.ac.in/~madhavan/courses/prog2-2015/docs/python-3.4.2-docs-html/library/functions.html#repr
Return a string containing a printable representation of an object.
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.
This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 6 years ago.
I am trying to understand the background of why the following works:
def part_string(items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
my_indexes = (2,1)
my_string = 'ABCDEFG'
function_instance = part_string(my_indexes)
print(function_instance(my_string))
# also works: print(part_string(my_indexes)(my_string))
how come I can pass my_string to function_instance object even though I already passed my_indexes attributes to part_string() when creating function_instance? why Python accepts my_string implicitly?
I guess it has something to do with the following, so more questions here:
what is obj in g(obj)? can this be something other e.g. g(stuff) (like with self which is just a convention)?
what if I want to pass 2 objects to function_instance? how do I refer to them in g(obj)?
Can You recommend some reading on this?
What you're encountering is a closure.
When you write part_string(my_indexes) you're creating a new function, and upon calling it, you use the old variables you gave to part_string together with the new variables given to function_instance.
You may name the inner function whatever you want, and there is no convention. (obj is used in here but it can be pie. There are no conventions for this except func for function closures (decorators).
If you wish to pass two variables to the function, you may define two variables to the g(obj) function:
def g(var1, var2):
...
Here's some more info regarding closures in python.
This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 9 years ago.
I got this:
tu = ("func1", "func2", "func3")
And with the operation I am looking for I would get this for the first string:
moduleA.func1()
I know how to concatenate strings, but is there a way to join into a callable string?
getattr(moduleA, 'func1')() == moduleA.func1()
You should use getattr builtin function. Try:
getattr(moduleA, 'func1')()
If you mean get a function or method on a class or module, all entities (including classes, modules, functions, and methods) are objects, so you can do a func = getattr(thing 'func1') to get the function, then func() to call it.