tags:

views:

94

answers:

4

Hi,

This is a silly question, but I can't figure it out so I had to ask.

I'm editing some Python code and to avoid getting too complicated, I need to be able to define a new variable along the lines of : Car.store = False.

Variable Car has not been defined in this situation. I know I can do dicts (Car['store'] = False) etc... but it has to be in the format above.

Appreciate any help

Thanks.

+1  A: 

I think the closest you can get to what you want is by adding one extra line (assuming you have defined a class called Car):

car = Car()
car.store = False

Without the first line you will get an error.

If you want brevity you could set store to False in __init__ so that only the first line is necessary.

Mark Byers
thanks. It worked.
iceanfire
A: 

Maybe you can try whith this:

try:
    car.store = False
except NameError:
    #This means that car doesn't exists
    pass
except AttributeError:
    #This means that car.store doesn't exists
    pass
razpeitia
-1 It is very unlikely that AttributeError will be raised in the circumstances that you describe (unless the class is defined with `__slots__`). Did you actually try this yourself? It would of course happen if you did `foo = car.store` and `car` exists but has no `store` attribute, but that's a completely different scenario.
John Machin
Yeah, you're rightYou need to add a line to get work that code.<pre>try: car.store car.store = Falseexcept NameError: #This means that car doesn't exists passexcept AttributeError: #This means that car.store doesn't exists pass</pre>
razpeitia
A: 

I'm a bit late to the party, but also check out the namedtuple function in the collections module. It lets you access fields of a tuple as if they were named members of a class, and it's nice when all you want is a C-style "structure". Of course, tuples are immutable so you'd probably have to rearrange your existing code quite a bit; perhaps not the best thing for this example, but maybe keep it in mind in the future.

Peter Milley
A: 

car, car.store = car if "car" in locals() else lambda:1, False