noober
noober

Reputation: 1505

python - NameError on a variable declared outside class

Python newbie and learning how to use a class. I've defined a class which has a method - "create" that uses a parameter (private_key) as part of a command to create a token.

Here's the command:

jwt.encode(payload, private_key, algorithm="RS256", headers=additional_headers).decode("utf-8")

I use a function outside of the class to populate the variable private_key.

Here's the code (myToken.py):

class MyTokenMgr():

    def __init__(self):
        pass

    def create(self, privkey, email):
        <MORE CODE HERE TO CREATE TOKEN>


# Function to load key from file
def load_privkey(privkey_filename):
    with open(privkey_filename, 'r') as f:
        data = f.read()
    return data

#Read the private local key
private_key = load_privkey('testkeys/jwt-key')
print('This is the local private key:', private_key)

Here's my problem. When I run python locally from command line. I want to test instantiation of the object. However, I get NameError and variable is not defined :

$ python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.myToken import MyTokenMgr
This is the local private key: -----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEAtr454soMHt7IYU+9mM6OmtzOK/i2ajNwtybYY/fQf3vMOUt8
'''
'''
-----END RSA PRIVATE KEY-----

>>> newtoken = MyTokenMgr()
>>> newtoken.create(private_key,'[email protected]')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'private_key' is not defined

You can see that I printed out the variable so I can view the key and confirm its used by the variable. So why am I still getting the is not defined error? What concept am i misunderstanding? Thanks for your help.

Upvotes: 0

Views: 148

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45736

from lib.myToken import MyTokenMgr

You're only importing the symbol MyTokenMgr. If you want to import other symbols, you need to specify them as well when importing:

from lib.myToken import MyTokenMgr, private_key

Upvotes: 2

Related Questions