1

Here is the code. What I need to do is find a way to make i global so that upon repeated executions the value of i will increment by 1 instead of being reset to 0 everytime. The code in main is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.

from __future__ import nested_scopes
import sys
import time

startTime = time.time()
timeLimit = 5000
def traceit(frame, event, arg):
if event == "line": 
    elapsedTime = ((time.time() - startTime)*1000)
    if elapsedTime > timeLimit:
         raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate"
return traceit

sys.settrace(traceit)
def main______():
    try:
        i+=1
    except NameError:
        i=1
main______()
5
  • 2
    Why aren't you trying to turn scriptA and scriptB into a proper classes? If your scripts where object methods, this would be trivial. Why aren't you using classes and objects? Commented Oct 16, 2009 at 20:09
  • I have a pyhton editor where a user can enter a script. I have to check to see how long the script has been executing, via the setTrace function. I do this by placing the script in a main method in scriptB, otherwise it won't work. That works for the most part. The only problem is that it takes out the functionality of having scriptA's global variables not persist when the script is executed multiple times. i.e. When this try: i+=1 except NameError: i=0 is run multiple times, what used to happen (when the script wasn't modified) was that the i would be incremented upon each execution. Commented Oct 16, 2009 at 20:40
  • So now you say the variable is defined in a function, when you before said it was not declared in a function. You are contradicting yourself, you need to post real code and ask specific questions instead of general ones. Commented Oct 16, 2009 at 21:14
  • Hey, what I said was variables that are not defined in functions. Commented Oct 16, 2009 at 21:18
  • I've updated the question to be a little more straightforward. Thanks Commented Oct 16, 2009 at 21:25

5 Answers 5

2

It's unfortunate that you've edited the question so heavily that peoples' answers to it appear nonsensical.

There are numerous ways to create a variable scoped within a function whose value remains unchanged from call to call. All of them take advantage of the fact that functions are first-class objects, which means that they can have attributes. For instance:

def f(x):
    if not hasattr(f, "i"):
       setattr(f, "i", 0)
    f.i += x
    return f.i

There's also the hack of using a list as a default value for an argument, and then never providing a value for the argument when you call the function:

def f(x, my_list=[0]):
   my_list[0] = my_list[0] + x
   return my_list[0]

...but I wouldn't recommend using that unless you understand why it works, and maybe not even then.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to do two things to make your variable global.

  1. Define the variable at the global scope, that is outside the function.
  2. Use the global statement in the function so that Python knows that this function should use the larger scoped variable.

Example:

i = 0
def inc_i():
  global i
  i += 1

1 Comment

...or were you trying to make it persistent, that is to track the values between script execution? Probably want to use pickle for that.
0

A variable not defined in a function or method, but on the module level in Python is as close as you get to a global variable in Python. You access that from another script by

from scriptA import variablename

That will execute the script, and give you access to the variable.

2 Comments

What if the varibalename is inside a function? Can we still access it?
@user2475677 No, you can't.
0

The following statement declares i as global variable:

global i

Comments

0

Your statement "embed in 'main' in order to have the trace function work" is quite ambiguous, but it sounds like what you want is to:

  • take input from a user
  • execute it in some persistent context
  • abort execution if it takes too long

For this sort of thing, use "exec". An example:

import sys
import time

def timeout(frame,event,arg):
    if event == 'line':
        elapsed = (time.time()-start) * 1000

code = """
try:
    i += 1
except NameError:
    i = 1
print 'current i:',i
"""
globals = {}

for ii in range(3):
    start = time.time()
    sys.settrace(timeout)
    exec code in globals
    print 'final i:',globals['i']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.