My idea is this, so I want to allow users to send code to a web endpoint.
I would like to grab the modules/imports from the method.
Is that possible?
import pickle
import inspect
def add(x,y):
return x+y
def stringify_method(func):
""""""
return pickle.dumps(func)
print(pickle.loads(stringify_method(add))(1,2))
3
So it returns 3, which is expected.
Now let's say I have something more complicated:
import sys
import pickle
import inspect
import arcpy
import pandas as pd
import numpy as np
def create_array(array):
return np.array(array)
def unpickle_method(func):
""""""
return pickle.dumps(func)
print(pickle.loads(stringify_method(create_array))([1,2,3,4]))
I get the method just fine, but the modules do not follow. How do I get my import numpy as np and pandas, etc..?
Not exactly sure what you are trying to do, but is this helpful?
>>> import sys
>>> import numpy as np
>>> import inspect
>>>
>>> [x[0] for x in inspect.getmembers(sys.modules[__name__], inspect.ismodule)]
['__builtins__', 'inspect', 'np', 'sys']
this gets me 1/2 way there, I need to be able to then grab the import statements from the method: import numpy as np
You could probably reconstruct the statements from this:
>>> [(x, y.__name__) for x,y in inspect.getmembers(sys.modules[__name__], inspect.ismodule)]
[('__builtins__', 'builtins'), ('inspect', 'inspect'), ('np', 'numpy'), ('sys', 'sys')]
(note the ('np', 'numpy') element which tells you import numpy as np)
Related
For instance, define a numpy array with numpy.str_ format and doing the replace operation supported by numpy.char:
import numpy as np
a = np.array(['a-b-c-d','e-f-g-h'],np.str_)
print (np.char.replace(a,'*-','i-'))
The returned result would be ['a-b-c-d', 'e-f-g-h'] but ['i-i-i-d', 'i-i-i-h'] is expected.
Is there any reason to use numpy arrays? You can't use wildcards with numpy.char.replace.
I would suggest to use python lists here and the re module:
l = ['a-b-c-d', 'e-f-g-h']
import re
out = [re.sub('.-', 'i-', i) for i in l]
Output: ['i-i-i-d', 'i-i-i-h']
I have the following code:
def a():
response = rannum(14)
print("Number: " + response)
def rannums(x):
random(x)
it is saying that the object is not callable and I am having a hard time figuring out how to get this to work
rannums calls random, which isn't defined anywhere. a calls rannum, which isn't defined anywhere. Neither a nor rannums are called from anywhere.
Following your comment (" I am basically trying to make a method that will return back a random number with the length of the argument (x)"):
This is copy and paste from ipython interactive shell – you have to retype, if you want to use it
In [1]: from random import choices; from string import digits
In [2]: def get_random_number_with_length(length):
...: return int(''.join(choices(digits, k=length)))
...:
In [3]: get_random_number_with_length(13)
Out[3]: 8677100367579
or maybe better:
In [1]: from random import randint
In [2]: def get_random_number_with_length(length):
...: return randint(10**(length-1), (10**length) -1)
...:
In [3]: get_random_number_with_length(3)
Out[3]: 806
and your error is that you are calling the module random and not the function random.random(x), or do from random import random.
I have two files: in one of them (named myrandom) I have defined a function called spinner that would choose a random number from 1 to 6 and would return its value. In the second file, named main, I have imported the first one (as a module) and have also called the spinner function.
This is the code of the file myrandom:
def spinner():
import random
val = random.choice([1, 2, 3, 4, 5, 6])
return val
And this is the code of main:
import myrandom
x = spinner()
print(x)
My problem is that when I run main, I get the following error message: "NameError: name spinner() is not defined". I don't know why I'm getting this error, since I have other files and modules with similar characteristics that run without problems.
Any idea?
You need to use it like:
import myrandom
x = myrandom.spinner()
Or import directly:
from myrandom import spinner
x = spinner()
Or use star import:
from myrandom import *
x = spinner()
You should import it either like this:
import myrandom
x = myrandom.spinner()
or like this:
from myrandom import spinner
x = spinner()
or like this:
from myrandom import *
x = spinner()
An explanation of the different ways of importing can be found here: Importing modules in Python - best practice
I can't seem to find where the actual name that a module has been bound to is stored. For example:
import re as my_re
print my_re.__name__ # Output is "re," not "my_re"
I would like to be able to get the name that I imported the module as rather than the actual name of the module.
My use case is that I have a function that takes a function object as an argument and needs to be able to determine what name it is bound to. Here is a more thorough example:
import module as my_module
def my_func(in_func):
print in_func.__bound-name__ # Or something to this effect
my_func(my_module.function1) # Should print "my_module.function1"
I would pass the module name as string and then use globals() to fetch the module for use within the function. Suppose you pass 'np' to the function, then globals()['np'] will return the function.
In [22]: import numpy as np
In [23]: def demo(A):
...: a = globals()[A]
...: print(a.array([i for i in range(10)]))
...:
In [24]: demo('np')
[0 1 2 3 4 5 6 7 8 9]
There is no way to do exactly what you want because string my_re is not stored anywhere, it is only a name of a variable. PEP221 which proposed the syntax for import ... as statement explains that the following lines are equal:
import re as my_re
and
import re
my_re = re
del re
Well, this query struck my mind when someone pointed out to me that importing a package using import package gives more code readability. Is this actually true? I mean when using this statement as compared to from package import x, y, z, isn't there any overhead of importing the entire package?
I don't expect any performance difference. Whole package will be loaded anyway.
For example:
# load dirname() function from os.path module
>>> from os.path import dirname
#the os.path.basename() was not imported
>>> basename('/foo/bar.txt')
NameError: name 'basename' is not defined
# however, basename() is already available anyway:
dirname.__globals__['basename']('/foo/bar.txt')
Using the point notation is always less performant than importing a function directly and calling it, because the function does have to be searched in the modules dictionary. This counts for every getattr operation.
For example when appending items to a list:
lst = []
for i in xrange(5000):
lst.append(i ** .5 * 2)
This is faster:
lst = []
append = lst.append
for i in xrange(5000):
append(i ** .5 * 2)
This can make a real heavy difference.
>>> def bad():
... lst = []
... for i in xrange(500):
... lst.append(i ** .5 * 2)
>>> def good():
... lst = []
... append = lst.append
... for i in xrange(500):
... append(i ** .5 * 2)
>>> from timeit import timeit
>>> timeit("bad()", "from __main__ import bad", number = 1000)
0.175249130875
>>> timeit("good()", "from __main__ import good", number = 1000)
0.146750989286
The performance will be same either way. The entire module is compiled, if needed, and the code executed, the first time you import a module, no matter how you import it.
Which is more readable
from os.path import split, join
then a bunch of split and join calls that would accidentally be read as the string methods of the same name, or
import os.path
then referencing them as os.path.split and os.path.join? Here, it's clear they're methods dealing with paths.
Either way, you have to actually load the whole module. Otherwise, things that you imported that depended on other things in the module you didn't import wouldn't work.