AttributeError: 'function' object has no attribute 'b64encode' python 3.9 base64 encoding string fail
Question:
import base64
def base64(text):
newText = base64.b64encode(text.encode())
return newText
This is function the main calls with input, gets string and returns the encoded string. I keep on getting the following error-
AttributeError: 'function' object has no attribute 'b64encode'
I have tried string or bytes as parameter but the error stays the same.
Answers:
The issue is that you have imported base64
but then created your own function with the same name base64
. That means the references to base64
after your definition of the function (including inside of it) will be to your function and not to the module.
That’s what the error is refering to a function base64
which does not have the attribute you are referencing b64encode
.
In order to fix this, all you have to do is change the name of your function to something else, for example – my_base64
will work 🙂
import base64
imports the module and binds it to the module variable "base64". The following def base64(...):
compiles a function object and then rebinds the module variable "base64". By the time you use it, its now a function. The solution is to rename your function, perhaps
def my_encoder(text):
...
import base64
def base64(text):
newText = base64.b64encode(text.encode())
return newText
This is function the main calls with input, gets string and returns the encoded string. I keep on getting the following error-
AttributeError: 'function' object has no attribute 'b64encode'
I have tried string or bytes as parameter but the error stays the same.
The issue is that you have imported base64
but then created your own function with the same name base64
. That means the references to base64
after your definition of the function (including inside of it) will be to your function and not to the module.
That’s what the error is refering to a function base64
which does not have the attribute you are referencing b64encode
.
In order to fix this, all you have to do is change the name of your function to something else, for example – my_base64
will work 🙂
import base64
imports the module and binds it to the module variable "base64". The following def base64(...):
compiles a function object and then rebinds the module variable "base64". By the time you use it, its now a function. The solution is to rename your function, perhaps
def my_encoder(text):
...