comp.lang.python - 25 new messages in 7 topics - digest
comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en
comp.lang.python@googlegroups.com
Today's topics:
* isinstance(False, int) - 6 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/27beadbbfad9243d?hl=en
* Slicing [N::-1] - 3 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/add9aa920b55eacc?hl=en
* Evaluate my first python script, please - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/24bfa00b428f868f?hl=en
* A "scopeguard" for Python - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/8c752e871801c223?hl=en
* start function in new process - 5 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/87262d1edfe35a69?hl=en
* Conditional based on whether or not a module is being used - 7 messages, 5
authors
http://groups.google.com/group/comp.lang.python/t/ee22c223fa73a429?hl=en
* imap vs map - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6feec3c038799c6d?hl=en
==============================================================================
TOPIC: isinstance(False, int)
http://groups.google.com/group/comp.lang.python/t/27beadbbfad9243d?hl=en
==============================================================================
== 1 of 6 ==
Date: Fri, Mar 5 2010 10:30 am
From: MRAB
mk wrote:
> >>> isinstance(False, int)
> True
> >>>
> >>> isinstance(True, int)
> True
>
> Huh?
>
> >>>
> >>> issubclass(bool, int)
> True
>
> Huh?!
>
Python didn't have Booleans originally, 0 and 1 were used instead. When
bool was introduced it was made a subclass of int so that existing code
wouldn't break.
== 2 of 6 ==
Date: Fri, Mar 5 2010 10:32 am
From: mk
Arnaud Delobelle wrote:
>>>> 1 == True
> True
>>>> 0 == False
> True
>
> So what's your question?
Well nothing I'm just kind of bewildered: I'd expect smth like that in
Perl, but not in Python.. Although I can understand the rationale after
skimming PEP 285, I still don't like it very much.
Regards,
mk
== 3 of 6 ==
Date: Fri, Mar 5 2010 10:54 am
From: Jean-Michel Pichavant
Steven D'Aprano wrote:
> On Fri, 05 Mar 2010 18:14:16 +0100, mk wrote:
>
>
>>>>> isinstance(False, int)
>>>>>
>> True
>> >>>
>> >>> isinstance(True, int)
>> True
>>
>> Huh?
>>
>
> Yes. Do you have an actual question?
>
>
>
>> >>> issubclass(bool, int)
>> True
>>
>> Huh?!
>>
>
> Exactly.
>
> Bools are a late-comer to Python. For historical and implementation
> reasons, they are a subclass of int, because it was normal for people to
> use 0 and 1 as boolean flags, and so making False == 0 and True == 1 was
> the least likely to break code.
>
> E.g. back in the day, you would have something like:
>
> {2:None}.has_key(2) -> 1
>
> So folks would do:
>
> print "The key is", ["missing", "present"][d.has_key(key)]
>
> Which still works even now that has_key returns True or False rather than
> 1 or 0.
>
>
>
Despite there are good reasons for bool to be int, the newcomer 'wtf'
reaction at first glance is legitimate.
Starting python from scratch, booleans would have not been a subclass of
int (just guessing though), 'cause it makes no sense from a design POV.
Booleans are not ints, 0 does not *mean* False and veracity is not
quantification.
JM
== 4 of 6 ==
Date: Fri, Mar 5 2010 11:01 am
From: Rolando Espinoza La Fuente
On Fri, Mar 5, 2010 at 2:32 PM, mk <mrkafk@gmail.com> wrote:
> Arnaud Delobelle wrote:
>
>>>>> 1 == True
>>
>> True
>>>>>
>>>>> 0 == False
>>
>> True
>>
>> So what's your question?
>
> Well nothing I'm just kind of bewildered: I'd expect smth like that in Perl,
> but not in Python.. Although I can understand the rationale after skimming
> PEP 285, I still don't like it very much.
>
So, the pythonic way to check for True/False should be:
>>> 1 is True
False
>>> 0 is False
False
instead of ==, right?
Regards,
Rolando
== 5 of 6 ==
Date: Fri, Mar 5 2010 11:46 am
From: mk
Rolando Espinoza La Fuente wrote:
> Doesn't have side effects not knowing that False/True are ints?
It does, in fact I was wondering why my iterator didn't work until I
figured issubclass(bool, int) is true.
Regards,
mk
== 6 of 6 ==
Date: Fri, Mar 5 2010 11:54 am
From: Steven D'Aprano
On Fri, 05 Mar 2010 15:01:23 -0400, Rolando Espinoza La Fuente wrote:
> On Fri, Mar 5, 2010 at 2:32 PM, mk <mrkafk@gmail.com> wrote:
>> Arnaud Delobelle wrote:
>>
>>>>>> 1 == True
>>>
>>> True
>>>>>>
>>>>>> 0 == False
>>>
>>> True
>>>
>>> So what's your question?
>>
>> Well nothing I'm just kind of bewildered: I'd expect smth like that in
>> Perl, but not in Python.. Although I can understand the rationale after
>> skimming PEP 285, I still don't like it very much.
>>
>>
> So, the pythonic way to check for True/False should be:
>
>>>> 1 is True
> False
Why do you need to check for True/False?
But if you need to, yes, that is one way. Another would be:
isinstance(flag, bool)
But generally, you can use any object as a flag without caring if it is
actually True or False.
--
Steven
==============================================================================
TOPIC: Slicing [N::-1]
http://groups.google.com/group/comp.lang.python/t/add9aa920b55eacc?hl=en
==============================================================================
== 1 of 3 ==
Date: Fri, Mar 5 2010 10:33 am
From: Mensanator
On Mar 5, 12:01 pm, Joan Miller <pelok...@gmail.com> wrote:
> What does a slice as [N::-1] ?
Starts at position N and returns all items to the start of the
list in reverse order.
>
> It looks that in the first it reverses the slice and then it shows
> only N items, right?
Wrong. It shows N+1 items. Remember, counting starts from 0.
>
> Could you add an example to get the same result without use `::` to
> see it more clear?
for i in range(8,-1,-1):print(a[i],end=' ')
although I doubt this is more clear.
>
> Thanks in advance
== 2 of 3 ==
Date: Fri, Mar 5 2010 10:52 am
From: Mensanator
On Mar 5, 12:28 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 05 Mar 2010 18:12:05 +0000, Arnaud Delobelle wrote:
> >>>> l = range(10)
> >>>> l
> > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> >>>> l[7::-1]
> > [7, 6, 5, 4, 3, 2, 1, 0]
> >>>> [l[i] for i in range(7, -1, -1)]
> > [7, 6, 5, 4, 3, 2, 1, 0]
>
> Where does the first -1 come from? Slices are supposed to have default
> values of 0 and len(seq):
The only way to get a 0 from a reverse range() is to have a bound of
-1.
>
> >>> l[7::1]
> [7, 8, 9]
> >>> [l[i] for i in range(7, len(l), 1)]
> [7, 8, 9]
> >>> [l[i] for i in range(7, len(l), -1)]
>
> []
>
> I don't believe the actual behaviour is documented anywhere.
Well, it's implied. If the stopping bound in a reverse range()
is greater than the starting bound, you get an empty return.
>
> --
> Steven
== 3 of 3 ==
Date: Fri, Mar 5 2010 11:10 am
From: Robert Kern
On 2010-03-05 12:28 PM, Steven D'Aprano wrote:
> On Fri, 05 Mar 2010 18:12:05 +0000, Arnaud Delobelle wrote:
>
>>>>> l = range(10)
>>>>> l
>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>>> l[7::-1]
>> [7, 6, 5, 4, 3, 2, 1, 0]
>>>>> [l[i] for i in range(7, -1, -1)]
>> [7, 6, 5, 4, 3, 2, 1, 0]
>
> Where does the first -1 come from? Slices are supposed to have default
> values of 0 and len(seq):
Rather, they have 0 and len(seq), respectively, when the step is positive, and
len(seq)-1 and -1 when the step is negative.
>>>> l[7::1]
> [7, 8, 9]
>>>> [l[i] for i in range(7, len(l), 1)]
> [7, 8, 9]
>>>> [l[i] for i in range(7, len(l), -1)]
> []
>
>
> I don't believe the actual behaviour is documented anywhere.
True, I don't think it is.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
==============================================================================
TOPIC: Evaluate my first python script, please
http://groups.google.com/group/comp.lang.python/t/24bfa00b428f868f?hl=en
==============================================================================
== 1 of 1 ==
Date: Fri, Mar 5 2010 10:50 am
From: Pete Emerson
On Mar 5, 10:19 am, "sjdevn...@yahoo.com" <sjdevn...@yahoo.com> wrote:
> On Mar 5, 10:53 am, Pete Emerson <pemer...@gmail.com> wrote:
>
>
>
>
>
> > Thanks for your response, further questions inline.
>
> > On Mar 4, 11:07 am, Tim Wintle <tim.win...@teamrubber.com> wrote:
>
> > > On Thu, 2010-03-04 at 10:39 -0800, Pete Emerson wrote:
> > > > I am looking for advice along the lines of "an easier way to do this"
> > > > or "a more python way" (I'm sure that's asking for trouble!) or
> > > > "people commonly do this instead" or "here's a slick trick" or "oh,
> > > > interesting, here's my version to do the same thing".
>
> > > (1) I would wrap it all in a function
>
> > > def main():
> > > # your code here
>
> > > if __name__ == "__main__":
> > > main()
>
> > Is this purely aesthetic reasons, or will I appreciate this when I
> > write my own modules, or something else?
>
> Suppose the above code is in mymodule.py. By wrapping main() you can:
> 1. Have another module do:
> import mymodule
> ... (so some stuff, perhaps munge sys.argv)
> mymodule.main()
> 2. If mymodule has a small function in it, someone else can import it
> and call that function
> 3. You can run pylint, pychecker and other source-code checkers that
> need to be able to import your module to check it (I wouldn't be
> surprised if recent versions of one or the other of those don't
> require imports, and some checkers like pyflakes certainly don't).
> 4. You can easily have a unit tester call into the module
>
> etc.
>
> > > (2) PEP8 (python style guidelines) suggests one import per line
>
> > > (3) I'd use four spaces as tab width
>
> +1 on both; it's good to get into the habit of writing standard-
> looking Python code.
Agreed, noted, and appreciated, with the caveat that using spaces
instead of tabs might border on an emacs vs. vi flamewar in some
circles. I personally will use spaces going forward.
==============================================================================
TOPIC: A "scopeguard" for Python
http://groups.google.com/group/comp.lang.python/t/8c752e871801c223?hl=en
==============================================================================
== 1 of 2 ==
Date: Fri, Mar 5 2010 11:13 am
From: "Alf P. Steinbach"
* Mike Kent:
> On Mar 4, 8:04 pm, Robert Kern <robert.k...@gmail.com> wrote:
>
>> No, the try: finally: is not implicit. See the source for
>> contextlib.GeneratorContextManager. When __exit__() gets an exception from the
>> with: block, it will push it into the generator using its .throw() method. This
>> raises the exception inside the generator at the yield statement.
>
> Wow, I just learned something new. My understanding of context
> managers was that the __exit__ method was guaranteed to be executed
> regardless of how the context was left. I have often written my own
> context manager classes, giving them the __enter__ and __exit__
> methods. I had mistakenly assumed that the @contextmanager decorator
> turned a generator function into a context manager with the same
> behavior as the equivalent context manager class. Now I learn that,
> no, in order to have the 'undo' code executed in the presence of an
> exception, you must write your own try/finally block in the generator
> function.
>
> This raises the question in my mind: What's the use case for using
> @contextmanager rather than wrapping your code in a context manager
> class that defines __enter__ and __exit__, if you still have to
> manager your own try/finally block?
Robert Kern and Steve Howell have already given given good answers.
As it happened this was news to me also, because I'm not that well-versed in
Python and it seems contrary to the purpose of providing a simpler way to write
a simple init-cleanup wrapper.
But additionally, if you want that, then you can define it, e.g.
<code>
# Py3
def simplecleanup( generator_func ):
class SimpleCleanup:
def __init__( self, *args, **kwargs ):
self.generator = generator_func( *args, **kwargs )
def __enter__( self ):
self.generator.send( None )
return self
def __exit__( self, x_type, x_obj, x_traceback ):
try:
self.generator.send( x_obj ) # x_obj is None if no exception
except StopIteration:
pass # Expected
return SimpleCleanup
@simplecleanup
def hello_goodbye( name ):
print( "Hello, {}!".format( name ) )
yield
print( "Goodbye {}!".format( name ) )
try:
with hello_goodbye( "Mary" ):
print( "Talk talk talk..." )
raise RuntimeError( "Offense" )
except:
pass
print()
@simplecleanup
def sensitive_hello_goodbye( name ):
print( "Hello, {}!".format( name ) )
x = yield
if x is not None:
print( "Uh oh, {}!".format( x ) )
print( "Good day {}!".format( name ) )
else:
print( "C u, {}!".format( name ) )
try:
with sensitive_hello_goodbye( "Jane" ):
print( "Talk talk talk..." )
raise RuntimeError( "Offense" )
except:
pass
</code>
Cheers,
- Alf
== 2 of 2 ==
Date: Fri, Mar 5 2010 11:34 am
From: "Alf P. Steinbach"
* Steve Howell:
> On Mar 3, 7:10 am, "Alf P. Steinbach" <al...@start.no> wrote:
>> For C++ Petru Marginean once invented the "scope guard" technique (elaborated on
>> by Andrei Alexandrescu, they published an article about it in DDJ) where all you
>> need to do to ensure some desired cleanup at the end of a scope, even when the
>> scope is exited via an exception, is to declare a ScopeGuard w/desired action.
>>
>> The C++ ScopeGuard was/is for those situations where you don't have proper
>> classes with automatic cleanup, which happily is seldom the case in good C++
>> code, but languages like Java and Python don't support automatic cleanup and so
>> the use case for something like ScopeGuard is ever present.
>>
>> For use with a 'with' statement and possibly suitable 'lambda' arguments:
>>
>> <code>
>> class Cleanup:
>> def __init__( self ):
>> self._actions = []
>>
>> def call( self, action ):
>> assert( is_callable( action ) )
>> self._actions.append( action )
>>
>> def __enter__( self ):
>> return self
>>
>> def __exit__( self, x_type, x_value, x_traceback ):
>> while( len( self._actions ) != 0 ):
>> try:
>> self._actions.pop()()
>> except BaseException as x:
>> raise AssertionError( "Cleanup: exception during cleanup" ) from
>> </code>
>>
>> I guess the typical usage would be what I used it for, a case where the cleanup
>> action (namely, changing back to an original directory) apparently didn't fit
>> the standard library's support for 'with', like
>>
>> with Cleanup as at_cleanup:
>> # blah blah
>> chdir( somewhere )
>> at_cleanup.call( lambda: chdir( original_dir ) )
>> # blah blah
>>
>> Another use case might be where one otherwise would get into very deep nesting
>> of 'with' statements with every nested 'with' at the end, like a degenerate tree
>> that for all purposes is a list. Then the above, or some variant, can help to
>> /flatten/ the structure. To get rid of that silly & annoying nesting. :-)
>>
>> Cheers,
>>
>> - Alf (just sharing, it's not seriously tested code)
>
> Hi Alf, I think I understand the notion you're going after here. You
> have multiple cleanup steps that you want to defer till the end, and
> there is some possibility that things will go wrong along the way, but
> you want to clean up as much as you can. And, of course, flatter is
> better.
>
> Is this sort of what you are striving for?
>
> class Cleanup:
> def __init__( self ):
> self._actions = []
>
> def call( self, action ):
> self._actions.append( action )
>
> def __enter__( self ):
> return self
>
> def __exit__( self, x_type, x_value, x_traceback ):
> while( len( self._actions ) != 0 ):
> try:
> self._actions.pop()()
> except BaseException as x:
> raise AssertionError( "Cleanup: exception during
> cleanup" )
>
> def clean_the_floor():
> print('clean the floor')
>
> def carouse(num_bottles, accident):
> with Cleanup() as at_cleanup:
> at_cleanup.call(clean_the_floor)
> for i in range(num_bottles):
> def take_down(i=i):
> print('take one down', i)
> at_cleanup.call(take_down)
> if i == accident:
> raise Exception('oops!')
> print ('put bottle on wall', i)
>
> carouse(10, None)
> carouse(5, 3)
He he.
I think you meant:
> def carouse(num_bottles, accident):
> with Cleanup() as at_cleanup:
> at_cleanup.call(clean_the_floor)
> for i in range(num_bottles):
> def take_down(i=i):
> print('take one down', i)
> if i == accident:
> raise Exception('oops!')
> print ('put bottle on wall', i)
> at_cleanup.call(take_down)
I'm not sure. It's interesting & fun. But hey, it's Friday evening.
Regarding the "clean the floor", Marginean's original ScopeGuard has a 'dismiss'
method (great for e.g. implementing transactions). There's probably also much
other such functionality that can be added.
The original use case for Cleanup, I just posted this in case people could find
it useful, was a harness for testing that C++ code /fails/ as it should,
<url: http://pastebin.com/NK8yVcyv>, where Cleanup is used at line 479.
Some discussion of that in Usenet message and associated thread
<hmmcdm$p1i$1@news.eternal-september.org>, "Unit testing of expected failures --
what do you use?" in [comp.lang.c++].
Another similar approach was discussed by Carlo Milanesi in <url:
http://www.drdobbs.com/cpp/205801074>, but he supplied this reference after I'd
done the above. Mainly the difference is that he defines a custom mark-up
language with corresponding source preprocessing, while I use the ordinary C++
preprocessor. There are advantages and disadvantages to both approaches.
Cheers,
- Alf
==============================================================================
TOPIC: start function in new process
http://groups.google.com/group/comp.lang.python/t/87262d1edfe35a69?hl=en
==============================================================================
== 1 of 5 ==
Date: Fri, Mar 5 2010 11:21 am
From: "wongjoekmeu@yahoo.com"
Hello all,
I would like to run a python function completely in a new process. For
example I have a parent process. That parent process needs to start a
child process in which the function is called. After the child process
is finished however I want that the child process should stop and then
only the parent process remain. When I start the function I want to
pass arguments also which include a function reference. I tried
os.fork() as I need to write it in linux. However it seems like the
child process remain alive. I discovered this when I loop through the
function. I see that the child process continue with the loop and
starts again a new grand child untill the loop is finished. See code
snippet. f() is the function I want to run in a new process. It got as
one of the input a refence to a function c().
Function g() I called in a loop for 3 times. Now it seems that when
child process get started in the function g() it return to the loop
and it calls g() itself and starts itself a nwe child process. I do
not want thant. I want the child process to perform the function f()
and just finished. Does anyone know how I can achieve this ?
def c():
print "function c"
def f(a,b, d):
# function I want to run in a new child process
print a, b
d()
def g():
pidID = os.fork()
if pidID == 0:
# child do something here
f(2,3,c)
else:
# parent do something here
print "Parent
for i in range(3):
g()
== 2 of 5 ==
Date: Fri, Mar 5 2010 11:40 am
From: "Martin P. Hellwig"
On 03/05/10 19:21, wongjoekmeu@yahoo.com wrote:
<cut os.fork problem>
Any specific reason why threading.Thread or multiprocessing is not
suitable to solve your problem?
--
mph
== 3 of 5 ==
Date: Fri, Mar 5 2010 11:45 am
From: "wongjoekmeu@yahoo.com"
On 5 mrt, 20:40, "Martin P. Hellwig" <martin.hell...@dcuktec.org>
wrote:
> On 03/05/10 19:21, wongjoek...@yahoo.com wrote:
> <cut os.fork problem>
> Any specific reason why threading.Thread or multiprocessing is not
> suitable to solve your problem?
>
> --
> mph
Because I got a memory leak in my function f(). It uses scipy, numpy,
pylab, and I am not planning to solve the memory leak because its too
complicated. So I thought of just calling the function then when it is
finished the process is gone and all memory is released. With
threading I don't think I would solve this problem. I am not sure
though.
== 4 of 5 ==
Date: Fri, Mar 5 2010 12:02 pm
From: "Martin P. Hellwig"
On 03/05/10 19:45, wongjoekmeu@yahoo.com wrote:
> On 5 mrt, 20:40, "Martin P. Hellwig"<martin.hell...@dcuktec.org>
> wrote:
>> On 03/05/10 19:21, wongjoek...@yahoo.com wrote:
>> <cut os.fork problem>
>> Any specific reason why threading.Thread or multiprocessing is not
>> suitable to solve your problem?
>>
>> --
>> mph
>
> Because I got a memory leak in my function f(). It uses scipy, numpy,
> pylab, and I am not planning to solve the memory leak because its too
> complicated. So I thought of just calling the function then when it is
> finished the process is gone and all memory is released. With
> threading I don't think I would solve this problem. I am not sure
> though.
I would be surprised if you can't do the same with
subprocess/multiprocessing, since you seem to know how to identify the
memory leak it shouldn't be a problem scripting out a test to see if it
works this way. I would be interested though in your findings.
--
mph
== 5 of 5 ==
Date: Fri, Mar 5 2010 12:09 pm
From: "wongjoekmeu@yahoo.com"
On 5 mrt, 21:02, "Martin P. Hellwig" <martin.hell...@dcuktec.org>
wrote:
> On 03/05/10 19:45, wongjoek...@yahoo.com wrote:
>
>
>
> > On 5 mrt, 20:40, "Martin P. Hellwig"<martin.hell...@dcuktec.org>
> > wrote:
> >> On 03/05/10 19:21, wongjoek...@yahoo.com wrote:
> >> <cut os.fork problem>
> >> Any specific reason why threading.Thread or multiprocessing is not
> >> suitable to solve your problem?
>
> >> --
> >> mph
>
> > Because I got a memory leak in my function f(). It uses scipy, numpy,
> > pylab, and I am not planning to solve the memory leak because its too
> > complicated. So I thought of just calling the function then when it is
> > finished the process is gone and all memory is released. With
> > threading I don't think I would solve this problem. I am not sure
> > though.
>
> I would be surprised if you can't do the same with
> subprocess/multiprocessing, since you seem to know how to identify the
> memory leak it shouldn't be a problem scripting out a test to see if it
> works this way. I would be interested though in your findings.
>
> --
> mph
I can't use multiprocessing module since it comes only with python 2.6
and I am bound to python2.4. But subprocess does exist in python2.4,
but the question now is, how do I achieve that ? Any example ?
==============================================================================
TOPIC: Conditional based on whether or not a module is being used
http://groups.google.com/group/comp.lang.python/t/ee22c223fa73a429?hl=en
==============================================================================
== 1 of 7 ==
Date: Fri, Mar 5 2010 11:24 am
From: Pete Emerson
In a module, how do I create a conditional that will do something
based on whether or not another module has been loaded?
Suppose I have the following:
import foo
import foobar
print foo()
print foobar()
########### foo.py
def foo:
return 'foo'
########### foobar.py
def foobar:
if foo.has_been_loaded(): # This is not right!
return foo() + 'bar' # This might need to be foo.foo() ?
else:
return 'bar'
If someone is using foo module, I want to take advantage of its
features and use it in foobar, otherwise, I want to do something else.
In other words, I don't want to create a dependency of foobar on foo.
My failed search for solving this makes me wonder if I'm approaching
this all wrong.
Thanks in advance,
Pete
== 2 of 7 ==
Date: Fri, Mar 5 2010 11:39 am
From: Pete Emerson
On Mar 5, 11:24 am, Pete Emerson <pemer...@gmail.com> wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
>
> Suppose I have the following:
>
> import foo
> import foobar
>
> print foo()
> print foobar()
>
> ########### foo.py
> def foo:
> return 'foo'
>
> ########### foobar.py
> def foobar:
> if foo.has_been_loaded(): # This is not right!
> return foo() + 'bar' # This might need to be foo.foo() ?
> else:
> return 'bar'
>
> If someone is using foo module, I want to take advantage of its
> features and use it in foobar, otherwise, I want to do something else.
> In other words, I don't want to create a dependency of foobar on foo.
>
> My failed search for solving this makes me wonder if I'm approaching
> this all wrong.
>
> Thanks in advance,
> Pete
Aha, progress. Comments appreciated. Perhaps there's a different and
more conventional way of doing it than this?
def foobar():
import sys
if 'foomodule' in sys.modules.keys():
import foomodule
return foomodule.foo() + 'bar'
else:
return 'bar'
== 3 of 7 ==
Date: Fri, Mar 5 2010 11:51 am
From: Steve Holden
Pete Emerson wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
>
> Suppose I have the following:
>
> import foo
> import foobar
>
> print foo()
> print foobar()
>
> ########### foo.py
> def foo:
> return 'foo'
>
> ########### foobar.py
> def foobar:
> if foo.has_been_loaded(): # This is not right!
> return foo() + 'bar' # This might need to be foo.foo() ?
> else:
> return 'bar'
>
> If someone is using foo module, I want to take advantage of its
> features and use it in foobar, otherwise, I want to do something else.
> In other words, I don't want to create a dependency of foobar on foo.
>
> My failed search for solving this makes me wonder if I'm approaching
> this all wrong.
>
> Thanks in advance,
> Pete
One way would be
if "foo" in sys.modules:
# foo was imported
However that won't get you all the way, since sys.modules["foo"] will be
set even if the importing statement was
from foo import this, that, the_other
So you might want to add
foo = sys.modules["foo"]
inside the function.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
== 4 of 7 ==
Date: Fri, Mar 5 2010 11:53 am
From: Steven D'Aprano
On Fri, 05 Mar 2010 11:24:44 -0800, Pete Emerson wrote:
> In a module, how do I create a conditional that will do something based
> on whether or not another module has been loaded?
try:
import foo
except ImportError:
foo = None
def function():
if foo:
return foo.func()
else:
do_something_else()
Or, alternatively:
try:
import foo
except ImportError:
import alternative_foo as foo # This better succeed!
def function():
return foo.func()
--
Steven
== 5 of 7 ==
Date: Fri, Mar 5 2010 11:52 am
From: Steve Holden
Pete Emerson wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
>
> Suppose I have the following:
>
> import foo
> import foobar
>
> print foo()
> print foobar()
>
By the way, the above statements are never going to work, because
modules aren't callable. Maybe you want
print foo.foo()
print foobar.foobar()
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
== 6 of 7 ==
Date: Fri, Mar 5 2010 11:57 am
From: MRAB
Pete Emerson wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
>
> Suppose I have the following:
>
> import foo
> import foobar
>
> print foo()
> print foobar()
>
> ########### foo.py
> def foo:
> return 'foo'
>
> ########### foobar.py
> def foobar:
> if foo.has_been_loaded(): # This is not right!
> return foo() + 'bar' # This might need to be foo.foo() ?
> else:
> return 'bar'
>
> If someone is using foo module, I want to take advantage of its
> features and use it in foobar, otherwise, I want to do something else.
> In other words, I don't want to create a dependency of foobar on foo.
>
> My failed search for solving this makes me wonder if I'm approaching
> this all wrong.
>
Look for its name in sys.modules, for example:
'foo' in sys.modules
== 7 of 7 ==
Date: Fri, Mar 5 2010 12:06 pm
From: "Martin P. Hellwig"
On 03/05/10 19:24, Pete Emerson wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
<cut>>
> If someone is using foo module, I want to take advantage of its
> features and use it in foobar, otherwise, I want to do something else.
> In other words, I don't want to create a dependency of foobar on foo.
>
> My failed search for solving this makes me wonder if I'm approaching
> this all wrong.
>
> Thanks in advance,
> Pete
Hmm how about the module is available, just not imported yet, I would
assume that you still would like to use the module then.
Perhaps playing around with the imp module might get you what you mean
instead of what you say?
--
mph
==============================================================================
TOPIC: imap vs map
http://groups.google.com/group/comp.lang.python/t/6feec3c038799c6d?hl=en
==============================================================================
== 1 of 1 ==
Date: Fri, Mar 5 2010 11:55 am
From: mk
Hello everyone,
I re-wrote more "slowly" an example at the end of
http://wordaligned.org/articles/essential-python-reading-list
This example finds anagrams in the text file.
====
from itertools import groupby, imap
from operator import itemgetter
from string import ascii_lowercase, ascii_uppercase, punctuation,
maketrans, translate
data = open(r"c:\temp\words.txt", "rt").read()
trtable = maketrans(ascii_uppercase, ascii_lowercase)
words = translate(data, trtable, deletions = punctuation)
words = list(set(words.split()))
sw = sorted(words, key=sorted)
gb = groupby(sw, sorted)
print map(list, imap(itemgetter(1), gb))
===
words.txt:
===
Word Aligned
three
space sensitive programming
Feed Logo tins
Essential Python post Reading List
stop course there
times isnt
capes
===
Now, when I execute above, it works:
[['capes', 'space'], ['aligned'], ['reading'], ['essential'],
['programming'], ['course'], ['feed'], ['word'], ['there', 'three'],
['sensitive'], ['times'], ['logo'], ['python'], ['list'], ['isnt',
'tins'], ['stop', 'post']]
However, when I change the last line to:
print map(list, map(itemgetter(1), gb))
It stops working:
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ['post']]
Why? I was under impression that the only difference between map and
imap is that imap returns iterator allowing to produce a list, while map
returns equivalent list?
Regards,
mk
==============================================================================
You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.
To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en
To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com
To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en
To report abuse, send email explaining the problem to abuse@googlegroups.com
==============================================================================
Google Groups: http://groups.google.com/?hl=en
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home