How to call a function in a different module in Python and not repeating the function

I have defined a function in a different page in Python like so:

def getData():
    user=input('Enter Name')
    if user=='Irfan':
        mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='sample_data')
        df = pd.read_sql_query('select * from sample_data.sample_data3', mydb)
    else:
        if user=='Usman':
            mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='')
            df = pd.read_sql_query('select * from sample_data.sample_data1', mydb)

    return df

However, because that function is called in many other files in the project, it is asking me over and over again at runtime to enter the user name.

How can I input the user name once and then use that cached value to get the required database without having to enter the user name multiple times?

(Sorry for asking in layman’s terms; I am a beginner.)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Make the credentials global..

user=input('Enter Name')

def getData():
global user
if user=='Irfan':
    mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='sample_data')
    df = pd.read_sql_query('select * from sample_data.sample_data3', mydb)
else:
    if user=='Usman':
        mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='')
        df = pd.read_sql_query('select * from sample_data.sample_data1', mydb)

return df

Method 2

You can get the user input once and pass the name as a parameter to your function, like as follows:

user = input('Enter name')
def getData(user):
    ##your code

Method 3

How about:

user = ''
def getData():
    if len(user) == 0:
        user=input('Enter Name')
    
    if user=='Irfan':
        mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='sample_data')
        df = pd.read_sql_query('select * from sample_data.sample_data3', mydb)
    else:
        if user=='Usman':
            mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='')
            df = pd.read_sql_query('select * from sample_data.sample_data1', mydb)

    return df

By putting the user variable outside of the function it becomes a global variable. Inside you test, if the user variable is already filled or not


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x