Linked Questions
10 questions linked to/from Dynamic/runtime method creation (code generation) in Python
5 votes
12 answers
3k views
Why is it not possible to create a practical Perl to Python source code converter?
It would be nice if there existed a program that automatically transforms Perl code to Python code, making the resultant Python program as readable and maintainable as the original one, let alone ...
24 votes
4 answers
32k views
How to dynamically define functions?
I have functions like this: def activate_field_1(): print 1 def activate_field_2(): print 2 def activate_field_3(): print 3 How do I define activate_field_[x] for x=1:10, without typing ...
-3 votes
3 answers
1k views
How to create a class with an unknown number of instances?
I need to create multiple instances of function def name_VARIABLE_NUMBER(self): under one class. The number of instances will be determined from the input file and is unknown from the beginning. Is ...
4 votes
2 answers
643 views
Running a for loop to create functions with exec, inside a class, inside a function
I know it sounds complicated and it may not be possible, but I thought I'd try anyway. So I'm doing some web scraping with Selenium, and any time that I want to run some jQuery on a page, instead of ...
3 votes
4 answers
336 views
Python: define function only once [duplicate]
I want to define a function, e.g. a polynomial, from a list of prefactors. Something like order = [1,0,1] def poly(x): res = 0 for i, o in enumerate(order): res += o * x**i return ...
4 votes
1 answer
231 views
Proxying a class in Python
I'm using the python-mpd2 module to control a media player on a Raspberry Pi in a GUI application. Thus, I'd like to gracefully handle connection errors and timeouts (the player in question drops MPD ...
1 vote
1 answer
521 views
Create an ABC with abstract methods defined from json keys
Say I have a json file look like: { "foo": ["hi", "there"], "bar": ["nothing"] } I'd like to create an abstract base class (ABC), where the name of abstract methods are the keys of the json ...
0 votes
1 answer
87 views
Dynamically decorate a function inside a class in Python3
This is an extension of Dynamic/runtime method creation (code generation) in Python @John Montgommery properly answered @Eli Bendersky 's question that you can dynamically create a class with ...
1 vote
0 answers
88 views
Why is exec() dangerous? [duplicate]
I have been looking around StackOverflow for Python dynamic variable naming. And though I now know how much better it is to use a dictionary to store my dynamic objects. But I've seen more than once ...
0 votes
0 answers
46 views
Python methods added dynamically to classes not working as expected [duplicate]
I have the following piece of code: d = dict(q='q', w='w', e='e') class A(object): pass for o in d.items(): print o def _method(self): return o[0] setattr(A, o[1], _method) ...