473,687 Members | 3,538 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I access a main frunction from an import module?

Jim
Hi,

I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
############### #######

python25.exe main.py

Thanks,
Jim

Nov 24 '06 #1
11 1487
Jim wrote:
Hi,

I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
############### #######

python25.exe main.py
import __main__
....
__main__.m()
but better make a start.py and "import main" - then its symmetric
Robert
Nov 24 '06 #2

Jim wrote:
I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
############### #######

You can do it with "from __main__ import m" atop abc.py (the module
invoked at the command line is always called __main__).

However, I *highly* suggest you put m in another file. Importing
variables from __main__ would make your program incompatible with many
useful tools. For example, if you invoke the Python profiler on your
code, like this:

python -m profile main.py

it will break your code, because __main__ no longer refers to main.py
but to profile.py (from the Python library). Importing from __main__
adversely affects tools such as PyChecker and PyLint.

The exception to this would be if abc.py is specifically designed as a
utility for interactive use; then it would be ok and useful.
Carl Banks

Nov 24 '06 #3
Jim wrote:
I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
import sys
def a():
sys.modules['__main__'].m()
return None

Anton

'now why would anyone want to do *that* ?'
Nov 24 '06 #4
Jim wrote:
I have created an import module. And would like to access a
function from the main script, e.g.,
May I ask why? This style violates "normal" module philosophy.

Regards,
Björn

--
BOFH excuse #307:

emissions from GSM-phones

Nov 24 '06 #5
Jim

Bjoern Schliessmann wrote:
Jim wrote:
I have created an import module. And would like to access a
function from the main script, e.g.,

May I ask why? This style violates "normal" module philosophy.

Regards,
Björn

--
BOFH excuse #307:

emissions from GSM-phones
Application abc is designed as a complete module. The user is to
script their own functions to work with application abc.

Thanks,
JIm

Nov 24 '06 #6
Jim wrote:
Hi,

I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
############### #######

python25.exe main.py
Although there are literally correct answers to your question, the best
answer is "Don't do that. You would be creating circular references
between modules, and run the risk of emulating the mythical ooloo bird
by disappearing up your own fundamental orifice". Some possible
practical solutions:

1. Put the m function in a 3rd file/module. Then any other module which
needs it can import/call.

2. If you think that's not a good idea, then put it in abc.py (it's not
used in main.py in your example).

3. Maybe this will suit what you are really trying to do:

file abc.py:
############### ####
def a(argfunc): # <<<<<=====
argfunc() # <<<<<=====
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'

a(m) # <<<<<=====
############### #######

4. If you think *that's* not a good idea, then you might like to
explain at a higher level what you are *really* trying to achieve :-)
E.g. "Function m is one of n functions in main.py of which abc.py
may/must call 0, 1, or many because blah blah blah ..."

BTW, "return None" at the very end of a function is redundant. The
Python compiler generates "return None" automagically (implicitly!?)
instead of letting you fall off the end of the world. Which book or
tutorial are you using?

BTW #2: "python25.e xe main.py" ?? If you are on Windows, have Python
2.4 as your default setup, and are trialling 2.5: you may like to ask
(in a new thread) about more convenient ways of doing it. Otherwise you
might like to tell what you are up to (in a new thread) so that your
problem can be diagnosed correctly and cured :-)

HTH,
John

Nov 24 '06 #7
Jim wrote:
Application abc is designed as a complete module. The user is to
script their own functions to work with application abc.
so use execfile() with a prepared namespace:

namespace = { ...stuff to export to the module ... }
execfile("direc tory/module.py", namespace)

</F>

Nov 24 '06 #8
Jim
John Machin wrote:
Jim wrote:
Hi,

I have created an import module. And would like to access a function
from the main script, e.g.,

file abc.py:
############### ####
def a():
m()
return None
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'
return None

a()
############### #######

python25.exe main.py

Although there are literally correct answers to your question, the best
answer is "Don't do that. You would be creating circular references
between modules, and run the risk of emulating the mythical ooloo bird
by disappearing up your own fundamental orifice". Some possible
practical solutions:

1. Put the m function in a 3rd file/module. Then any other module which
needs it can import/call.

2. If you think that's not a good idea, then put it in abc.py (it's not
used in main.py in your example).

3. Maybe this will suit what you are really trying to do:

file abc.py:
############### ####
def a(argfunc): # <<<<<=====
argfunc() # <<<<<=====
############### #####

file main.py:
############### ######
from abc import *
def m():
print 'something'

a(m) # <<<<<=====
############### #######

4. If you think *that's* not a good idea, then you might like to
explain at a higher level what you are *really* trying to achieve :-)
E.g. "Function m is one of n functions in main.py of which abc.py
may/must call 0, 1, or many because blah blah blah ..."

BTW, "return None" at the very end of a function is redundant. The
Python compiler generates "return None" automagically (implicitly!?)
instead of letting you fall off the end of the world. Which book or
tutorial are you using?

BTW #2: "python25.e xe main.py" ?? If you are on Windows, have Python
2.4 as your default setup, and are trialling 2.5: you may like to ask
(in a new thread) about more convenient ways of doing it. Otherwise you
might like to tell what you are up to (in a new thread) so that your
problem can be diagnosed correctly and cured :-)

HTH,
John
BTW#1: I have most of the python books from O'Reilly. I'm sure that
some of them say that its a good idea to use 'return None'. However,
most their examples do not us it. Anyway I find that its useful when
reading my own scripts.

BTW#2: I do not have Python 2.4 installed anymore. Therefore, it is
not a trialling problem.

I thought that it would be NICE to keep the application and the user's
script separate from each other, being that python is so flexible.
However, there seems to be no end to the problems that occur by doing
this. So I will abandon this exercise, since it appears not to be a
very good programming practise.

Thanks,
Jim

Nov 24 '06 #9
This is an interesting question. It almost looks like a case of
event-driven programming, where main is the plug-in and abc is the
framework.
http://eventdrivenpgm.sourceforge.net/

So how about something like this:

############### ### abc.py ############### #####

#------------------------------------------------------------
# an "abstract" function.
# It should be over-ridden in the calling program
#------------------------------------------------------------
def m():
raise AssertionError( "You should have over-ridden abstract function
m()")

def a():
m()
return None
########### main.py ############### #####
import abc # "instantiat e" the framework

# define our our "concrete" function m
def m():
print 'something'
return None

#-----------------------------------------------
# override the "abstract" function abc.m()
# with our own "concrete" function m().
# Comment out this line and see what happens.
#-----------------------------------------------
abc.m = m

# invoke the a() function in the abc framework
abc.a()

############### ############### ############### ####

Nov 24 '06 #10

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

Similar topics

2
3270
by: zapazap | last post by:
Dear Snake Charming Gurus, (Was: http://mail.python.org/pipermail/python-list/2004-January/204454.html) First, a thank you to Tim Golden, Thomas Heller, and Mark Hammond for your earlier help with this problem. I am uncertain about what etiquette calls for, but more on that later. My Objective: I am trying to control the _VMWare Desktop_ application
2
2002
by: Reid Priedhorsky | last post by:
Dear group, I'd have a class defined in one module, which descends from another class defined in a different module. I'd like the superclass to be able to access objects defined in the first module (given an instance of the first class) without importing it. Example of what I'm looking for: <<<file spam.py>>> class Spam(object):
2
4162
by: enrio | last post by:
I need to process the source code associated with the forms outside access, and import the changes back to Access. I find that I can export the source code of a form, but when I subsequently import it, even with no change, I get a message saying the module name is illegal. If the form is named Form_NewParticipant, the export file gets named Form_NewParticipant.cls, and when I reimport it, the error message quotes the name...
2
8103
by: kkrizl | last post by:
I have an Access database that has a few huge tables. It was taking about 20 minutes per table to import them from another application. I used the upsize wizard to put them in a SQL server database. I created a DTS package to import the files and it runs in less than 5 minutes. I'd like to change my macro that used transfer text to import my files to run my DTS package. I've seen several posts regarding this, but I don't understand...
14
2423
by: Greg Copeland | last post by:
I am running python on VxWorks. In the course of operation, a vxworks tasks writes to a reserved area of memory. I need access to this chunk of memory from within python. Initially I thought I could simply access it as a string but a string would reallocate and copy this chunk of memory; which is not something I can have as it would waste a huge amount of memory. We're talking about something like 40MB on a device with limited RAM. I...
13
2353
by: Robin Haswell | last post by:
Hey people I'm an experience PHP programmer who's been writing python for a couple of weeks now. I'm writing quite a large application which I've decided to break down in to lots of modules (replacement for PHP's include() statement). My problem is, in PHP if you open a database connection it's always in scope for the duration of the script. Even if you use an abstraction layer ($db = DB::connect(...)) you can `global $db` and bring...
6
3815
by: fatwallet961 | last post by:
is the main function in python is exact compare to Java main method? all execution start in main which may takes arguments? like the follow example script - def main(argv): ==============================
8
3880
by: Sullivan WxPyQtKinter | last post by:
I am confused by the following program: def f(): print x x=12345 f() result is: 12345
4
5992
by: RgeeK | last post by:
I have a main module doStuff.py and another module utility.py. At the start of doStuff.py I call import utility.py Then I also proceed to initiallize some global variables sName = "" Then I create a class, some methods etc. In one of the methods I assign
0
8590
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8527
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9070
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8947
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8784
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7621
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5806
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2214
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1948
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.