|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today! |
|
#1
|
|||
|
|||
|
problem with str()
I want to generate a "random filename".
So: uniqid = str(os.getpid())+'.'+os.getenv('HOSTNAME') And I get the error: UnboundLocalError: local variable 'str' referenced before assignment Any ideas? Thanks in advance. |
|
#2
|
||||
|
||||
|
I've never actually heard of an UnboundLocalError, although if this is being raised by one of the functions you're calling it might explain a few things. Can you provide your full program for examination? Also, what version of Python and on what OS are you running?
Mark. |
|
#3
|
||||
|
||||
|
I suspect that the environment variable 'HOSTNAME' is not defined, in which case os.getenv will return None.
With my version of Python 2.3.3 it correctly reports that you can't concatenate None to a string. What version are you using? There are many ways to generate a more random file name (the tmpfile module could be useful). How about this: uniqid = str(os.getpid())+'.'+str(time.time())[-6:] as long as you don't request another filename within 100 ms in the same process.
__________________
*** Experimental Python Markup CGI V2 *** |
|
#4
|
|||
|
|||
|
Quote:
This error is caused because Python thinks 'str' is a local variable. This probably means that you use the name later in the same function to hold a value. e.g. Code:
>>> def test(): ... str(23) ... str = 'foo' ... >>> test() Traceback (most recent call last): File "<interactive input>", line 1, in ? File "<interactive input>", line 2, in test UnboundLocalError: local variable 'str' referenced before assignment >>> Because the code assigns to 'str' the Python compiler assumes that it is a local variable, but you can't use a local variable before you have assigned it a value, hence the exception. The solution is to search for occurrences of 'str' in your code, and if it is being used as a variable name then rename the variable. Dave - The Developers' Coach Last edited by DevCoach : April 8th, 2004 at 05:34 AM. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > problem with str() |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|