python


Different import behaviour for different modules


I have three modules a.py, b.py and c.py. The a.py module is the base one. What I want to achieve is to have different behaviour when a.py is imported by b.py and when a.py is imported by c.py. For example:
a.py
def ab():
return 5
def ac():
return 6
if __nameoftheimportmodule__ == 'b':
x = ab()
elif __nameoftheimportmodule == 'c':
x = ac()
else:
pass
Therefore, calling b.py like this:
b.py
import a
print(a.x)
will return 5 (and for c.py it would return 6).
And my question is whether such a design is possible (e.g. whether there exists such a function that behaves like the above-mentioned nameoftheimportmodule)?
You'd have to screw with the import system pretty hard to do that, especially since ordinarily, the module's code won't even run again when the second module imports it. Python will just reuse the same module object created on the first import, with the same value of x stored.
You could do it by replacing __import__, or maybe by using one of the less sledgehammery hooks the import system provides, but it's not at all worth it, and it's not going to lead to programs that are easy to understand or reason about.
The closest solution I could find to match that behavior is using the inspect module's stack function:
import inspect
def ab():
return 5
def ac():
return 6
if inspect.stack()[1][1] == 'b.py':
x = ab()
elif inspect.stack()[1][1] == 'c.py':
x = ac()
else:
pass
inspect.stack():
Return a list of frame records for the caller’s stack. The first entry
in the returned list represents the caller; the last entry represents
the outermost call on the stack.
When inspect.stack() is called from a.py, we get
[(<frame object at 0x102c25dd0>, '/Users/home/43985900/a.py', 3, '<module>', ['print inspect.stack()\n'], 0), (<frame object at 0x102c25c20>, 'c.py', 1, '<module>', ['print(a.x)\n'], -1)]
We're interested in "the last entry represents the outermost call on the stack" so we index the stack as stack[1][1] to get 'c.py', which we compared to the calling module's filenames.
Now when we test run the modules we get the expected output:
$ python c.py
6
$ python b.py
5
Adapted from this question's answer: Get name of calling function's module in Python.

Related Links

Ambigouos columns 'data' in Spark Dataframe
Converting Numpy Array Element to String: TypeError: bad operand type for unary +: 'str'
python import error cx_Oracle in macOS Sierra
Select specific rows and cells in text file and put into data frame: python or R
TensorFlow dynamic_rnn regressor: ValueError dimension mismatch
Using converters in Pandas read_hdf similar to read_csv
python3 package path of local file
Viewing other user profile
Python Tkinter, Stop a threading function
Python runtime warning when move unit test to a package
UserWarning on Django website for Raven client
Organise .rst files for sphinx?
Scatter Plot of a Specific Column in Python using matplotlib
How to make difference between email html body and html attachment in python?
Cobb-Douglas maximization in python
Django won't serve some static files

Categories

HOME
visual-studio-2015
sass
itext
voip
angular2-routing
command
apache2
rocketmq
appmaker
orientation
console
finite-group-theory
store
lstm
spring-cloud-config
bar-chart
arm-template
jcl
delete-file
bcrypt
iis-10
onesignal
owl-api
chrome-native-messaging
strophe
picturebox
spring-profiles
fractals
idl
mapguide
duktape
nsexception
viewgroup
xbim
html-agility-pack
amd
jtds
ideone
azureportal
windows-95
photon-controller
date-range
glkit
aescryptoserviceprovider
ruby-2.0
asteriskami
amf
listadapter
achievements
post-processing
handlebars.java
except
site-prism
matcaffe
registrykey
sem
textkit
python-winshell
visual-studio-code
xjc
crash-dumps
callstack
scrollspy
start-job
cocoascript
candidate-key
jstat
genetic-programming
aquafold
alpha-transparency
valence
data-generation
httpcontext
uipickerviewcontroller
lov
modeshape
vertical-rhythm
justgage
digital-design
htmltextwriter
returnurl
cosm
plone-funnelweb
mpmovieplayer
subtract
hinstance
port-scanning
nvelocity
pureftpd
loadui
svn-hooks
unreachable-code
openvg
iphone-sdk-3.2
graph-layout
usability-testing
database-diagramming
standardized
dotproject

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App