2

How can I get the module object/namespace for an already-loaded script datablock, given only the name/ID/path of the text datablock?

.as_module() doesn't do this, because D.texts[0].as_module() is D.texts[0].as_module() == Falseas_module() returns a new object and namespace, so it can't be used to alter or unregister the already-imported definitions. It also doesn't set __file__ correctly.


Basically, I'm looking for something like addon_utils.modules(), except with no fake modules, and if it also included all user scripts from which a type has been registered.

Will Chen
  • 1,607
  • 8
  • 21

1 Answers1

0

Method returns a module like object

Not exactly sure of what you are asking here, the as module method returns a module like object using the code of the datablock.

>>> foo = D.texts['Text'].as_module()

>>> foo <module 'Text'>

>>> foo.name 'Text'

>>> D.texts['Text'].as_module().name == D.texts['Text'].as_module().name True

Can see no reason to expect that

D.texts[0].as_module() is D.texts[0].as_module()

or that __file__ is set.

Related.

How to import text data blocks as modules using the 'from/import' statement?

batFINGER
  • 84,216
  • 10
  • 108
  • 233
  • Currently, I'm assigning globals() to bpy.ModuleName.__dict__ from inside each module/script, so I can call bpy.ModuleName.unregister() later. The idea is to be able to get the original namespace for arbitrary modules without requiring the modules to register themselves in that way. as_module() doesn't work because it just creates a new module with exec. I would expect there to be some way to get as_module() is as_module() because modules are usually singletons shared across multiple import statements, and the types are clearly kept around. – Will Chen Jun 08 '21 at 21:35
  • Basically, I'm looking for something like addon_utils.modules(), except with no fake modules, and if it also included all user scripts that had been run— Although, how such arbitrary and potentially conflicting data would be best sorted and discarded may be messy. – Will Chen Jun 08 '21 at 21:37
  • Have you investigated the source of addon_utills.modules() ?? – batFINGER Jun 09 '21 at 13:54
  • also IMO both methods in answer link show are examples re how to do this too. The as_module() method returns a new module like object using the code in the texblock How to make your own module like object instead is well covered on stackoverlow. – batFINGER Jun 09 '21 at 14:05
  • Unfortunately, while those methods are interesting, I believe they still require cooperation from either the original script's scope or the importing scope? I can already do that; what I'd like is to get the namespace of any arbitrary previously-run script when knowing nothing but its name, and without requiring it to have been loaded a certain way. Making a new module(-like) object is a different question IMO; you can't unregister or monkey-patch the original script if you just make a new object. – Will Chen Jun 09 '21 at 15:59