-1

Hi I'm trying to write a small helper function to save an object to a csv under its own name.

I'm working with arrays of data and this is intended to be a workaround to help visualise the array easily to help with editing it.

The challenge I'm facing is that I'm unclear is how to get the function to look through the x variable to the name of a in the MWE below. what I'd like to be able to do is save it as a.csv. getattr() doesn't work so I'm stumped.

import random
import csv

def csvit(x):
    f=open(name(x)+'.csv','wb'):
    writer = csv.writer(f,quotechar='"', quoting=csv.QUOTE_ALL)
    [writer.writerow(i) for i in x]
    f.close()


a = []
for i in range(10):
    t = [random.randint(0,1000) for r in range(10)]
    a.append(t)

the name(x) isn't a working function and I don't know what to use in its place. I'm really looking for a function where fun(x) yields ["a"]

for completeness the code that seems to work on the back of @PhilCooper 's answer below is

import csv

def csvit(x):
    tmp = next(key for key,val in globals().items() if val == x and not key.startswith('_'))
    f=open('/home/me/Desktop/csvs/'+tmp+'.csv','wb')
    writer = csv.writer(f,quotechar='"', quoting=csv.QUOTE_ALL,dialect=csv.excel)
    [writer.writerow(i) for i in x]
    f.close()

Would welcome any comments or improvements on it.

Tahnoon Pasha
  • 5,848
  • 14
  • 49
  • 75

2 Answers2

2

It looks like you are asking for the name of the object in the calling scope. In python the name of an object is not part of the object, it is it's key in the current scope (i.e. in locals() or globals())

Could you find it. yes but it could have multiple names in that scope:

next(key for key,val in globals().items() if val is x and not key.startswith('_'))

b = a
#do you want b or a as the name now?

And that just assumes global scope. uglier yet is that you would really have to check the frame stack and then.....ahhhhh

just pass in the name you want and sleep soundly.

if you want to do something fancy then create a class or named tuple but keep is simple.

Phil Cooper
  • 5,747
  • 1
  • 25
  • 41
1

I think you're looking for either dict or dir(obj), not sure though.

>>> class Foo (object):
...     def __init__ (self):
...             self.bar = 'foobar'
... 
>>> foo = Foo()
>>> dir(foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar']
>>> foo.__dict__
{'bar': 'foobar'}

But since your question is rather sparse I'm not sure.

Blubber
  • 2,214
  • 1
  • 17
  • 26
  • thanks @Blubber, you're right I wasn't too clear. the `name(x)` isn't a working function and I don't know what to use in its place. I'm really looking for a function where `fun(x)` yields `["a"]` – Tahnoon Pasha May 25 '13 at 12:52