-1

In JS, you can do something similar, assign all key, values of an object / dict, obj to be in the global namespace / context obj with this[key] = obj[key]

I expected to be able to do the same with

class A:
    def call(self):
        print('a')

a = A()

globals()['call'] = lambda: None
print(globals())
setattr(globals(), 'call', a.call)

the confusing thing is that the error I'm getting is AttributeError: 'dict' object has no attribute 'call' even though call is clearly defined when I print globals()

James T.
  • 910
  • 1
  • 11
  • 24
  • 5
    Attributes and keys are not the same thing in Python. – user2357112 Dec 26 '18 at 23:32
  • Why are you even mucking around with the `globals` dict anyway? Why not `call = a.call`??? – juanpa.arrivillaga Dec 27 '18 at 00:22
  • @juanpa.arrivillaga for when I decide to move 7+ funcs to a class, but I'm too lazy to refactor, and I may move more funcs in or out of this class as I dev this script; yea it's poor design and my IDE will think I'm trying to use some var that's not def – James T. Dec 27 '18 at 02:38

1 Answers1

0
class A:
    def call(self):
        print('a')

    def call2(self):
        print('b')

a = A()

method_names = list(filter(lambda func: '__' not in func, dir(a)))
for func in method_names:
    globals()[func] = getattr(a, func)

# globals()['call'] = a.call
print(globals())
call()
call2()
# setattr(globals(), 'call', a.call)

oops, got mixed up between attributes and keys when they're the same thing in JS. thanks

James T.
  • 910
  • 1
  • 11
  • 24