Issue
I'm trying to create a user defined function in which one of the arguments is a method (s_method)
to be applied to a sequence (seq)
and args_
are the arguments for s_method
. However, for simplicity, I'm only using lists as a sequence type here:
def this_function(args_, s_method, seq):
arguments = locals()
if type(seq) == list:
if s_method not in dir(type(seq)): # dir(type())
print('Method not found or some other error message here.')
else:
res_ = seq.arguments['s_method'](arguments['args_'])
return res
The expected output after calling the function would be:
new_list = this_function([1, 5], 'append', [3, 4, 2, 104])
print(new_list)
>>> [1,5,[3,4,2]]
what I want the function to do is seq.append(args_)
but, for some reason res_ = seq.arguments['s_method'](arguments['args_'])
is not working as intended, so I'm getting this error :
--------------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-89-b8df0448c005> in <cell line: 1>()
----> 1 output = this_function([1, 5], 'append', [3, 4, 2, 104])
2 print(output)
<ipython-input-88-6f8d5897c15c> in this_function(args_, s_method, seq)
11 'some error message here.')
12 else:
---> 13 res_ = seq.arguments['s_method'](arguments['args_'])
14
15 return res
AttributeError: 'list' object has no attribute 'arguments'
It's supposed to insert append
instead of 'arguments'
but this doesn't happen.
Evaluating separately I noticed that with everything I tried so far, I keep getting 'append'
which is a string... so, it's not the same as append
and therefore, every error is very much the same thing "no such attribute exists".
I've tried
seq_1 = [3, 4, 2, 104]
args_1 = [1, 5]
seq_method = 'append'
seq_2 = seq_1.seq_method([1, 5])
print(seq_2)
then,
seq_method = eval('seq_1.seq_method([1,5])')
print(seq_method)
but I get same error, and getattr()
returns
<function list.append(object, /)>
but I couldn't work out how to use it to extract append
from it.
Any help and suggestions much appreciated
Solution
If you want to call append()
by string name on seq_1
then getattr()
is what you are looking for:
seq_1 = [3, 4, 2, 104]
args_1 = [1, 5]
seq_method = 'append'
getattr(seq_1, seq_method)(args_1)
print(seq_1)
Gives you:
[3, 4, 2, 104, [1, 5]]
Note that append()
returns None
so you don't get a new list.
If you want a new list you need a comprehension, copy, or to populate nn empty list in a loop.
Answered By - JonSG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.