Is there a way to get the dictionary containing the global variables in a specific module namespace? It looks that you can achieve it if the module contains at least one function with something like:
import mymodule
d = mymodule.func.__globals__
Is this right?
Is there a more general way? (For instance, how could this be done if the module wouldn't contain any function but only variables?)
I am not expecting a "What are you trying to do with that? There is probably another way of doing it." answer; my question is rather a theoretical one.
I am more interested here by a Python3 answer if it matters.
Just grab use vars which grabs its __dict__ which corresponds to the global scope.
vars(mymodule)
func.__globals__ simply returns this dictionary for you see how:
vars(mymodule) is mymodule.func.__globals__
returns True.
Related
Case I: In some cases, I use the library name to call some set of function i.e, np.median().
Case II: And in some cases, I use the variable name and library name to call another set of function i.e, np.mean(heights) or heights.mean().
In case II, I am able to use both library name and variable name. In case I, only library name works.
My doubt is how to differentiate these tow sets of functions.
If I am wrong in anyway, please clear my thoughts.
(here i am referring to python language)
thank you.
In the first case you’re calling a method (function) of the library. Libraries are usually class instances or collections of functions within a module.
In the second example instead, you’re again calling a function from the module but in this case it returns a ndarray (a numpy list basically) which itself has some methods that can be called on it.
Suppose I have a module PyFoo.py that has a function bar. I want bar to print all of the local variables associated with the namespace that called it.
For example:
#! /usr/bin/env python
import PyFoo as pf
var1 = 'hi'
print locals()
pf.bar()
The two last lines would give the same output. So far I've tried defining bar as such:
def bar(x=locals):
print x()
def bar(x=locals()):
print x
But neither works. The first ends up being what's local to bar's namespace (which I guess is because that's when it's evaluated), and the second is as if I passed in globals (which I assume is because it's evaluated during import).
Is there a way I can have the default value of argument x of bar be all variables in the namespace which called bar?
EDIT 2018-07-29:
As has been pointed out, what was given was an XY Problem; as such, I'll give the specifics.
The module I'm putting together will allow the user to create various objects that represent different aspects of a numerical problem (e.x. various topology definitions, boundary conditions, constitutive models, ect.) and define how any given object interacts with any other object(s). The idea is for the user to import the module, define the various model entities that they need, and then call a function which will take all objects passed to it, make needed adjustments to ensure capability between them, and then write out a file that represents the entire numerical problem as a text file.
The module has a function generate that accepts each of the various types of aspects of the numerical problem. The default value for all arguments is an empty list. If a non-empty list is passed, then generate will use those instances for generating the completed numerical problem. If an argument is an empty list, then I'd like it to take in all instances in the namespace that called generate (which I will then parse out the appropriate instances for the argument).
EDIT 2018-07-29:
Sorry for any lack of understanding on my part (I'm not that strong of a programmer), but I think I might understand what you're saying with respect to an instance being declared or registered.
From my limited understanding, could this be done by creating some sort of registry dataset (like a list or dict) in the module that will be created when the module is imported, and that all module classes take this registry object in by default. During class initialization self can be appended to said dataset, and then the genereate function will take the registry as a default value for one of the arguments?
There's no way you can do what you want directly.
locals just returns the local variables in whatever namespace it's called in. As you've seen, you have access to the namespace the function is defined in at the time of definition, and you have access to the namespace of the function itself from within the function, but you don't have access to any other namespaces.
You can do what you want indirectly… but it's almost certainly a bad idea. At least this smells like an XY problem, and whatever it is you're actually trying to do, there's probably a better way to do it.
But occasionally it is necessary, so in case you have one of those cases:
The main good reason to want to know the locals of your caller is for some kind of debugging or other introspection function. And the way to do introspection is almost always through the inspect library.
In this case, what you want to inspect is the interpreter call stack. The calling function will be the first frame on the call stack behind your function's own frame.
You can get the raw stack frame:
inspect.currentframe().f_back
… or you can get a FrameInfo representing it:
inspect.stack()[1]
As explained at the top of the inspect docs, a frame object's local namespace is available as:
frame.f_locals
Note that this has all the same caveats that apply to getting your own locals with locals: what you get isn't the live namespace, but a mapping that, even if it is mutable, can't be used to modify the namespace (or, worse in 2.x, one that may or may not modify the namespace, unpredictably), and that has all cell and free variables flattened into their values rather than their cell references.
Also, see the big warning in the docs about not keeping frame objects alive unnecessarily (or calling their clear method if you need to keep a snapshot but not all of the references, but I think that only exists in 3.x).
I want to make a map containing various attributes of a single item and share it across several modules. The most obvious answer is to use a string, but since the map will be used across several modules, I don't want maintainers to have to know about all existing attributes. For example, if two modules want something associated with "color", they shouldn't clobber each other by accidentally picking the same name.
A few ideas I've thought of which don't work:
1) Strings, integer keys: As said above, this isn't easily extensible.
2) Create of a particular class, use id(): I thought it would work to make a Key() class, for example, but this doesn't work in the case of modules imported from two different places. For example, you might want to make the "color" attribute described above as follows:
color = Key()
This doesn't work if you do
# module named foo
bar = Key()
import foo
id(foo.bar) == id(bar)
3) Look at the stack trace to see where the Key was created and use that as part of the identifier. Definitely wouldn't want to use line number, as this would be too brittle. Using module and name of item fails in the case of the main module, though. For example:
in foo.py:
key = Key() # will be named foo.py-key
elsewhere, in bar.py:
import foo
foo.key # will be named /Users/person/foo.py-key
Thanks! Any advice is appreciated.
Use a string, but prefix it with the current module name. Then you won't get any collisions.
key = __name__ + '.color'
how can i get a list of all built-in objects in python recursively?
what i'm exactly searching for is a function like dir() which returns a list of objects instead of strings.
also, why does "dir(__builtins__.print)" fail in python's interactive mode with a syntax error?
thanks for your answers!
A dictionary of key value pairs: __builtins__.__dict__
Only the objects: __builtins__.__dict__.values()
These will give you a list of a dictionary you can iterate over to your hearts content!
EDIT: Not recommended, see below comment and that users answer
import __builtin__
__builtin__.__dict__.values()
Note that there is also, rather confusingly, an object called __builtins__. Don't use it; it might not work consistently:
CPython implementation detail: Most modules have the name __builtins__ (note the 's') made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
As for __builtins__.print giving a syntax error, it's because print is a statement, not a function. Python won't let you use the print keyword except as part of a print statement.
As to your second question, it's because in Python 2, print is not a function or any kind of object, but a statement. See this previous question.
I have two functions like the following:
def fitnesscompare(x, y):
if x.fitness>y.fitness:
return 1
elif x.fitness==y.fitness:
return 0
else: #x.fitness<y.fitness
return -1
that are used with 'sort' to sort on different attributes of class instances.
These are used from within other functions and methods in the program.
Can I make them visible everywhere rather than having to pass them to each object in which they are used?
Thanks
The best approach (to get the visibility you ask about) is to put this def statement in a module (say fit.py), import fit from any other module that needs access to items defined in this one, and use fit.fitnesscompare in any of those modules as needed.
What you ask, and what you really need, may actually be different...:
as I explained in another post earlier today, custom comparison functions are not the best way to customize sorting in Python (which is why in Python 3 they're not even allowed any more): rather, a custom key-extraction function will serve you much better (future-proof, more general, faster). I.e., instead of calling, say
somelist.sort(cmp=fit.fitnesscompare)
call
somelist.sort(key=fit.fitnessextract)
where
def fitnessextract(x):
return x.fitness
or, for really blazing speed,
import operator
somelist.sort(key=operator.attrgetter('fitness'))
Defining a function with def makes that function available within whatever scope you've defined it in. At module level, using def will make that function available to any other function inside that module.
Can you perhaps post an example of what is not working for you? The code you've posted appears to be unrelated to your actual problem.