Use of . in python? [duplicate] - python

This question already has answers here:
Understanding the dot notation in python
(2 answers)
Closed 5 years ago.
I am struggling to explain the use of the dot. I thought it might be another way of multiplying variables but get an error when I try run such a code.
I can't explain what it is doing exactly, take this code for example:
import random
for i in range(100):
value = random.randint(1, 10)
print(value)
I understand what the code does but in line 3 I am confused by random.randint what is the dot doing here? randint is not defined or imported so how does the program know what is being asked of it?
An brief explanation of the above code would be nice but a good explanation of the use of the dot in python would be appreciated.

You use dot for 3 main reasons:
Accessing members of a module: a module is simply a python file, and members can be variables, functions, classes and so on.
Accessing modules within a package: a package is a directory containing a__init__ module. Some packages are nested and contain inner packages. You have to reach the innermost and then the module. For both you use dot syntax.
And at last, accessing members of a class, for example method (functions) fields (variables) and so on.
In your above code random is a Python module and you are accessing its function randint.

In Python, the dot operator is used to access attributes of objects.
In your example, think of the module imported "random" as an object which has various functions like randint, shuffle, etc
So, when you say "random.randint()", you are accessing the function "randint" from the module "random"

The dot here is used to resolve scope. The randint() function is inside the random module. The dot here tells the interpreter where to look for the named function/ data member.
Apart from this, the dot is also used to access functions and data members from an object reference.
For example:
op = object.function()
Here, the function() is being accessed using the reference of object.
Also you can access inner modules using . like this:
import module.submodule
More information here: https://www.codecademy.com/en/forum_questions/5170307264a7402d9a0012f5

random is a package and randint() is its method. Dot notation here works just like it does in any other language. It's used to access the
randint property of random module.

Related

Calling library functions in python

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.

How can I find the builtin function code? [duplicate]

This question already has answers here:
Finding the source code for built-in Python functions?
(8 answers)
Closed 2 years ago.
I just want to take a look builtin function code. Because I'm a beginner on Python and I think some source code can give me very useful instruction. I made some test code as follows and I did 'Ctrl+click' on 'join' with PyCharm IDE.
zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
And then cursor points builtin.py module's join function, but there is empty code. There is only an explanation. How does this operate? Where is the real code?
def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__
"""
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
"""
pass
'builtin.py' path is : C:\Users\admin.PyCharmCE2019.3\system\python_stubs\542861396\builtins.py
str.join() is implemented in C, specifically in unicodeobject.c at unicode_join.
"How can I find the source code for builtin functions and objects" doesn't have a great answer. See Finding the source code for built-in Python functions? for some overviews of how CPython is laid out. While some of Python's standard library is written in Python (this sits in lib/), you'll find that builtins and some performance-sensitive components of the standard library have a C implementation. The former resides in objects/, and the latter in modules/.

How to get the globals from a module namespace?

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.

Storing a list of modules

I recently learned of the __ import__ function and found that I could store a module in a variable, so I was thinking of making a list of modules and then calling the appropriate one when necessary.
So I might have three modules test1, test2, test3, each containing a single function "print_hello" that simply prints "hello, I'm [module name]"
At runtime, I would call some function to import those modules and put them in a list.
Then I would pick a random number between 0 and 2 inclusively, pick that module from the list, and print hello.
#run function to import each module, resulting in the following list
#my_modules = [module1, module2, module3]
#generate some number i
chosen_module = my_modules[i]
chosen_module.print_hello()
Is this acceptable coding practice? Or are there any reasons that would discourage this?
I use this sort of approach in some of my testing code. I want to test output from one version of a module against a different versions of the same module. Being able to iterate over different module instances makes the code cleaner.
But this sort of code is the exception to the rule. It's very infrequently that this approach is the cleanest solution to a problem.

Python: how to make a function visible throughout a program

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.

Categories