1

For business logic reasons I want to be able to create an object that has an attribute named global. But I obviously can't just do

class Foo(object):
    
    def __init__(self):
        self.global = True

Because global is a reserved keyword that has special meaning in Python. Dynamically getting the attribute using __getattr__ or __getattribute__ has the same problem though. Is there anyway that I can do this, or do I have to make the attribute name global_?

I need to be able to access the attribute directly from the object, so I can't use getattr(foo, 'global').

Batman
  • 8,571
  • 7
  • 41
  • 80

1 Answers1

0

I think you just have to do global_, I don't think there's any way to bypass this, since naming with reserved keywords is illegal and creates all sorts of issues.

Edit: You can check out this post though: How to use reserved keyword as the name of variable in python?

  • 3
    As pointed out by the link, it's only illegal syntactically. You can create an attribute by that name with `setattr(self, 'global', True)`, but for the same syntactic reasons you'd have to access it with `getattr(self, 'global')`. – chepner Apr 27 '21 at 15:30
  • Also, note this limitation is due to the old Python parser. While the new PEG-based parser *could* allow `self.global = True` to be valid, I don't know if there are any plans to make it so. (Basically, the new grammar allows keywords to be reserved based on context. This is how the new `match` keyword is being added without invalidating code that uses `match` as an identifier.) – chepner Apr 27 '21 at 15:33