JohnJ
JohnJ

Reputation: 7056

global variable (although defined) errors out as not defined in python

I have a rather weird problem in python: I am trying to run this script (it is auto generated using MMddn, which converts one neural network model to another - but this background is irrelevant to this question - just an FYI):

https://zerobin.net/?a8436f2ae6791499#dhZsFWXc91YpvlHajIqLY74MdeP8pE98E3IELiAD3bw=

but when I execute (using another script which calls this script) it I get:

  File "/home/foo/ve_name/env_name/lib/python3.7/site-packages/torch/nn/modules/module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/foo/ve_name/env_name/etc/model-r100-ii/pytorch.py", line 288, in forward
    self.minusscalar0_second = torch.autograd.Variable(torch.from_numpy(__weights_dict['minusscalar0_second']['value']), requires_grad=False)
NameError: name '_KitModel__weights_dict' is not defined

I am perplexed why this is happening. I can clearly see the __weights_dict being defined globally, so I am clueless why this error appears :(

Any directions to solve this problem would be incredibly useful (wasted 8 hours on this already!)

Upvotes: 1

Views: 145

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50076

Python has name mangling inside class scopes, which means that names starting with two underscores are renamed. Inside the class scope, __weights_dict actually refers to _KitModel__weights_dict, i.e. not the name of the global variable.

As a fix, rename all occurrences of __weights_dict to _weights_dict.

Upvotes: 1

Related Questions