473,401 Members | 2,068 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,401 software developers and data experts.

Tricky import question.

importedfiles = {}
for f in FileList
f2 = f.split('.')[0] # strip the .py, .pyc
__import__(f2)
s2 = f2+'.main()' # main is the top file in each import
c = compile(s2, '', 'eval')
importedfiles[f2] = eval(c)

'importedfiles' should hold an object reference to the main() function
within each imported file.

The problem is, the import function works but I can't get the object
reference into the imortedfiles dictionary object. the code keeps
telling me

NameError: name 'C1_Dosing' is not defined.

in this instance C1_Dosing is the first file name in the filelist. The
import worked, why not the compile ??

TIA.

Oct 25 '05 #1
7 1771
David Poundall wrote:
importedfiles = {}
for f in FileList
f2 = f.split('.')[0] # strip the .py, .pyc
__import__(f2)
s2 = f2+'.main()' # main is the top file in each import
c = compile(s2, '', 'eval')
importedfiles[f2] = eval(c)

'importedfiles' should hold an object reference to the main() function
within each imported file.

The problem is, the import function works but I can't get the object
reference into the imortedfiles dictionary object. the code keeps
telling me

NameError: name 'C1_Dosing' is not defined.

in this instance C1_Dosing is the first file name in the filelist. The
import worked, why not the compile ??


because your __import__ statement didn't assign the returned module
to anything, so there's no C1_Dosing in the current namespace.

assuming that the main function in each module returns something that
you want to store in the importedfiles dictionary, here's a better way to
do it:

m = __import__(f2)
importedfiles[f2] = getattr(m, "main")()

tweak as necessary.

</F>

Oct 25 '05 #2
Sadly I get this reply when I try that.

AttributeError: 'module' object has no attribute 'main'

I am getting the impression that the value returned from the
__import__() function is only a string reference NOT an object.

I am going to have a go at trying this with the imp' module as that
specifically mentions that an object is returned.

Oct 25 '05 #3
This worked ...

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

for reasons given here...

http://www.python.org/doc/2.3.5/lib/built-in-funcs.html

Oct 25 '05 #4
On 25 Oct 2005 06:39:15 -0700, "David Poundall" <da***@jotax.com> wrote:
importedfiles = {}
for f in FileList
f2 = f.split('.')[0] # strip the .py, .pyc importedfiles[f2] = __import__(f2).main
# it sounds like all you want is the above (untested ;-), or
# use __import__(f2).main() if you actually want the _result_ returned by main

Either way, you don't need the following __import__(f2)
s2 = f2+'.main()' # main is the top file in each import
c = compile(s2, '', 'eval')
importedfiles[f2] = eval(c)

'importedfiles' should hold an object reference to the main() function
within each imported file. Do you want a reference to the function, or the result of calling the function?
If you want a reference to the function itself, you should leave off the () after main,
otherwise you will execute the function.

The problem is, the import function works but I can't get the object
reference into the imortedfiles dictionary object. the code keeps
telling me

NameError: name 'C1_Dosing' is not defined. probably your first file is C1_Dosing.py (or some other extension after the '.')
so f2 becomes 'C1_Dosing' and s2 becomes 'C1_Dosing.main()' and you compile that
into code bound to c, and when you try to eval(c), it tries to find C1_Dosing in
the current environment, et voila! you have the error.

When confronted with mysteries such as presented by your code results, I suggest
you intruduce print statements to verify what you are assuming about what it is doing.
E.g., you could print repr(f2) after assignment, and after the __import__ if you thought
it was going to do something to f2 in the local name space, and repr(s2) after the assignment,
etc. to see if I guessed right. Or a quick line to clone for a snapshot of local varibles
at different points might be (untested)
print '\n'.join('%15s: %s'%(k, repr(v)[:60]) for k,v in sorted(locals().items()))

in this instance C1_Dosing is the first file name in the filelist. The
import worked, why not the compile ?? I think the compile did work. But your code didn't produce a binding for the name
'C1_Dosing' which the code c was looking for when eval(c) was called. If you wanted to
make your code work, perhaps replacing (untested)
__import__(f2)
with
exec '%s = __import__(f2)'%f2 # bind imported module to name specified by f2 string
might have got by the error in eval (c), but I suspect you would want to leave the () off
the .main in any case. And why go through all that rigamarole?

TIA.

Try it both ways and report back what you found out ;-)

Regards,
Bengt Richter
Oct 25 '05 #5
On 25 Oct 2005 08:51:08 -0700, "David Poundall" <da***@jotax.com> wrote:
This worked ...

def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

for reasons given here...

http://www.python.org/doc/2.3.5/lib/built-in-funcs.html

Aha. You didn't mention multi-dot names ;-)
But was that the real problem? Your original code
wasn't using anything corresponding to mod above.

Regards,
Bengt Richter
Oct 25 '05 #6
All I was trying to do with my feeble code attempt, was to return a
reference to the imported module so that I could do...

result = instanceref.main()

where main was a function within the import.

Having glanced at the code in the import section of the help files all
morning, when I actually sat down and read it it turned out the example
code was what I needed.

Its always the way.

Many thanks for taking time out to reply Bengt.

Oct 25 '05 #7
repr() is a new one on me I am afraid, and I have yet to achieve any
decent competance with global and local lists.

As you probaly noticed earlier, I managed to bungle my way through this
time. However, I will log this thread away for when I next get stuck
with a bindings.

Thank you Bengt :-)

Oct 25 '05 #8

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

Similar topics

1
by: JZ | last post by:
Oracle 9iR2 I have a table: SQL> select * from test; A B C ------------------- ---------- ---------- 01/01/2004 10:00:00 1 1...
2
by: Charles Fineman | last post by:
I've been asked to look over an integration toolkit that has a bunch of schemas to specify message format. There are a couple of strange things I noticed right off the bat and I wanted to get...
0
by: Piotr Szukalski | last post by:
Hi! I have a quite tricky question about .NET debugger: do I need to install the whole SDK to make SDK CLR debugger working? The situation is as follows: I have an application deployed to 130...
25
by: PyPK | last post by:
What possible tricky areas/questions could be asked in Python based Technical Interviews?
8
by: pras.vaidya | last post by:
Hi , below given question was asked to me during an interview and i figured it out little tricky . It would be a great help if anyone could solve it. Code : - main() { char...
3
by: Dave | last post by:
So I'm trying to write a CSS preprocessor. I want to add the ability to append a selector onto other selectors. So, given the following code: ========================================= #selector...
14
by: felixnielsen | last post by:
Consider this 3d vector: const SIZE = 'some_size'; std::vector<std::vector<std::vector<char> > >GRID(SIZE, std::vector<std::vector<char> >(SIZE, std::vector<char>(SIZE))); It can be viewed...
9
by: howachen | last post by:
Hi, I have one very simple tricky question which is quite interesting, I would like to share with all of you here... //======================================= <script...
5
by: Erich93063 | last post by:
Ok so I'm gonna attempt to explain my problem as easy as I can. I have a database of contacts (they are actually vendors). I am writing a procedure that will query the vendors and generate a tab...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.