0

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').

1
  • No, unfortunately I need to be able to access the attribute directly on the object. Commented Apr 27, 2021 at 16:41

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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').
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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.