Python Forum
Having trouble defining variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having trouble defining variable
#1
I don't know if this has been asked before but, I am using the ftp library and making a tiny client. In my connect function i save the username and password to a variable. Now i understand that i can't use those variables outside so what i did was declare 2 more variables called perm_Uname and perm_pass. These are declared outside. I set the perm variables to equal the other and when i run them they stay the same. My code will make more sense.


from ftplib import FTP
import getpass
ftp = FTP()
def connect():
    try:
        ftp.connect("ipaddress", 21)
    except:
        print("Some error occured check to see if the ip is correct.")
        return False
    username = input("Username: ")
    password = getpass.getpass("Password: ")
    perm_Uname = username
    perm_pass = password
    try:
        ftp.login(username, password)
        print("Login Passed")
    except:
        print("Login failed")
    del username
    del password

perm_pass = ""
perm_Uname = ""
connect()
print(perm_pass)
print(perm_Uname)
The output is what i declared them as. Why?
I need the password and username saved for other functions.
help is really appreciated.
Reply
#2
What you've run into here is local variables masking global variables.

Basically, your module has a storage of variables and your function has a separate sub-storage. It reads variables from the module if they don't exist in the function, but doesn't write to the module variables unless explicitly told to do so.
x = 0
def func():
   print(x)

def func2():
   x = 5
   print(x)

print(x) # 0
func() # 0
func2() # 5
print(x) # 0
In most cases, this is what you want. It allows you to avoid accidentally overwriting variables elsewhere in the file. But you can explicitly tell Python that you want the global variable.
Continuing from above:
def func3():
   global x # use the module's x!
   x = 5
   print(x)

print(x) # 0
func3() # 5
print(x) # 5
Now, global variables are not always the answer to the problem of persistent variables. Many times, a class is better suited for that role.
class Persister:
    def __init__(self):
        self.x = 0
    def calculate_x(self):
        self.x = 5
    def output_x(self):
        print(self.x)

p = Persister()
p.output_x() # 0
p.calculate_x()
p.output_x() # 5
Running Manjaro Linux 16.08/OpenRC/i3wm on a Dell Precision 5510.

John 3:17
Reply
#3
Thanks. I will stick with global variables for now. Mine is not a huge project. Smile
Reply
#4
(Feb-08-2017, 05:17 AM)tannishpage Wrote: Thanks. I will stick with global variables for now. Mine is not a huge project. Smile
Just FYI, this kind of thing has been said about projects that ended up growing unexpectedly and caused enormous human suffering that was easily avoided. No one's going to tell you what you have to do, but I just want to make sure you're aware of historical mistakes so if you do find yourself repeating them unhappily, it's not a surprise.
Reply
#5
(Mar-22-2017, 08:48 PM)micseydel Wrote:
(Feb-08-2017, 05:17 AM)tannishpage Wrote: Thanks. I will stick with global variables for now. Mine is not a huge project. Smile
Just FYI, this kind of thing has been said about projects that ended up growing unexpectedly and caused enormous human suffering that was easily avoided. No one's going to tell you what you have to do, but I just want to make sure you're aware of historical mistakes so if you do find yourself repeating them unhappily, it's not a surprise.

Your point has been noted :). But I still have no clue how to go around this. If you could help, I will change it.
Reply
#6
Learn to live without globals.
It's extremely rare that you ever need one.
If you find that you are using a lot, re-examine your coding,
you are doing something wrong.
Reply
#7
Restructure your code (warning, pseudo code, not real Python code):

def getCredentials():
  # ask user for userid & pwd
  return userid,pwd

def connect(userid,pwd):
   # activate connection using provided credentials
   return connectionSuccessful

connected=False
while not connected:
   credentials=getCredentials()
   connected=connect(credentials)

otherfunction(credentials)
Basic principle: one action, one function. If you need userid/pwd elsewhere, then these are disjoint from the connection.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trouble with threading and reading variable from a different script Lembas 14 3,066 Apr-26-2023, 11:21 PM
Last Post: Lembas
  Defining an object's argument whose name is stored in a variable arbiel 2 2,193 Dec-11-2020, 10:19 PM
Last Post: arbiel
Question trouble with functions "def", calling/defining them Duck_Boom 13 4,402 Oct-21-2020, 03:50 AM
Last Post: Duck_Boom
  Problem defining a variable rix 6 3,207 Dec-17-2019, 11:34 AM
Last Post: rix
  Trouble Setting a Variable True basing on an Imput VictorVictus 5 2,774 Aug-02-2019, 08:14 PM
Last Post: VictorVictus
  While loop variable defining Yordy 5 4,004 Jan-04-2018, 04:53 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020