Creating "virtual" module-namespace 
Author Message
 Creating "virtual" module-namespace

Imagine... there is a:

a= "class nasenbaer:\n  def singt():\n    print "tralala"\n\n"

(the content of a is:
class nasenbaer:
        def singt():
                print "tralala"

)

now I want to exec a in a "special" way so that later I can call

exec a in ???????

grail=somthing.nasenbaer()
grail.singt()

My try was

b=globals()

exec a in b
grail=b.nasenbaer()

but it failed...

what is the correct way?



Mon, 30 May 2005 06:17:43 GMT  
 Creating "virtual" module-namespace
I'm not sure this will help, but I observe that the namespace to be provided
is a dictionary. Thus a minimalist approach would be:

Quote:
>>> b = {}
>>> exec a in b
>>> type(b)

<type 'dict'>

What you need next is therefore

Quote:
>>> grail = b['nasenbaer']()

Then you will see you have a nasenbaer instance in grail. However ...

Quote:
>>> grail.singt()

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: singt() takes no arguments (1 given)

this error is because you forgot to put the "self" argument on the method's
argument list :-) I presume, though, that you are really interested in
getting nasenbaer in a namespace rather than a simple dictionary. You now
have some further food for thought...

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------

Quote:
> Imagine... there is a:

> a= "class nasenbaer:\n  def singt():\n    print "tralala"\n\n"

> (the content of a is:
> class nasenbaer:
>     def singt():
>         print "tralala"

> )

> now I want to exec a in a "special" way so that later I can call

> exec a in ???????

> grail=somthing.nasenbaer()
> grail.singt()

> My try was

> b=globals()

> exec a in b
> grail=b.nasenbaer()

> but it failed...

> what is the correct way?



Mon, 30 May 2005 07:06:31 GMT  
 Creating "virtual" module-namespace

Quote:

> now I want to exec a in a "special" way so that later I can call

> exec a in ???????

> grail=somthing.nasenbaer()
> grail.singt()

> My try was

> b=globals()

> exec a in b
> grail=b.nasenbaer()

> but it failed...

> what is the correct way?

You want a separate dictionary:

        myGlobals = {}
        exec statment in myGlobals

--

 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Even paranoids have real enemies.
\__/ Delmore Schwartz
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.



Mon, 30 May 2005 07:51:08 GMT  
 Creating "virtual" module-namespace

Quote:

> Imagine... there is a:

> a= "class nasenbaer:\n  def singt():\n    print "tralala"\n\n"

> (the content of a is:
> class nasenbaer:
>        def singt():
>                print "tralala"

> )

> now I want to exec a in a "special" way so that later I can call

> exec a in ???????

> grail=somthing.nasenbaer()
> grail.singt()

> My try was

> b=globals()

> exec a in b
> grail=b.nasenbaer()

> but it failed...

It's because b is a dictionary.  b['nasenbaer']() would have worked,
I think, but I don't think it's what you wanted.

Quote:
> what is the correct way?

I would do it this way.  I'm assuming "something" is an object (an
instance of some class) and you want to be able to call
something.nasenbaer().

    class whatever: pass
    something = whatever()

    exec a in globals(), something.__dict__
    grail = something.nasenbaer()

--
CARL BANKS



Mon, 30 May 2005 06:51:20 GMT  
 Creating "virtual" module-namespace
Quote:
> It's because b is a dictionary.  b['nasenbaer']() would have worked,
> I think, but I don't think it's what you wanted.

No, that is not wat I wanted :-=

Quote:
> I would do it this way.  I'm assuming "something" is an object (an
> instance of some class) and you want to be able to call
> something.nasenbaer().

Not att all... something can be NO object, because nasenbaer is a class
and will instanciate it's own objects.

something is rather a module.

I want to use it as if all the class definition is in one file and I do a
"import nameoffile"

then I have access to all the classes /functions via
newobjekt=nameoffile.class()

thanks for giving thoughts,

Harald



Mon, 30 May 2005 15:06:07 GMT  
 Creating "virtual" module-namespace
Erik, thank you for your thoughts, but

Quote:
>> exec a in b
>> grail=b.nasenbaer()
> You want a separate dictionary:
>      myGlobals = {}
>      exec statment in myGlobals

than I have to call

c=myGlobals["nasenbaer"]()

that is not exactly my Objective...



Mon, 30 May 2005 15:08:47 GMT  
 Creating "virtual" module-namespace

Quote:

> than I have to call

> c=myGlobals["nasenbaer"]()

> that is not exactly my Objective...

What exactly is your objective?

        exec "nasenbear()" in myGlobals

--

 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ You are the lovers rock / The rock that I cling to
\__/ Sade
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.



Mon, 30 May 2005 15:26:35 GMT  
 Creating "virtual" module-namespace
Erik,

Quote:
> What exactly is your objective?

I have some modules stored in strings (to be exact: in a database).

Now I want to use THIS modules in the same way as if I would import them
via
import FileName

If I simply exec this strings in "globals"

exec <string> in globals()

all the classes & functions are in my global namespace - without a
prefix.

That's all.

Thank you for your time

Harald



Mon, 30 May 2005 15:53:23 GMT  
 Creating "virtual" module-namespace

Quote:

> I have some modules stored in strings (to be exact: in a database).

> Now I want to use THIS modules in the same way as if I would import
> them
> via
> import FileName

> If I simply exec this strings in "globals"

> exec <string> in globals()

> all the classes & functions are in my global namespace - without a
> prefix.

Attribute access is related to a dictionary by an instance with a
__dict__ attribute.  You could try something like

        class Dummy: pass
        namespace = Dummy() # we just need an instance of _something_
        exec code in namespace.__dict__
        namespace.nasenbaer()

How's that grab you?

--

 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ To perceive is to suffer.
\__/ Aristotle
    Official Omega page / http://www.alcyone.com/max/projects/omega/
 The official distribution page for the popular Roguelike, Omega.



Mon, 30 May 2005 16:22:39 GMT  
 Creating "virtual" module-namespace

Quote:

>Imagine... there is a:

>a= "class nasenbaer:\n  def singt():\n    print "tralala"\n\n"

>(the content of a is:
>class nasenbaer:
>            def singt():
>                    print "tralala"

>)

>now I want to exec a in a "special" way so that later I can call

>exec a in ???????

>grail=somthing.nasenbaer()
>grail.singt()

>My try was

>b=globals()

>exec a in b
>grail=b.nasenbaer()

>but it failed...

>what is the correct way?

I don't know about correct, but trying to make something do
what you seem to want:

 >>> def pseudo_import(name, s):
 ...     class pseudo_module:
 ...         def __repr__(self): return '<pseudo_module %s>' % self.__name__
 ...     tmp = pseudo_module()
 ...     tmp.__dict__['__name__'] = name
 ...     exec s in tmp.__dict__
 ...     return tmp
 ...
 >>> a = """\
 ... class nasenbaer:
 ...             def singt(self):
 ...                     print "tralala"
 ... """
 >>>
 ==->> Note that you need a self argument (which I added) for a method,
       even if you don't use it explicitly.

 >>> fa = pseudo_import('file_a', a)
 >>> grail = fa.nasenbaer()
 >>> grail.singt()
 tralala
 >>> fa
 <pseudo_module file_a>
 >>> fa.nasenbaer
 <class file_a.nasenbaer at 0x007A9FD0>

Not tested any more than you see here, so caveat whatever ;-)

Regards,
Bengt Richter



Mon, 30 May 2005 17:11:36 GMT  
 Creating "virtual" module-namespace

Quote:

>I have some modules stored in strings (to be exact: in a database).

>Now I want to use THIS modules in the same way as if I would import them
>via
>import FileName

>If I simply exec this strings in "globals"

>exec <string> in globals()

>all the classes & functions are in my global namespace - without a
>prefix.

>That's all.

>Thank you for your time

>Harald

If I understood correctly, you have for example ['ftplib', 'mymodule']
stored in a database, and you want to, given one of the modules of the
database, use them like this:

x = mymodule.Foo()
mymodule.set('Hail')

If that is so, use the builtin function __import__:

mymodule = __import__('mymodule')

And there you go.

Hope that helps.
Nicodemus.



Mon, 30 May 2005 20:19:29 GMT  
 Creating "virtual" module-namespace

Quote:

>> It's because b is a dictionary.  b['nasenbaer']() would have worked,
>> I think, but I don't think it's what you wanted.
> No, that is not wat I wanted :-=

>> I would do it this way.  I'm assuming "something" is an object (an
>> instance of some class) and you want to be able to call
>> something.nasenbaer().
> Not att all... something can be NO object, because nasenbaer is a class
> and will instanciate it's own objects.

From your variable names I assume German is your native language? When
you say "something can be NO object" do you mean (please excuse my
German spelling) "'something' kann kein Objekt sein"? In that case, the
proper way to say it in English would be "'something' can NOT be an
object."

But you are wrong; something COULD be an object. Python makes no
distinction between what types of things a name can point to. A name can
point to a class, a function, a list, an object, a dict... And that name
can be in any namespace -- and objects have their own namespace.
Therefore, this is perfectly legal:

    class Record: pass

    something = Record()

    class nasenbaer:
        # Insert definition here...
        def __init__(self):
            # Do stuff
            pass

    something.foo = nasenbaer

    a = something.foo()  # Equivalent in every way to the next line
    a = nasenbaer()

What is happening here is that a name 'foo' is created in the namespace
of object 'something' -- so it is therefore accessed by 'something.foo'
since the period operator means namespace lookup. That name,
'something.foo', points to the same thing that the name nasenbaer points
to: a class definition.

Python's absolute separation between the concept of names and what they
point to is one of the biggest sources of confusion that I have seen; it
was an epiphany for me, coming to Python from places like C and Perl,
when I finally understood it. Just to make it clear: this:

    def func(foo, bar):
        return foo + bar

does NOT create a function called 'func'! It creates a *function object*
and also creates a name 'func' which *points to* the function object.
But there is nothing stopping you from redefining the name func:

    func = some_other_function

at which point the original function object (the one that would return
the sum of its two arguments) will have no names pointing to it at all
and will be inaccessible.

I hope this helps.

--

http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



Mon, 30 May 2005 23:55:05 GMT  
 Creating "virtual" module-namespace

Quote:

> If I understood correctly, you have for example ['ftplib', 'mymodule']
> stored in a database, and you want to, given one of the modules of the
> database, use them like this:

Not exactly. I have not stored the complete code of modules in a
database. I retrieve them to a string. And I want to treat (the
content of) this string like a module.

I CAN allready use the content of this string via compile and exec.
BUT all the modules are in the same namespace.

Quote:
> mymodule = __import__('mymodule')

If I try to do this on my string...
that is
mymodule=__import__(a)

where a contains the usual...
a='class nasenbaer:\n   def singe(self):\n      print "gugug"\n\n'

it yields an
ImportError: No module named class nasenbaer:

Thanks for your considerations,

Harald



Tue, 31 May 2005 00:14:39 GMT  
 Creating "virtual" module-namespace

Quote:
> Attribute access is related to a dictionary by an instance with a
> __dict__ attribute.  You could try something like

YEAH! That worked. EXACTLY the information I've been looking for.

Quote:
>    class Dummy: pass
>    namespace = Dummy() # we just need an instance of _something_
>    exec code in namespace.__dict__

changing the following lines to

kragenbaer=namespace.nasenbaer()
kragenbaer.singe()

gives me my "tralalala"

Thank you very much...

I was allready digging in the code of import hooks, but did not understand it...

Thanks for the solution

Harald



Tue, 31 May 2005 00:18:04 GMT  
 Creating "virtual" module-namespace
Robin,

thank you very much for taking time to clarify!

Quote:
> What is happening here is that a name 'foo' is created in the namespace
> of object 'something' -- so it is therefore accessed by 'something.foo'
> since the period operator means namespace lookup.

Coming from C++, Java, VB, PHP ... I was not able to imagine that much
orthogonal design.

Python is overwhelming in his clear concepts.

Quote:
> Python's absolute separation between the concept of names and what they
> point to is one of the biggest sources of confusion that I have seen;

So I know: I need an object only to form a namespace which I can access
via "."

I think it would be possible to use something else instead of an
object...

Do something like

zoo=[] # empty list
exec a in zoo.__dict__  # execute a in the namespace of "zoo"

Thank you very much

Harald



Tue, 31 May 2005 05:34:22 GMT  
 
 [ 17 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Mingw32 modules (was: "win32: cygwin modules")

2. string.join(["Tk 4.2p2", "Python 1.4", "Win32", "free"], "for")

3. Need to create module with virtual functions to mirror another module

4. Bug in "Move to/Namespace"?

5. ANN:Virtual Friends "club"

6. PTUI problem, "lifo::lifo": unknown namespace

7. Proposal: "Virtual References"

8. "load" into namespace

9. "namespace import": bug or feature?

10. Why no "namespace exists"

11. BUGS?: Tcl8 "namespace" quirks

12. require/provide and "unknown" namespace fix

 

 
Powered by phpBB® Forum Software