How to Get List of Defined Namespaces

is it possible to get list of defined namespaces

Firstly, to see if a class exists, used class_exists.

Secondly, you can get a list of classes with namespace using get_declared_classes.

In the simplest case, you can use this to find a matching namespace from all declared class names:

function namespaceExists($namespace) {
$namespace .= "\\";
foreach(get_declared_classes() as $name)
if(strpos($name, $namespace) === 0) return true;
return false;
}

Another example, the following script produces a hierarchical array structure of declared namespaces:

<?php
namespace FirstNamespace;
class Bar {}

namespace SecondNamespace;
class Bar {}

namespace ThirdNamespace\FirstSubNamespace;
class Bar {}

namespace ThirdNamespace\SecondSubNamespace;
class Bar {}

namespace SecondNamespace\FirstSubNamespace;
class Bar {}

$namespaces=array();
foreach(get_declared_classes() as $name) {
if(preg_match_all("@[^\\\]+(?=\\\)@iU", $name, $matches)) {
$matches = $matches[0];
$parent =&$namespaces;
while(count($matches)) {
$match = array_shift($matches);
if(!isset($parent[$match]) && count($matches))
$parent[$match] = array();
$parent =&$parent[$match];

}
}
}

print_r($namespaces);

Gives:

Array
(
[FirstNamespace] =>
[SecondNamespace] => Array
(
[FirstSubNamespace] =>
)
[ThirdNamespace] => Array
(
[FirstSubNamespace] =>
[SecondSubNamespace] =>

)
)

Get a List of User-Defined Controls From Current Namespace

With these method i can extract list of all user-defined controls in my project and create an instance of the User-defined Control by it's name on my form.

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();           // Get my CurrentDomain Object
Assembly myType = Assembly.GetExecutingAssembly(); // Extract list of all references in my project
foreach (var assembly in assemblies) // Search for the library that contains namespace that have needed controls
{
if (assembly.GetName().ToString().ToUpper().IndexOf("FIBACONTROLS") > -1)
{
myType = assembly; // Get All types in the library
List<Type> myTps = myType.GetTypes().ToList();

Type mT = null;
foreach (Type selType in myTps) // Find the type that refer to needed user-defined control
{
if (selType.Name.ToUpper() == "FIBACOLORPICKER")
{
mT = selType;
break;
}
}

if (mT == null)
return;

object myInstance = Activator.CreateInstance(mT); // Created an instance on the type
Control mFib = (Control)myInstance; // create the control's object
mFib.Name = "Hahah"; // add the control to my form
mFib.Left = 100;
mFib.Top = 200;
mFib.Visible = true;

this.Controls.Add(mFib);

break;
}
}

I try add some comment to code to describe it.

It work and sure there are some better way to do it, but I'm new one in C# and I am sure that the solution that I found is not the best.

How do I use/get the list element out of the namespace?

The parser returns the namespace with all arguments, you have to access the specific argument. Here is your program with a few commented changes:

import argparse

def get_avg(xyz): # use pep8-style names (get_avg instead of GetAvg)
total = sum(xyz) # use predefined Python functions
return total / len(xyz)

if __name__ == "__main__":
# put all of the main program here so that it is not executed
# if the function is called from elsewhere
parser = argparse.ArgumentParser()
parser.add_argument("-lst", nargs='+', type=int, required=True)
xyz = parser.parse_args().lst # access the needed argument
print(get_avg(xyz))

Python - Get name list of objects of a specified class in the namespace

Here is one function that would return a dataframe with variable names and their respective classes, which makes is filterable as well:

#%%% Objects in namespace

import pandas as pd

def get_env_vars(filter_for=None):
globals_list = globals()
var_list = [k for k in globals_list.keys() if (not k.startswith('_')) & (k not in ['In','Out','get_ipython','exit','quit'])]
var_df = pd.DataFrame({'VarName': var_list})
var_types = []
for z in var_list:
var_types.append(type(globals()[z]))
var_df['VarClass'] = var_types
var_df['VarClass'] = var_df['VarClass'].apply(lambda x: str(x).replace("<class '", "").replace("'>", ""))
if not pd.isna(filter_for):
filter_for = str(filter_for).replace("<class '", "").replace("'>", "") if not isinstance(filter_for, str) else filter_for
var_df = var_df[var_df['VarClass'] == filter_for].reset_index(drop=True)

return var_df

Example:

a = 3
b = [1,2,3]
c = ['a','b']
d = {'a': 1, 'b': 2}

get_env_vars()

>>> OUTPUT
# VarName VarClass
# 0 pd module
# 1 get_env_vars function
# 2 a int
# 3 b list
# 4 c list
# 5 d dict

Get list objects only

get_env_vars('list')

>>> OUTPUT
# VarName VarClass
# 0 b list
# 1 c list

PHP5: get imported namespaces list

Check this class and 'getUseStatements' method.

https://github.com/doctrine/common/blob/2.8/lib/Doctrine/Common/Reflection/StaticReflectionParser.php

Or this class and 'getNamespaceAliases' method.

https://github.com/Andrewsville/PHP-Token-Reflection/blob/master/TokenReflection/ReflectionFileNamespace.php

Or perhaps simplified

https://github.com/vaniocz/type-parser/blob/master/src/UseStatementsParser.php

How can I get all classes within a namespace?

You will need to do it "backwards"; list all the types in an assembly and then checking the namespace of each type:

using System.Reflection;
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return
assembly.GetTypes()
.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
.ToArray();
}

Example of usage:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}

For anything before .Net 2.0 where Assembly.GetExecutingAssembly() is not available, you will need a small workaround to get the assembly:

Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly;
Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}

How to check the existence of a namespace in php

You need to use the entire namespace in the class_exists I believe. So something like:

class_exists('Fetch\\Server')


Related Topics



Leave a reply



Submit