0

Since my last question was rather poorly worded, here is a different question that will provide me the same benefits!

First of all, I want to accomplish one thing: create a new Set and set that Set's name to the value of a variable (a string I would set it equal to, e.g. new_set_name = 'buffalo')

I want it to be something like this new_set_name = Set([]) Except I don't want the end result to be a Set with the name new_set_name I want the name of the Set to instead be: buffalo.

I tried quite hard to make this as non-confusing as possible, but if it is, let me know! I will try to fix it!

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • Do you mean you want to use the vaue of a variable as a variable name ? in that case I'd check this out http://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name – scrineym Nov 23 '15 at 14:24
  • Seconded: [use a dictionary](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python). – Matt Hall Nov 23 '15 at 14:40

2 Answers2

0

I'm not too sure what you mean, but if you want to use a variable value as a variable name you need to use setattr inside a class like this

class Test:
   def testmethod(self,name):
      setattr(self,name,Set())

Then you can say

tmp = Test()
varname= 'buffalo'
tmp.testmethod(varname)

And you'll have

In [29]: type(t.buffalo)
Out[29]: sets.Set
scrineym
  • 759
  • 1
  • 6
  • 28
0

You can create a variable in the module namespace like so

new_set_name = 'buffalo'
globals()[new_set_name] = set()

Namespaces are implemented by dicts but python figures out context when you use the variables so you don't have to refer to them directly. You can view or update at other module namespaces using their __dict__ variable but its more customary to use setattr

import os
print(os.__dict__)
os.__dict__[new_set_name] = set()
setattr(os, new_set_name, set())
tdelaney
  • 73,364
  • 6
  • 83
  • 116