472,353 Members | 1,483 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

Re: Function to import module to namespace

Terry Reedy wrote:
>
<snip>
>
Do you mean something like this?
<snip>
>>math.__dict__.update(string.__dict__)
>>dir(math)
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__',
<snip>

I think this is working.... First off, 2 module files:

funcs.py
def func1():
print "I'm func1 in funcs.py"

more.py
def func2():
print "I'm func2 in 'more.py'"

and my wonderful main program:

xx.py
import funcs
def addnewfuncs(p):
x = __import__(p)
funcs.__dict__.update(x.__dict__)
funcs.func1()
addnewfuncs('more')
funcs.func2()

The first problem I had was getting import to accept a variable. It
doesn't seem to, so I used __import__(). Then, I had to remember to
assign this to a variable ... and then it appears to work just fine.

Did I miss anything in this???

Thanks for the pointer!

Bob.
Jun 29 '08 #1
4 1156
On Jun 30, 9:52 am, bvdp <b...@mellowood.cawrote:
Terry Reedy wrote:
>

<snip>
>
Do you mean something like this?

<snip>
>>math.__dict__.update(string.__dict__)
>>dir(math)
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__',

<snip>

I think this is working.... First off, 2 module files:

funcs.py
def func1():
print "I'm func1 in funcs.py"

more.py
def func2():
print "I'm func2 in 'more.py'"

and my wonderful main program:

xx.py
import funcs
def addnewfuncs(p):
x = __import__(p)
funcs.__dict__.update(x.__dict__)
funcs.func1()
addnewfuncs('more')
funcs.func2()

The first problem I had was getting import to accept a variable. It
doesn't seem to, so I used __import__(). Then, I had to remember to
assign this to a variable ... and then it appears to work just fine.

Did I miss anything in this???
You are updating with *everything* in the 'more' module, not just the
functions. This includes such things as __name__, __doc__, __file__.
Could have interesting side-effects.

One quick silly question: why do you want to do this anyway?

Sorry, *two* quick silly questions: are the add-on modules under your
control, or do you want to be able to do this with arbitrary modules?
[If under your control, you could insist that such modules had an
__all__ attribute with appropriate contents]

A third: why do you want to import into an existing namespace? Now
that you know about __import__, why just not call the functions where
they are?

Cheers,
John
Jun 30 '08 #2
John Machin wrote:

<snip>

Good questions. Short answer ... probably 'cause I've not thought the
problem though completely :)
You are updating with *everything* in the 'more' module, not just the
functions. This includes such things as __name__, __doc__, __file__.
Could have interesting side-effects.

One quick silly question: why do you want to do this anyway?
I'm writing a "simple" macro expander. I've got some mainline code which
reads an input file, parses out macros, and expands them. So, in my
input file I might have something like:

a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ]

So, I need a function link() to evaluate and return "http://...."

Instead of putting funcs like link() in my mainline I've stuck them in a
module of their own. In the mainline I

import funcs

and then when I need to expand I have the following code:

if not cmd in vars(funcs):
error("Unknown function/variable '%s'" % cmd)

if type(vars(funcs)[cmd]) == type(parse):
txt = eval("""funcs.%s("%s")""" % (cmd, arg))

else: # not a func, just expand the variable
if arg:
error("Argument to variable '%s' not permitted." % cmd)
txt = str(eval("funcs.%s" % cmd ))

Of course, the question comes up ... what if a user (probably me) wants
to add more functions? Easy enough to just edit funcs.py I suppose, but
I thought it'd be nice to use more modules.

So, I suppose that rather than adding the 2ndary module stuff to the
default 'funcs.py' I could just as well have a look and check for the
needed function in all the modules I've imported.

Sorry, *two* quick silly questions: are the add-on modules under your
control, or do you want to be able to do this with arbitrary modules?
[If under your control, you could insist that such modules had an
__all__ attribute with appropriate contents]
Why would I want to do that ... and how?
A third: why do you want to import into an existing namespace? Now
that you know about __import__, why just not call the functions where
they are?
Yeah, that would probably be cleaner (safer).

Thanks.
Jun 30 '08 #3
On Jun 30, 11:45 am, bvdp <b...@mellowood.cawrote:
John Machin wrote:

<snip>

Good questions. Short answer ... probably 'cause I've not thought the
problem though completely :)
You are updating with *everything* in the 'more' module, not just the
functions. This includes such things as __name__, __doc__, __file__.
Could have interesting side-effects.
>
One quick silly question: why do you want to do this anyway?
>

I'm writing a "simple" macro expander. I've got some mainline code which
reads an input file, parses out macros, and expands them. So, in my
input file I might have something like:

a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ]

So, I need a function link() to evaluate and return "http://...."

Instead of putting funcs like link() in my mainline I've stuck them in a
module of their own.
Why? Do they have any use at all other than to be called by your
mainline?
In the mainline I

import funcs

and then when I need to expand I have the following code:
Build a dictionary *ONCE*, not each time you want to look in it. E.g.

funcs_vars = vars(funcs)

.... much later:

if not cmd in funcs_vars:

if not cmd in vars(funcs):
error("Unknown function/variable '%s'" % cmd)

if type(vars(funcs)[cmd]) == type(parse):
txt = eval("""funcs.%s("%s")""" % (cmd, arg))
Any particular reason why you are going to the trouble of laboriously
building a statement, compiling it, and running it, when you could
simply do:
txt = funcs_vars[cmd](arg)
?
>
else: # not a func, just expand the variable
if arg:
error("Argument to variable '%s' not permitted." % cmd)
txt = str(eval("funcs.%s" % cmd ))
txt = str(funcs_vars[cmd])
>
Of course, the question comes up ... what if a user (probably me) wants
to add more functions? Easy enough to just edit funcs.py I suppose, but
I thought it'd be nice to use more modules.
You may already have one more module than you need. If the only thing
different about the extra functions is that they are an afterthought,
then put them in the same module as the others.
>
So, I suppose that rather than adding the 2ndary module stuff to the
default 'funcs.py' I could just as well have a look and check for the
needed function in all the modules I've imported.
Sounds quite unnecessary, inefficient and pointless to me.
>
Sorry, *two* quick silly questions: are the add-on modules under your
control, or do you want to be able to do this with arbitrary modules?
[If under your control, you could insist that such modules had an
__all__ attribute with appropriate contents]

Why would I want to do that ... and how?
Why: so that you append only the functions that you want to the target
namespace, and don't import stuff like __name__. How: read about
__all__. Just append the stuff that's listed in __all__. However it
sounds like you have seen the light and won't be doing anything like
appending to a namespace.
>
A third: why do you want to import into an existing namespace? Now
that you know about __import__, why just not call the functions where
they are?

Yeah, that would probably be cleaner (safer).
Much cleaner, safer, etc is just to import, or even not to have a
separate module at all.

HTH,
John
Jun 30 '08 #4
John Machin wrote:
On Jun 30, 11:45 am, bvdp <b...@mellowood.cawrote:
>John Machin wrote:

<snip>

Good questions. Short answer ... probably 'cause I've not thought the
problem though completely :)
> You are updating with *everything* in the 'more' module, not just the
functions. This includes such things as __name__, __doc__, __file__.
Could have interesting side-effects.

One quick silly question: why do you want to do this anyway?

I'm writing a "simple" macro expander. I've got some mainline code which
reads an input file, parses out macros, and expands them. So, in my
input file I might have something like:

a fjas j kj sdklj sdkl jfsdkl [ link somewhere sometext ]

So, I need a function link() to evaluate and return "http://...."

Instead of putting funcs like link() in my mainline I've stuck them in a
module of their own.

Why? Do they have any use at all other than to be called by your
mainline?
> In the mainline I

import funcs

and then when I need to expand I have the following code:

Build a dictionary *ONCE*, not each time you want to look in it. E.g.

funcs_vars = vars(funcs)

... much later:

if not cmd in funcs_vars:

>if not cmd in vars(funcs):
error("Unknown function/variable '%s'" % cmd)

if type(vars(funcs)[cmd]) == type(parse):
txt = eval("""funcs.%s("%s")""" % (cmd, arg))

Any particular reason why you are going to the trouble of laboriously
building a statement, compiling it, and running it, when you could
simply do:
txt = funcs_vars[cmd](arg)
?
> else: # not a func, just expand the variable
if arg:
error("Argument to variable '%s' not permitted." % cmd)
txt = str(eval("funcs.%s" % cmd ))

txt = str(funcs_vars[cmd])
>Of course, the question comes up ... what if a user (probably me) wants
to add more functions? Easy enough to just edit funcs.py I suppose, but
I thought it'd be nice to use more modules.

You may already have one more module than you need. If the only thing
different about the extra functions is that they are an afterthought,
then put them in the same module as the others.
>So, I suppose that rather than adding the 2ndary module stuff to the
default 'funcs.py' I could just as well have a look and check for the
needed function in all the modules I've imported.

Sounds quite unnecessary, inefficient and pointless to me.
>>Sorry, *two* quick silly questions: are the add-on modules under your
control, or do you want to be able to do this with arbitrary modules?
[If under your control, you could insist that such modules had an
__all__ attribute with appropriate contents]
Why would I want to do that ... and how?

Why: so that you append only the functions that you want to the target
namespace, and don't import stuff like __name__. How: read about
__all__. Just append the stuff that's listed in __all__. However it
sounds like you have seen the light and won't be doing anything like
appending to a namespace.
>>A third: why do you want to import into an existing namespace? Now
that you know about __import__, why just not call the functions where
they are?
Yeah, that would probably be cleaner (safer).

Much cleaner, safer, etc is just to import, or even not to have a
separate module at all.

HTH,
John
Thanks. Much food for thought here. Let me digest and see what comes of
it all.
Jun 30 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Torsten Bronger | last post by:
Hallöchen! I have a file that looks a little bit like a C header file with a long list of variables (actually constants) definitions, e.g. ...
3
by: Jim | last post by:
I would be very grateful for help on the following. I have the following modules in a program. Names changed to protect the innocent. ...
5
by: Pekka Niiranen | last post by:
Hi there, I have two scripts. The first "main.py" sets some variables and then imports another called "gen.py". The idea is to provide "main.py"...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() :...
23
by: Shane Hathaway | last post by:
Here's a heretical idea. I'd like a way to import modules at the point where I need the functionality, rather than remember to import ahead of...
5
by: Ian Bicking | last post by:
I got a puzzler for y'all. I want to allow the editing of functions in-place. I won't go into the reason (it's for HTConsole --...
11
by: Brian Blazer | last post by:
OK, I have a very simple class here: class Student: """Defines the student class""" def __init__(self, lName, fName, mi): self.lName = lName...
49
by: Martin Unsal | last post by:
I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like...
6
by: beginner | last post by:
Hi Everyone, Is there any equivalent version of C's static function in Python. I know I can make a class function private by starting a function...
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.