0

I have an init function that holds some start up information. I would like to

  1. have the user input their email address,
  2. save it to a variable called "user_id"
  3. then use that variable within the init function.

It seems to be working using global variables, but I've read that using global variables is a bad idea.

How do I achieve this without using global variables?

user_id ="no email yet"

Class GetDatabase():

 def user_email_input():
    global user_id
    user_id = input("what is your email") 
    return


 def __init__(self,uri: Text = "localhost:2555", servername: Text = "schools") -> Text:
    global user_id

    self.uri = uri
    self.servername= servername
    self.me = user_id```
    
  • 1
    Pass the variable as an argument to the constructor as you're doing with `uri` and `servername`. – enzo Nov 04 '21 at 15:31
  • Thanks, @enzo do you mean like this? I get a NameError ' user_id is not defined `` def __init__(self,uri: Text = "localhost:2555", servername: Text = "schools", me: Text = f"{user_id}") global user_id self.uri = uri self.servername= servername self.me = me ``` – Overture04 Nov 04 '21 at 15:40

1 Answers1

1

Bad way to do it but if you must:

class GetDatabase:
    def __init__(self, uri="localhost:2555", servername="schools"):
        self.uri = uri
        self.servername = servername
        self.user_email_input()

    def user_email_input(self):
        self.me = input("what is your email: ")

Passing arguments to the instantiation of the class seems like exactly what you need:

class GetDatabase:
    def __init__(self, user_id, uri="localhost:2555", servername="schools"):
        self.uri = uri
        self.servername = servername
        self.me = user_id

# then instantiated with
db = GetDatabase(my_user_id, my_uri, my_servername)
ChrisOram
  • 1,254
  • 1
  • 5
  • 17
  • Why don't you return the value in user_email_input and set self.me = user_email_input()? I would do it like that but I don't know if that is the best way to do it. – Wimanicesir Nov 04 '21 at 15:58
  • I agree with the second snippet. Just for completeness, you can add `my_user_id = input("what is your email: ")` before creating `db`. – enzo Nov 04 '21 at 15:59
  • @Wimanicesir This approach would work. However, if someone tests this code in the future, they can't pass a different source for `self.me` if not from standard input, going against [dependency injection](https://stackoverflow.com/a/140655/9997212). – enzo Nov 04 '21 at 16:03
  • @Wimanicesir you can do that - its perfectly sound. It then requires the method to become static (does not take self i.e. does not depend on the instance of the class), a return statement, and manual attribute assignment when you want to reassign `self.me`. To me that sounds like more code for not much benefit. – ChrisOram Nov 04 '21 at 16:44