Checking argument values at runtime in python [duplicate] - python

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.

Related

Python variable inheritance not working (as expected) [duplicate]

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.

In python, when does pass by reference occur? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 2 years ago.
I have a code as below,
attractions = [[] for i in range(5)]
def add_attraction(attraction):
attractions_for_destination = attractions[2]
attractions_for_destination.append(attraction)
return
pass by reference occurs in 3rd line "attractions_for_destination = attractions[2]". The general idea of pass by reference that I have is that it happens between actual parameter and formal parameter. But the above line is a simple assignment code. Can pass by reference happen in a simple assignment code?
If so, if I write
attractions_for_destination = attractions[2] + ": best attraction site"
will altering the value force the newly made variable to use a new memory space?
Saying pass by reference or pass by value isn't really applicable to python. For example consider Java. Everything in Java is pass by value, everything. However the value of an object is the reference to the object. So it is, in a way, pass by reference since mutating the object will be reflected to the calling context. Calling it "pass by value" is a bit confusing since for people used to C-family (where this distinction is more straightforward) assume that pass by value means you won't modify the underlying argument passed.
So saying Java is "pass by value" is true but possibly confusing. It is a more relevant statement at much lower levels of the language (like when talking about how the compiler handles passing arguments but not at the level of application programmer).
Python is similar. The confusion about the Java example actually lead Python to not say if it is pass by value/reference. http://stupidpythonideas.blogspot.com/2013/11/does-python-pass-by-value-or-by.html
So for programming, it is save to assume that any object is "passed by reference" (technically no but essentially yes). It is more complicated than that but that link explains it in more depth.

Calling a method from a constructor in python [duplicate]

This question already has answers here:
Python function calling order
(5 answers)
Closed 3 years ago.
The initial question I had was whether or not a method could be called from a Python constructor. The answer here suggests that it can, but this surprised me some as, based on my reading, python cannot use something that hasn't been previously defined in the code. Looking at the answers in the linked thread, it seems like they are using a method in the constructor that is defined later in the text. How is this possible in python?
Thanks.
When you would be running the code the class would be created , the function wouldn't be called
The function would only be called by object in main function by that time the definition of function would be compiled and known.
Try this
Declare a class and then call a function which is not a member of class * and also not declared
And declare it later , it would throw an error

% and/or format for function string [duplicate]

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.

The correct way to unpack keyword arguments (kwargs) [duplicate]

This question already has answers here:
Proper way to use **kwargs in Python
(14 answers)
Closed 8 years ago.
With keyword arguments, you can't just reference potential keyword values in the dict, since they may not be present. What's the best way to reference keyword values that may or may not be there? I find myself doing things like this:
def save_link(link, user, **kwargs):
if "auto" in kwargs:
auto = kwargs["auto"]
else:
auto = False
in order to provide default values and create a variable that is reliably present. Is there a better way?
You may use the get property of dict:
auto = kwargs.get('auto', False)
This allows for using a default value (Falsein this case).
However, please be quite careful with this approach, because this kind of code does not complain about wrong keyword arguments. Someone calls funct(1,2,auot=True) and everything looks ok. You might consider checking that the kwargs you receive belong to some certain list.

Categories