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

Get importer module from imported module


I found this problem when trying to split a module into two.
Here's an example:

==============
#Module a (a.py):
from b import *
class Main: pass
==============

==============
#Module b (b.py)
def How():
Main_instance = module_a.Main()
return Main_instance
==============
import a
a.How()

the problem would show at How() function. I have been unable
to get variable pointing to module a from inside module b.
In short, I need to have a variable pointing to the module
whose importing me.
--
dody s wijaya <do****@gmail.com>, YM: dody, [36932B53]

Jul 18 '05 #1
5 1991
dody suria wijaya wrote:

I found this problem when trying to split a module into two.
Here's an example:

==============
#Module a (a.py):
from b import *
class Main: pass
==============

==============
#Module b (b.py)
def How():
Main_instance = module_a.Main()
return Main_instance
==============
import a
a.How()

the problem would show at How() function. I have been unable
to get variable pointing to module a from inside module b.
In short, I need to have a variable pointing to the module
whose importing me.


'import a' will let you reference module 'a', unless 'a' was invoked as a
script in which case you would need 'import __main__'.

#Module b (b.py)
import a
def How():
Main_instance = a.Main()
return Main_instance

But: keep in mind that all statements (except 'global') are executable in
Python, so you must not call How() until after the Main class has actually
been created. This is one reason why it is generally safer to import a
module and do the lookup when you need it instead of using 'from
amodule import *' which can only get at the names which exist at the time
it is executed.

A better solution would be to structure your code so that your modules
don't have any mutual dependencies. If your function 'How()' is in module b
then just call 'b.How()' wherever you use it and lose the import of 'b'
from 'a' altogether.
Jul 18 '05 #2
Thank you for such a quick reply. There were some details I
had left behind related to my case that I guess would now
need to be told to better illustrate the problem.

I have many different module of "a", let's called it a1, a2 ...
a100, and there is only one module "b". Here's a better
example (and using some of your tips):

#Module a1
import b
class Main(b.Basic): pass

#Module a2
import b
class Main(b.Basic): pass

#Module a3
import b
class Main(b.Basic): pass

..
..
..

#Module b
class Basic: pass
class SaltyMixIn: pass
class SugaryMixIn: pass
def Salty():
class Food(SaltyMixIn,module_importing_me.Main): pass
return Food()
def Sweet():
class Food(SugaryMixIn,module_importing_me.Main): pass
return Food()

#Module c
import sys
food_no = sys.argv[1]
m = __import__(food_no)
goodie = m.Salty()
"import a" inside b would not solve the problem, since there
are many "module a" and module b does not know beforehand
which module had imported it. I could, say, put these
additional lines on all "module a" (which I previously had
and worked):

#Module a1
import b
class Main(b.Basic): pass
class Salty(SaltyMixIn,Main): pass # new
class Sweet(SaltyMixIn,Main): pass # new
but dislike it for personal taste; code dupes (there could
be a lot of food flavouring), and sheer messiness.
--
dody suria wijaya
YahooMsgr ID: dody

Monday, February 7, 2005, 6:10:14 PM, you wrote:

DB> dody suria wijaya wrote:

I found this problem when trying to split a module into two.
Here's an example:

==============
#Module a (a.py):
from b import *
class Main: pass
==============

==============
#Module b (b.py)
def How():
Main_instance = module_a.Main()
return Main_instance
==============
import a
a.How()

the problem would show at How() function. I have been unable
to get variable pointing to module a from inside module b.
In short, I need to have a variable pointing to the module
whose importing me.


DB> 'import a' will let you reference module 'a',
DB> unless 'a' was invoked as a
DB> script in which case you would need 'import __main__'.

DB> #Module b (b.py)
DB> import a
DB> def How():
DB> Main_instance = a.Main()
DB> return Main_instance

DB> But: keep in mind that all statements (except
DB> 'global') are executable in
DB> Python, so you must not call How() until after the Main class has actually
DB> been created. This is one reason why it is
DB> generally safer to import a
DB> module and do the lookup when you need it instead of using 'from
DB> amodule import *' which can only get at the names which exist at the time
DB> it is executed.

DB> A better solution would be to structure your code so that your modules
DB> don't have any mutual dependencies. If your
DB> function 'How()' is in module b
DB> then just call 'b.How()' wherever you use it and lose the import of 'b'
DB> from 'a' altogether.

Jul 18 '05 #3
dody suria wijaya wrote:
"import a" inside b would not solve the problem, since there
are many "module a" and module b does not know beforehand
which module had imported it.
Ok, I understand now what you are trying to achieve, but there isn't any
concept relating a module back to the first module which tried to import
it. Instead you'll have to specify the relationship yourself.

How about this:
#Module c import sys
food_no = sys.argv[1]
m = __import__(food_no)
goodie = b.Salty(m)
#Module b ....
def Salty(module):
class Food(SaltyMixIn,module.Main): pass
return Food()
....

In fact, it looks like the importing isn't really something module c should
be concerned about. I haven't tested the following code (so it will have
bugs), but it should give you some ideas. It remembers classes it has
created so as not to duplicate them, and it also gives each class a
sensible name.
#Module c import sys
food_no = sys.argv[1]
goodie = b.Salty(food_no)
#Module b

....
import new
Classes = {}

def makeFood(classname, food, mixin):
m = __import__(food)
main = m.Main
if (mixin, main) in Classes:
return Classes[mixin, main]()

newclass = new.classobj(classname + '_' + food, (mixin, main), {})
Classes[mixin, main] = newclass
return newclass
def Salty(food):
return makeFood('Salty', food, SaltyMixIn)
....

Jul 18 '05 #4
Yup, Got it.

New problem though. On line:

newclass = new.classobj(classname + '_' + food, (mixin, main), {})

received "TypeError: metaclass conflict: the metaclass of a
derived class must be a (non-strict) subclass of the
metaclasses of all its bases". This had not happened when
was written using 'normal' style like:

class (SaltyMixIn, Main): pass

--
dody suria wijaya
YahooMsgr ID: dody

Monday, February 7, 2005, 7:20:14 PM, you wrote:

DB> dody suria wijaya wrote:
"import a" inside b would not solve the problem, since there
are many "module a" and module b does not know beforehand
which module had imported it.
DB> Ok, I understand now what you are trying to
DB> achieve, but there isn't any
DB> concept relating a module back to the first module which tried to import
DB> it. Instead you'll have to specify the relationship yourself.

DB> How about this:
#Module c DB> import sys
DB> food_no = sys.argv[1]
DB> m = __import__(food_no)
DB> goodie = b.Salty(m)
#Module b DB> ...
DB> def Salty(module):
DB> class Food(SaltyMixIn,module.Main): pass
DB> return Food()
DB> ...

DB> In fact, it looks like the importing isn't really
DB> something module c should
DB> be concerned about. I haven't tested the following code (so it will have
DB> bugs), but it should give you some ideas. It remembers classes it has
DB> created so as not to duplicate them, and it also gives each class a
DB> sensible name.
#Module c DB> import sys
DB> food_no = sys.argv[1]
DB> goodie = b.Salty(food_no)
#Module b

DB> ...
DB> import new
DB> Classes = {}

DB> def makeFood(classname, food, mixin):
DB> m = __import__(food)
DB> main = m.Main
DB> if (mixin, main) in Classes:
DB> return Classes[mixin, main]()

DB> newclass = new.classobj(classname + '_' + food, (mixin, main), {})
DB> Classes[mixin, main] = newclass
DB> return newclass
DB> def Salty(food):
DB> return makeFood('Salty', food, SaltyMixIn)
DB> ...
Jul 18 '05 #5
dsw> New problem though. On line:
dsw> newclass = new.classobj(classname + '_' + food, (mixin, main), {})
dsw> received "TypeError: metaclass conflict: the metaclass of a
dsw> derived class must be a (non-strict) subclass of the
dsw> metaclasses of all its bases".

Oops, goofed up on me. The above "main" had mistakenly
pointed to the module. main.Main did the trick.

-- dsw

Jul 18 '05 #6

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

Similar topics

9
by: Paul Rubin | last post by:
That's what the Python style guides advise. They don't seem to like def frob(x): import re if re.search('sdfxyz', x): ... instead preferring that you pollute your module's global namespace...
8
by: Grant D. Watson | last post by:
If this has been answered before, or if my terminology is off, please bear with me; my Python experience is limited to use in one class and to personal projects. I'd like to do something rather...
17
by: Jacek Generowicz | last post by:
I have a module whose behaviour needs to be configurable. The module needs to decide, the first time it is imported, beteween alternative interfaces it presents. Currently, I set some...
1
by: aurora00 | last post by:
I'm using Python in a scripting environment. The host application would pass in some objects so that the script can act on it. But there are a number of things I like to add to every script to make...
10
by: Michael Abbott | last post by:
It seems to be an invariant of Python (insofar as Python has invariants) that a module is executed at most once in a Python session. I have a rather bizzare example that breaks this invariant: can...
10
by: Charles Russell | last post by:
Why does this work from the python prompt, but fail from a script? How does one make it work from a script? #! /usr/bin/python import glob # following line works from python prompt; why not in...
4
by: noagbodjivictor | last post by:
I have a variable names actions in a module named qt_actions.py Well this is what I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object...
5
by: saif.shakeel | last post by:
#!/usr/bin/env python from elementtree import ElementTree as Element tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): if t.get("Semantics") == "localId":...
3
by: Jugdish | last post by:
Why doesn't the following work? $HOME/pkg/__init__.py $HOME/pkg/subpkg/__init__.py $HOME/pkg/subpkg/a.py $HOME/pkg/subpkg/b.py # empty import a
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.