Python passing parameters as part of the function code - python-3.x

I have 2 functions as follows:
def test1(var):
return var*2
def test2(var):
return var*4
I want to pass a variable to form part of the code, something like below:
var='test2'
def new_test(var,4):
return var(4)
And I expect the output to be 16 (i.e. output from test2)
In excel, it is achievable via the function of =indirect(...). Is there any way to achieve that in Python?

Yes, instead of this:
var = 'test2'
def new_test(var, 4):
return var(4)
You can do this directly:
var = test2
def new_test(var, 4):
return var(4)
Functions are first class objects in Python.

Related

Python default 'wildcard' function - possible?

Here is my class code:
class Example:
def __init__(self):
self.parameter1 = 1
def standardFunction(self):
print("Hello")
Is it possible to initialise the Example class and make sure that every method that may be called for this particular instance will always point to the standardFunction?
For example:
ex1 = Example()
ex1.test1()
prints "Hello"
ex1.test2()
prints "Hello"
ex1.test3.test4()
prints "Hello"
ex1.test5().test6().IamBatman(42)
prints "Hello"
Basically, I would like to always have the Example.standardFunction() called, disregarding the string after the first "dot". Plus I don't know what's being put after the dot - it may be any string, int, float, or null.
Is it possible to achieve such behaviour with Python?
Yes we can achieve similar behavior in Python by overloading __getattr__. Like this,
class Example:
def __init__(self):
self.parameter1 = 1
def standardFunction(self):
print("Hello")
def __getattr__(self, name):
return self.standardFunction

How to check which function has been returned in python?

I have two methods which take different number of arguments. Here are the two functions:
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
I am using a function which will return one of these functions to main.I have stored this returned function in a variable named operation.
Since the number of parameters are different for both,how do I identify which function has been returned?
if(operation == jumpMX):
operation(IAS,list)
elif(operation == addMX):
operation(IAS)
What is the syntax for this?Thanks in advance!
You can identify a function through its __name__ attribute:
def foo():
pass
print(foo.__name__)
>>> foo
...or in your case:
operation.__name__ #will return either "jumpMX" or "addMX" depending on what function is stored in operation
Here's a demo you can modify to your needs:
import random #used only for demo purposes
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
def FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove():
# This will randomly return either jumpMX()
# or addMX to simulate different scenarios
funcs = [jumpMX, addMX]
randomFunc = random.choice(funcs)
return randomFunc
operation = FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove()
name = operation.__name__
if(name == "jumpMX"):
operation(IAS,list)
elif(name == "addMX"):
operation(IAS)
You can import those functions and test for equality like with most objects in python.
classes.py
class MyClass:
#staticmethod
def jump(self, ias, _list):
pass
#staticmethod
def add(self, ias):
pass
main.py
from classes import MyClass
myclass_instance = MyClass()
operation = get_op() # your function that returns MyClass.jump or MyClass.add
if operation == MyClass.jump:
operation(myclass_instance, ias, _list)
elif operation == MyClass.add:
operation(myclass_instance, ias)
However, I must emphasize that I don't know what you're trying to accomplish and this seems like a terribly contrived way of doing something like this.
Also, your python code examples are not properly formatted. See the PEP-8 which proposes a standard style-guide for python.

Decorating a decorator

I tried to do some argument modification on a decorator which decorates a function.
The original code looks like
#original_decorator(arg=some_object)
def calculate(a, b):
# complex business logic
raise Exception()
where original_decorator is responsible for exception handling.
What I want to achieve is to do some temporary modification on some_object and restore it's property after function returned.
And I've tried the following
def replace_arg(arg, add_some_property):
def decorator_wrapper(decorator_func):
def decorator_inner(*decorator_args, **decorator_kwargs):
def actual_wrapper(actual_func):
def actual_inner(*actual_args, **actual_kwargs):
original = arg['func']
arg['func'] = add_some_property
decorator_kwargs['arg'] = arg
result = actual_func(*actual_args, **actual_kwargs)
arg['func'] = original
return result
return actual_inner
return actual_wrapper
return retry_inner
return retry_wrapper
Also tried to place the modification logic in decorator_inner, but neither worked.
My Questions:
Is it possible to modify a decorator's argument?
If true, then how can I achieve it?

Calling various function based on input in python 3.x

I'm writing some code to get various data from a class (which extracts data from a '.csv' file). I was wondering if there was a way to call one of these methods based off the name of an input
I've attempted to create a function called get(), which takes in 'param_name' - the name of the method contained within the class that I want to call. I was wondering if there was a more elegant way to solve this without creating a large amount of if statements.
def get(param_name):
# Some initialisation of the .csv file goes here. This works as intended.
list_of_objects = [] # Initialised above, as a list of objects with methods function1(), function2() for getting data out of the .csv
for item in list_of_objects:
if param_name == "name of function 1":
return function1()
if param_name == "name of function 2":
return function2()
You could store your functions ina a dictionary as such:
function_dict = {
'function_1': function_1,
'function_2': function_2
}
To use these you could do:
function_to_use = function_dict.get(param_name)
function_to_use(*args, **kwargs) # *args, **kwargs are arguments to be used.
If you want to return a list after you have applied the function to all item in list_of_objects instead of the for loop you could do:
list(map(function_to_use, list_of_objects))
You could use __getattribute__:
class Alpha:
def f1(self):
print("F1")
x = Alpha()
x.__getattribute__('f1')()
You can do that using globals(), globals() returns a dict containing all methods and attributes.
def fun1():
print('this is fun1')
def fun2():
print('this is fun2')
def get(func_name):
globals()[func_name]()
get('fun1')
get('fun2')
Will Output:
this is fun1
this is fun2

Mocking a resource from outerscope of a function in python

I have a function that uses a dictionary, constructed out of the function, and do something. The function is like this:
TRANSLATION_TABLE = {#something}
def get_translate(tokens_and_tags):
results = []
for token, tag in tokens_and_tags:
results.append((TRANSLATION_TABLE.get(token, token), tag))
return results
Now I want to write test for it, but, I could not find how to mock the "TRANSLATION_TABLE" dictionary properly.
What is the correct way to test this function and mocking the dictionary?
You want to use dependency injection
def get_translate(tokens_and_tags, translation_table=None)
translation_table = translation_table or TRANSLATION_TABLE
Now you can inject a fake in your test.
def test_get_translate(...):
...
expect = ...
actual = get_translate(fake_tokens_and_tags, {...})
assert actual == expect.

Resources