Prashant Pandey
Prashant Pandey

Reputation: 13

['UnboundLocalError', ["local variable 'x' referenced before assignment"]]

I am trying to call the function in other program getting the error like:

[\'UnboundLocalError\', ["local variable \'x\' referenced before assignment"]]  

please help

connect FSN1 @FSN1 @MANTISPORT  
connect FSN2 @FSN2 @MANTISPORT  
* from commonFunctions import *  
* import os  
* import sys  
* import shutil
import io

*:
    #********* Common Variables**********
    exactShareNameFound = False

    def findExact(logMessage, share):
        f = open('logFile', 'w+')
        f.write(logMessage)
        for line in f:

          if line.find('%s')%(share) >= 0: exactShareNameFound = True

          if exactShareNameFound: x+= line

          if line.find('Share Name')>=0:
              if line.find('%s')(share)<0: exactShareNameFound = False

              else:
                    print('ERROR!!')
          else:
                print('Error in Executing Loop')



        return x

Upvotes: 0

Views: 3619

Answers (2)

tenstar
tenstar

Reputation: 10506

In python and almost all other programming languages, you cannot change the value in a variable unless you declare it.

in your code:

if exactShareNameFound: x+= line

you did not declare x, but you are referring to it in the above line.

If you wanted to append the value of line to x, then declare a variable x before using it, like so:

x = ''

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122512

Your code is manipulating a variable x without ever setting it first:

if exactShareNameFound: x+= line

Add the following line at the top of the function:

x = ''

The code will not work as currently written anyway because it attempts to read from a file opened in 'write and read' mode; the file pointer is set to the end of the file and thus reading from it will never return data without seeking to the strat first.

The function could do with some more cleaning up:

def findExact(logMessage, share):
    share = str(share)

    with open('logFile', 'w+') as f:
        f.write(logMessage)
        f.seek(0)

        lines = []
        found = False
        for line in f:
            if share in line:
                found = True

            if found: 
                x.append(line)

            if 'Share Name' in line:
                if share not in line:
                    found = False
                    continue

    return ''.join(lines)

It is unclear to me when 'ERROR' messages should be raised; use raise ValueError('error message') instead of loud 'print' statements to exit the function early in any case.

Upvotes: 1

Related Questions