scratchattach icon indicating copy to clipboard operation
scratchattach copied to clipboard

stop using self.__dict__.update(**kwargs) in __init__

Open faretek1 opened this issue 9 months ago • 3 comments

although using self.__dict__.update(**kwargs) allows for more concise code, it also causes a lot of confusion when an ide's code completion attempts to find an object's attributes. Also, using self.__dict__.update could cause completely unexpected issues, e.g. a method being overridden by a string, and when trying to call the method, a strange error would be raised.

Possible alternatives:

  • dataclasses (and potentially using the __post_init__ special method)
  • defining __init__ in a completely conventional manner (this may lead to a lot of parameters in one line)
  • keep code the same but explicitly define attribute names & types within the class definition

faretek1 avatar Apr 13 '25 14:04 faretek1

Would you like to create a pull request for this?

TheCommCraft avatar Apr 13 '25 14:04 TheCommCraft

list of classes which use self.__dict__.update in __init__: in certain cases, this might be better left alone, e.g. eventhandlers.cloud_requests.ReceivedRequest note that some of these may affect their child classes. Changing these would require careful testing.

  • cloud.cloud.CustomCloud
  • eventhandlers.cloud_requests.ReceivedRequest
  • other.project_json_capabilities.ProjectBody.BaseProjectBodyComponent
  • other.project_json_capabilities.ProjectBody.Monitor
  • other.project_json_capabilities.ProjectBody.Asset
  • site.activity.Activity
  • site.backpack_asset.BackpackAsset
  • site.classroom.Classroom
  • site.cloud_activity.CloudActivity
  • site.comment.Comment
  • site.forum.ForumTopic
  • site.forum.ForumPost
  • site.project.PartialProject
  • site.session.Session
  • site.studio.Studio
  • site.user.User

faretek1 avatar Apr 13 '25 14:04 faretek1

Would you like to create a pull request for this?

There are a lot of classes involved and in each case, one has to be careful not to cause any existing functionality to break. I will not create a single pull request encompassing all of these cases, especially not project_json_capabilities due to the heavy reliance on self.__dict__. I intend to change some of the classes that I am more familiar with as it would be less prone to error.

faretek1 avatar Apr 13 '25 14:04 faretek1

This could probably be better solved through a use of dataclasses. that way, when running init, if an unrecognised attribute is used, an error will be raised, which will notify us to add relevant keys. Any processing done currently in __init__ can be done in __post_init__


So perhaps this issue should be closed as not planned and a different issue to be opened

faretek1 avatar May 30 '25 11:05 faretek1