naming objects from string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • manstey

    #1

    naming objects from string

    Hi,

    If I have a string, how can I give that string name to a python object,
    such as a tuple.

    e.g.

    a = 'hello'
    b=(1234)

    and then a function
    name(b) = a

    which would mean:
    hello=(1234)

    is this possible?

  • James Stroud

    #2
    Re: naming objects from string

    manstey wrote:
    Hi,
    >
    If I have a string, how can I give that string name to a python object,
    such as a tuple.
    >
    e.g.
    >
    a = 'hello'
    b=(1234)
    >
    and then a function
    name(b) = a
    >
    which would mean:
    hello=(1234)
    >
    is this possible?
    >
    Depends on your namespace, but for the local namespace, you can use this:

    pya = object()
    pya
    <object object at 0x40077478>
    pylocals()['bob'] = a
    pybob
    <object object at 0x40077478>

    A similar approach can be used for the global namespace.

    James

    --
    James Stroud
    UCLA-DOE Institute for Genomics and Proteomics
    Box 951570
    Los Angeles, CA 90095


    Comment

    • manstey

      #3
      Re: naming objects from string

      Hi,

      But this doesn't work if I do:

      a=object()
      x='bob'
      locals()[x] = a

      How can I do this?

      James Stroud wrote:
      manstey wrote:
      Hi,

      If I have a string, how can I give that string name to a python object,
      such as a tuple.

      e.g.

      a = 'hello'
      b=(1234)

      and then a function
      name(b) = a

      which would mean:
      hello=(1234)

      is this possible?
      >
      Depends on your namespace, but for the local namespace, you can use this:
      >
      pya = object()
      pya
      <object object at 0x40077478>
      pylocals()['bob'] = a
      pybob
      <object object at 0x40077478>
      >
      A similar approach can be used for the global namespace.
      >
      James
      >
      --
      James Stroud
      UCLA-DOE Institute for Genomics and Proteomics
      Box 951570
      Los Angeles, CA 90095
      >
      http://www.jamesstroud.com/

      Comment

      • Wildemar Wildenburger

        #4
        Re: naming objects from string

        manstey wrote:
        If I have a string, how can I give that string name to a python object,
        such as a tuple.
        >
        e.g.
        >
        a = 'hello'
        b=(1234)
        >
        and then a function
        name(b) = a
        >
        which would mean:
        hello=(1234)
        >
        is this possible?
        >
        Direct answer:
        Look up the setattr() functions (DO look it up!). Replace your
        name(b) = a line with
        setattr(__built ins__, a, b).
        There you go.


        Hopefully more helpful answer:
        One alternative would be using a dictionary. Your example would then
        translate to:

        a = 'hello'
        b = (1234,) # notice the comma!
        # without it, it wouldn't be a tuple but a simple
        # parenthesized integer
        d = {} # your dictionary

        d[a] = b # assign the value of b to a key given by a

        d[a]
        >>(1234,)
        d['hello']
        >>(1234,)
        In most cases this will be a LOT less cumbersome compared to messing
        with module attributes.

        hope that helps a bit
        wildemar

        Comment

        • Damjan

          #5
          Re: naming objects from string

          manstey wrote:
          Hi,
          >
          But this doesn't work if I do:
          >
          a=object()
          x='bob'
          locals()[x] = a
          >
          How can I do this?
          try
          sys.modules[__name__].__dict__[x] = a

          But what's the point?


          --
          damjan

          Comment

          • Wildemar Wildenburger

            #6
            Re: naming objects from string

            manstey wrote:
            Hi,
            >
            But this doesn't work if I do:
            >
            a=object()
            x='bob'
            locals()[x] = a
            >
            How can I do this?
            You can. I just copy/pasted your code and it works fine here. (You are
            aware that there is whitespace before locals() that you have to remove
            before you feed it to the snake?)

            What error did you get?

            Let me again stress that using locals and globals is a bit contrived,
            whereas the dictionary approach from my other post is not.


            Just out of curiosity: Why do you want to do this anyway?

            wildemar

            Comment

            • Wildemar Wildenburger

              #7
              Re: naming objects from string

              Damjan wrote:
              try
              sys.modules[__name__].__dict__[x] = a
              @manstay: You see! Ugly, unreadable trickery!
              Hands off this stuff, bad mojo!

              You've been told three very different approaches now, which is a pretty
              good indicator that there is no obvious way to do it. Which means
              another angle to your problem might make it a lot easier.
              (btw: Try 'import this' at the python prompt for some wise words.)

              Please describe your problem and let us suggest that new angle.

              wildemar

              Comment

              • manstey

                #8
                Re: naming objects from string

                Hi,

                thanks for the suggestions. this is my problem:

                I have a metadata file that another user defines, and I don't know
                their structure in advance. They might have 300+ structures. the
                metadata defines the name and the tuple-like structure when read by
                python.

                my program reads in the metadata file and then generates python tuples
                corresponding to their structures.

                so they might provide a list of names, like 'bob','john','p ete', with 3
                structures per name, such as 'apple','orange ','red' and I need 9 tuples
                in my code to store their data:

                bob_apple=()
                bob_orange=()
                ...
                pete_red=()

                I then populate the 9 tuples with data they provide in a separate file,
                and the filled tuples are then validated against the metadata to make
                sure they are isomorphic.

                Is this clear?

                thanks

                Comment

                • manstey

                  #9
                  Re: naming objects from string

                  Hi,

                  thanks for the suggestions. this is my problem:

                  I have a metadata file that another user defines, and I don't know
                  their structure in advance. They might have 300+ structures. the
                  metadata defines the name and the tuple-like structure when read by
                  python.

                  my program reads in the metadata file and then generates python tuples
                  corresponding to their structures.

                  so they might provide a list of names, like 'bob','john','p ete', with 3
                  structures per name, such as 'apple','orange ','red' and I need 9 tuples
                  in my code to store their data:

                  bob_apple=()
                  bob_orange=()
                  ...
                  pete_red=()

                  I then populate the 9 tuples with data they provide in a separate file,
                  and the filled tuples are then validated against the metadata to make
                  sure they are isomorphic.

                  Is this clear?

                  thanks

                  Comment

                  • Wildemar Wildenburger

                    #10
                    Re: naming objects from string

                    manstey wrote:
                    Hi,
                    >
                    thanks for the suggestions. this is my problem:
                    >
                    I have a metadata file that another user defines, and I don't know
                    their structure in advance. They might have 300+ structures. the
                    metadata defines the name and the tuple-like structure when read by
                    python.
                    >
                    my program reads in the metadata file and then generates python tuples
                    corresponding to their structures.
                    >
                    so they might provide a list of names, like 'bob','john','p ete', with 3
                    structures per name, such as 'apple','orange ','red' and I need 9 tuples
                    in my code to store their data:
                    >
                    bob_apple=()
                    bob_orange=()
                    ..
                    pete_red=()
                    >
                    I then populate the 9 tuples with data they provide in a separate file,
                    and the filled tuples are then validated against the metadata to make
                    sure they are isomorphic.
                    >
                    Is this clear?
                    Erm, not exactly but I think I get it.

                    Note that creating empty tuples will mean that they will always be
                    empty. They are immutable, basically meaning that you can not change
                    them after they are created. If you want to create empty data that you
                    want to fill later on, use lists. Or (which might be more convenient)
                    put in the data right away).

                    Generally, since you do not know the names ('bob', 'john', etc.) and the
                    structures in advance, the best way to store them is in a *variable*.
                    Here I would suggest dictionaries again. Let me write an example in
                    pseudo python:

                    people = {} # data dict
                    # lets suppose the data from your file is a list of tuples like:
                    # [('bob',('orange ', 'apple', 'red')), ...]
                    # (I didnt quite get how your data is organized)
                    for name, structure in list_of_names_f rom_file:
                    people[name] = {} # make a new dict for the 'structures'
                    for item in structure:
                    people[name][item] = () # empty tuple
                    # instead of an empty tuple you could fill in your data
                    # right here, which would save you the extra keyboard mileage

                    Does that make sense in the context of your application?

                    wildemar

                    Comment

                    • Ben Finney

                      #11
                      Re: naming objects from string

                      "manstey" <manstey@csu.ed u.auwrites:
                      If I have a string, how can I give that string name to a python
                      object, such as a tuple.
                      The thing I'd like to know before answering this is: how will you be
                      using that name to refer to the object later?

                      --
                      \ "If you ever catch on fire, try to avoid seeing yourself in the |
                      `\ mirror, because I bet that's what REALLY throws you into a |
                      _o__) panic." -- Jack Handey |
                      Ben Finney

                      Comment

                      • Tim Roberts

                        #12
                        Re: naming objects from string

                        "manstey" <manstey@csu.ed u.auwrote:
                        >
                        >If I have a string, how can I give that string name to a python object,
                        >such as a tuple.
                        >
                        >e.g.
                        >
                        >a = 'hello'
                        >b=(1234)
                        That's not a tuple. That's an integer. (1234,) is a tuple.
                        >and then a function
                        >name(b) = a
                        >
                        >which would mean:
                        >hello=(1234)
                        >
                        >is this possible?
                        Yes, but it's almost never the right way to solve your problem. Use an
                        explicit dictionary instead.

                        C:\Tmp>python
                        Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
                        on win32
                        Type "help", "copyright" , "credits" or "license" for more information.
                        >>a='hello'
                        >>locals()[a] = 1234
                        >>hello
                        1234
                        >>>
                        --
                        - Tim Roberts, timr@probo.com
                        Providenza & Boekelheide, Inc.

                        Comment

                        • Gabriel Genellina

                          #13
                          Re: naming objects from string

                          At Thursday 21/9/2006 00:59, manstey wrote:
                          >If I have a string, how can I give that string name to a python object,
                          >such as a tuple.
                          >
                          >e.g.
                          >
                          >a = 'hello'
                          >b=(1234)
                          >
                          >and then a function
                          >name(b) = a
                          >
                          >which would mean:
                          >hello=(1234)
                          >
                          >is this possible?
                          You may use another object as a namespace:

                          class X: pass
                          x = X()

                          a = 'hello'
                          b = (1,2,3,4)
                          setattr(x, a, b)

                          print x.hello # prints (1,2,3,4)
                          getattr(x, a) # returns the same

                          but perhaps if you explain better what you want, we can figure out
                          how to do that...



                          Gabriel Genellina
                          Softlab SRL





                          _______________ _______________ _______________ _____
                          Preguntá. Respondé. Descubrí.
                          Todo lo que querías saber, y lo que ni imaginabas,
                          está en Yahoo! Respuestas (Beta).
                          ¡Probalo ya!


                          Comment

                          • Fredrik Lundh

                            #14
                            Re: naming objects from string

                            manstey wrote:
                            so they might provide a list of names, like 'bob','john','p ete', with 3
                            structures per name, such as 'apple','orange ','red' and I need 9 tuples
                            in my code to store their data:
                            >
                            bob_apple=()
                            bob_orange=()
                            ..
                            pete_red=()
                            >
                            I then populate the 9 tuples with data they provide in a separate file,
                            and the filled tuples are then validated against the metadata to make
                            sure they are isomorphic.
                            if you want a dictionary, use a dictionary.

                            </F>

                            Comment

                            • Jeremy Sanders

                              #15
                              Re: naming objects from string

                              manstey wrote:
                              so they might provide a list of names, like 'bob','john','p ete', with 3
                              structures per name, such as 'apple','orange ','red' and I need 9 tuples
                              in my code to store their data:
                              >
                              bob_apple=()
                              bob_orange=()
                              ..
                              pete_red=()
                              I really think you should be using dictionaries here. You don't want to be
                              messing around creating random variables in the local or global namespace.

                              For instance

                              myvals = {}
                              myvals['bob'] = {}
                              myvals['pete'] = {}
                              ....
                              myvals['bob']['apple'] = (1,2,3,4)
                              myvals['bob']['orange'] = (2,3,4)
                              myvals['pete']['red'] = (4,5,6,7)

                              and so on
                              >>myvals
                              {'pete': {'red': (4, 5, 6, 7)}, 'bob': {'orange': (2, 3, 4), 'apple': (1, 2,
                              3,4)}}

                              --
                              Jeremy Sanders

                              Comment

                              Working...