Possible to dynamically pass arguments to a function? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Possible to dynamically pass arguments to a function? (/thread-32607.html) |
Possible to dynamically pass arguments to a function? - grimm1111 - Feb-21-2021 Hello, Probably a newbie question here.... but is there any way to dynamically pass arguments to a function? I am accessing a class from someone else's code, and I can't modify it. attackers = board.attackers(chess.BLACK, chess.A7)The first argument can either be (chess.BLACK) or (chess.WHITE), and the second can be anything from (chess.A1) to (chess.H8)... so a total of 128 combinations. I would like my program to be able to loop through each possible argument for this method, but I don't want to hardcode 128 lines of code in to my program. If I try to do something intuitive like this, it doesn't work... color = 'BLACK' square = 'A7' attackers = board.attackers(chess.color, chess.square) Because it's trying to read the attribute literally, rather than treating it as a variable. Can an attribute be a variable? How would I handle this? RE: Possible to dynamically pass arguments to a function? - grimm1111 - Feb-21-2021 Nevermind, I figured it out. color = [chess.BLACK, chess.WHITE] square = [chess.A7, chess.C7] a = 1 attackers = board.attackers(color[a], square[a])If anybody else ever wants to do this, here's how I did it. It will accept a slice or an integer, but not an immutable object like a string, which was the problem I was having. Thanks everyone. RE: Possible to dynamically pass arguments to a function? - deanhystad - Feb-21-2021 You can look up attributes by name. class ChessThing(): """Standing for chess which I do not have""" def __init__(self): self.BLACK = 100 self.WHITE = 200 self.A0 = 0 self.A1 = 1 self.A2 = 2 self.A3 = 3 self.A4 = 4 self.A5 = 5 self.A6 = 6 self.A7 = 7 chess = ChessThing() # Get attributes from chess using the attribute name colors = [getattr(chess, color) for color in ['BLACK', 'WHITE']] squares = [getattr(chess, f'{r}{c}') for r in ['A'] for c in range(8)] print(colors) print(squares) Before doing that I would exhaust all efforts to see if there is any kind of collection for the A0..H7. But if you have to, you can get all 64:squares = [getattr(chess, f'{r}{c}') for r in ['ABCDEFGH'] for c in range(8)] |