I would like to write a module that provides some mathematical functions
on top of those defined in math, cmath etc. but I would like to make it
work with "any" type that overloads the math functions.
Thus, I would like to write:
module_f.py
----
def f(x):
""" Compute sqrt of x """
return sqrt(x) from math import * import module_f module_f.f(3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "module_f.p y", line 2, in f
return sqrt(x)
NameError: global name 'sqrt' is not defined
I understand why sqrt is not in scope, but my question is: what is the
best way to do this?
Here is one fairly ugly solution:
module_g.py
-----------
def g(x,math):
return math.sqrt(x)
import math, cmath, module_g module_g.g(2,ma th)
1.4142135623730 951 module_g.g(-2,cmath)
1.4142135623730 951j
I am sure there is a better way of doing this that makes use of the
type of the argument (Dynamical scoping would solve the
problem but we don't want to go there...). Note that the following
function would work fine
def f(x):
return abs(x)
because of the special member __abs__ attached to the type. There is no
corresponding member for sqrt, sin etc.
What is the "proper" pythonic way to do this?
Michael.
Mar 3 '06
13 3794
On Fri, 3 Mar 2006, david mugnai wrote:
[snip] If I don't misunderstood the problem, you can define an "init" method for your module_g
(code not tested)
module_g.py -----------
_functions = {} def init(mathmodule ): _function['sqrt'] = getattr(mathmod ule, 'sqrt', None)
def _get(name): try: return _functions[name] except KeyError: raise TypeError("you have to initialize module_g")
def sqrt(x): return _get('sqrt')(x)
main.py -------
import math import module_g
module_g.init(m ath) print module_g.sqrt(2 )
Thanks, this gets me close. Is there anything really bad about the
following? It works exactly as I would like, but I don't want to get in
trouble down the road:
module_f
--------
import math as my_math
def set_math(custom _math):
globals()['my_math'] = custom_math
def f(x):
return my_math.sqrt(x) import module_f module_f.f(2)
1.4142135623730 951 import cmath module_f.set_ma th(cmath) module_f.f(2j)
(1+1j)
Or, if one wants to use the "from __ import *" form:
from math import *
def set_math(custom _math):
globals().updat e(custom_math._ _dict__)
def f(x):
return sqrt(x)
Michael
On Fri, 3 Mar 2006, Steven D'Aprano wrote: ... you can do this:
import my_module my_module.set_e nvironment("mat h") # or cmath, or numeric, or whatever
Your my_module will be like this:
# Warning: untested code. ENVIRON = None # global variables sometimes have their uses
def f(x): if ENVIRON is None: raise ValueError("Uni nitialised module!") # or use a custom exception return ENVIRON.sqrt(x)
def set_environment (name): global ENVIRON ENVIRON = __import__(name )
Does this help?
Yes. However, this raises a question: Is this any different than
directly modifying the globals, or is it just syntactic sugar.
import math as my_math
def set_environment (name):
globals()['ENVIRON'] = __import__(name )
Thanks,
Michael.
Michael McNeil Forbes wrote: Is there anything really bad about the following? It works exactly as I would like, but I don't want to get in trouble down the road:
module_f -------- import math as my_math
def set_math(custom _math): globals()['my_math'] = custom_math
This seems clearer to me:
def set_math(custom _math):
global my_math
my_math = custom_math
Or, if one wants to use the "from __ import *" form:
from math import *
def set_math(custom _math): globals().updat e(custom_math._ _dict__)
This will cause interesting trouble if custom_math doesn't implement all
the functions you use from math.
Kent
On Sat, 04 Mar 2006 23:07:12 -0800, Michael McNeil Forbes wrote: On Fri, 3 Mar 2006, Steven D'Aprano wrote:
... you can do this:
import my_module my_module.set_e nvironment("mat h") # or cmath, or numeric, or whatever
Your my_module will be like this:
# Warning: untested code. ENVIRON = None # global variables sometimes have their uses
def f(x): if ENVIRON is None: raise ValueError("Uni nitialised module!") # or use a custom exception return ENVIRON.sqrt(x)
def set_environment (name): global ENVIRON ENVIRON = __import__(name )
Does this help? Yes. However, this raises a question: Is this any different than directly modifying the globals, or is it just syntactic sugar.
The keyword "global" instructs Python to make all references to the
following name come from the global namespace. It is the correct way to
do it (but not necessarily the *only* correct way, or *always* the
correct way). In something as tiny as your example:
def set_environment (name): globals()['ENVIRON'] = __import__(name )
it may not make any practical difference which method you use. But in
larger, more complex code, you are creating a rod for your own back. Try
running these three functions, and explain the difference in their
behaviour.
def f1():
global parrot
parrot = 3
parrot += 1
print "parrot is %d" % parrot
def f2():
globals()["parrot"] = 3
globals()["parrot"] += 1
print "parrot is %d" % parrot
def f3():
globals()["parrot"] = 3
parrot += 1
print "parrot is %d" % parrot
Directly modifying the globals is playing around with Python's internals.
You are allowed to do that, and sometimes it is the right thing to do,
otherwise Guido wouldn't have made globals() writable.
E.g. you have code where you want -- heaven knows why -- a name to refer
to both a local and a global variable. This will work:
def func():
x = 5 # x is local
globals()['x'] = 3 # but this x is global
I don't know whether writing to globals() is guaranteed to work for all
variants of Python (CPython, Jython, PyPy, IronPython ... ) or if it is
likely to change in Python 3. But even if modifying globals() is
officially allowed, it still has a whiff of the sort of code-smell that
Joel Spolsky talks about : http://www.joelonsoftware.com/articles/Wrong.html
In my opinion, manipulating globals() is one of those things that ring
warning bells in my head. It might not be *wrong*, exactly, but I'll want
to pay extra attention to any function that does that.
--
Steven. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Equis Uno |
last post by:
Hi there,
I just figured out how to use __add__() to overload the "+" operator
for objects of a class.
According to googel queries, I see other functions available to me for
overloading other operators:
__mul__(), __sub__(), ...
|
by: pauldepstein |
last post by:
I am writing a program which will use the ceiling and floor of square
roots.
If a positive integer is an exact square (and is not overly huge), does
sqrt return an integer-valued real?
Or might the sqrt function tell me that, for example, sqrt(1024) =
31.99999999999999999999999
You might say "try it". The problem is that I can't try infinitely
|
by: Aric |
last post by:
Hi,
I'm a bit new to programming in general, really I've just picked it up
as a hobby, and so I've started by reading "Practical C Programming"
by Steve Oualline. Things have been going fine in the book until I
reached exercise 6-1 in the book, which reads:
Write a program to find the square of the distance between two points.
(For a more advanced problem, find the actual distance. This problem
involves using the standard function...
|
by: Vladimir Granitsky |
last post by:
Hi guys,
Please, look at the code below and try to step into it. The compiled code calls the loosely typed method public void Method1(object o) !?!?
Am I right that C# compiler does wrong overload resolution ?
I've used parameters of type object and string here, just to illustrate the problem. Really I have a bit more deep inheritance graph, and the things get more interesting if the strongly typed overload is like override public void...
|
by: Thomas Zhu |
last post by:
hello all,
n is an 32bit-integer, how to calculate
sqrt(n)
I know high(n) is the the value, but how to use bit operation to
implement this function.
thanks in advance.
yours
Yin
| |
by: siggi |
last post by:
Hi all,
this is a newbie question on :
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on
win32
PC with WinXP
In
http://www.python.org/doc/2.3.5/lib/module-math.html
I read:
|
by: copx |
last post by:
I am writing a program which uses sqrt() a lot. A historically very slow
function but I read on CPUs with SSE support this is actually fast. Problem:
C's sqrt() (unlike C++ sqrt()) is defined to work on doubles only, and early
versions of SSE did not support double precision. The CPU requirement
"something with at least first generation SEE support" (everything from
P3/Athlon XP and up) is acceptable for me. However, requiring a CPU which...
|
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= |
last post by:
Hi,
Why does Math.Sqrt() only accept a double as a parameter? I would think
it would be just as happy with a decimal (or int, or float, or ....). I can
easily convert back and forth, but I am interested in what is going on behind
the scenes and if there is some aspect of decimals that keep them from being
used in this calculation.
Thanks!
Ethan
Ethan Strauss Ph.D.
|
by: Blue sky |
last post by:
Hi ,I think the follow program is right in logical But why the
compiler output :"square:declared identifier"
#include<stdio.h>
#include<math.h>
int main()
{
double x1;
|
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...
|
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...
| |
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |