0

I have several variables and want to modify them with a single function.

default strength = 0
default dex = 0
default wis = 0
default cha = 0
default point_pool = 5   

I can do something like:

def inc_strength():
    global strength
    global point_pool

    if strength<5 and point_pool>0:
        strength = strength+1
        point_pool = point_pool-1

But I don't want to create one for each stat. I'd prefer to pass the variable I want to use a param, but am struggling. Something like:

def stat_inc(stat):
    global point_pool

    if stat<5 and point_pool>0:
        stat = stat+1
        point_pool = point_pool-1

And call it with:

 action Function(stat_inc(strength))
  • 1
    You want a `dict` of stats, not 4 individual variables (`stats = {'strength': 0, 'dec': 0, ...}`). You probably want a class to wrap the value of `point_pool` so that some method can update it while updating an entry in `stats`. – chepner Jan 19 '21 at 19:42
  • 1
    You might also just want a single function that takes a point pool as an argument, and returns a fully populated stat `dict`, without having to update any global state. – chepner Jan 19 '21 at 19:43

1 Answers1

1

You can directly update the globals() dictionary:

>>> def stat_inc(arg1, arg2):
    stat = globals()[arg1]
    point_pool = globals()[arg2]

    if stat<5 and point_pool>0:
        stat = stat+1
        point_pool = point_pool-1
    globals()[arg1] = stat
    globals()[arg2] = point_pool

>>> stat=3
>>> point_pool = 3
>>> stat_inc('stat', 'point_pool')
>>> stat, point_pool
(4, 2)

That said, I think modifying global values is rarely needed, so it is better if you can do without it.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52