Python Forum
Dynamically create functions from Json
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamically create functions from Json
#2
You're defining functions that are local to the __init__ method, so they won't be accessible to the class as a whole. That can be fixed, but I'm not sure it should be. Dynamically generating code is pretty sketchy, and you should be very suspicious whenever you see the words "exec" or "eval" in source.

For starters, how are you planning on calling these dynamic functions?
What if one of the functions is "printText"? Would all the others stop working, because they're trying to use a version of printText which no longer exists?

I think it'd make more sense for you to load them as a dict, then have a single method that looks them up. So instead of ML390.formFeed(), you'd do ML390.dispatch("formFeed"). Then that function would look something like:
def dispatch(self, key):
    if key in self.data:
        return self.printText(self.data[key])
    raise Exception(f"Invalid key: {key}")
Reply


Messages In This Thread
RE: Dynamically create functions from Json - by nilamo - Feb-20-2019, 10:12 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create variable and list dynamically quest_ 12 4,585 Jan-26-2021, 07:14 PM
Last Post: quest_
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,572 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  JSON Decode error when using API to create dataframe Rubstiano7 4 3,037 Jan-11-2021, 07:52 PM
Last Post: buran
  How to create a basic grid with functions trousers1 2 1,892 Nov-22-2019, 04:16 PM
Last Post: ThomasL
  Create a new list dynamically floatingshed 6 14,379 Nov-20-2017, 01:25 PM
Last Post: floatingshed
  dynamically create a list wfsteadman 0 2,395 Aug-30-2017, 05:34 PM
Last Post: wfsteadman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020