setattr - unresolved identifier

Hi,

Know somebody how to deal with following very shorted example?

class A(object):

     def __init__(self):

          # some complex atribute generation with by ex:

          setattr(self,"XX",list())

     def go(self):

          self.XX.append()          <--XX is unresolved identifier

The problem is in dynamicaly created class attribute. How to hint pyCharm type of self.XX ?

Thanks.

2 comments

Hi Michal,

Your example looks a bit unnatural to me. Either you know that attribute 'XX' is or at least should be an instance attribute, then you would code it this way:

class C(object):
    def __init__(self):
        self.XX = list()

    def go(self):
        self.XX.append("something")

... or you do not know which attributes are set (for example due to dynamic creation), then you could code it that way:

class B(object):
    def __init__(self):
        setattr(self, "XX", list())

    def go(self):
        try:
            getattr(self, "XX").append("something")
        except AttributeError:
            # handle exception
            pass

Both cases do not show any warnings within the IDE. Could you give more details why you would code it the way you did in your message? This is, mixing explicit knowledge (self.XX) with implicit creation (setattr(self, "XX")).

Regards,
Volker

0

Hi Volker,

Yes, the example is very shorted and again yes :-) the problem is mixing explicit vs. implicit.  The method go() for this example is not very good.

I can try a better explanation:

Constructor of class C contain code for implicit creation a lot of atributes (why it's done this vay I don't know :-) it is part of some internal framework).

Later somewhere in complex application I need instance of C and access to one of this attribute. So for readability of code is better explicit variant and voila - problem is here:-)

I know it is possible to use getatt, but I was thinking about hint to IDE that this is not error or better what type is this atribute.

Of course these implicit attributes of C class can be type object and will be very useful to have working code completion for this atributes.

I hope that this explanation is understandable.

Regards,

Michal

0

Please sign in to leave a comment.