473,324 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 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 1229
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. VI_ATTR_TIMO = 0x54378 .... Actually I need this...
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. 1.Simulation 2.Branches 3.MyFiles I import Branches,...
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" that defines some paths, variables etc. without...
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() : global math # necessary ?????? else next line...
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 time. This might eliminate a step in my coding...
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 -- http://blog.ianbicking.org/introducing-htconsole.html), except that...
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 self.fName = fName self.mi = mi
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 the Python package system, in particular the...
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 name with two underscores, but it does not work...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.